Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,4 @@
- [29: Safety of `boxed`](./challenges/0029-boxed.md)
- [30: Safety and Correctness of Integer Logarithms](./challenges/0030-integer-logarithms.md)
- [31: Verify the safety of `BinaryHeap` functions](./challenges/0031-binary-heap.md)
- [36: Verify the safety of `core::slice::rotate`](./challenges/0036-slice-rotate.md)
127 changes: 127 additions & 0 deletions doc/src/challenges/0036-slice-rotate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Challenge 36: Verify the safety of `core::slice::rotate`

- **Status:** *Open*
- **Solution:** *Option field to point to the PR that solved this challenge.*
- **Tracking Issue:** [#773](https://github.com/model-checking/verify-rust-std/issues/773)
- **Start date:** *2026/11/17*
- **Reward:** *TBD*

-------------------

## Goal

Verify the safety of the in-place slice rotation implementation in
[rotate.rs](https://github.com/model-checking/verify-rust-std/blob/main/library/core/src/slice/rotate.rs),
which backs `<[T]>::rotate_left` and `<[T]>::rotate_right`, for arbitrary rotation sizes and for generic
`T`, and verify that it actually rotates.

## Motivation

`rotate_left` and `rotate_right` are safe, stable (and now `const`) slice methods used throughout the
standard library and by user code. All of their work is done by one private unsafe function,
`ptr_rotate`, which picks one of three raw-pointer algorithms at run time according to the size of `T`
and the split point:

- `ptr_rotate_memmove`, which parks the smaller half in a 256-byte `MaybeUninit` stack buffer and uses
`ptr::copy` / `ptr::copy_nonoverlapping`;
- `ptr_rotate_gcd`, the juggling algorithm, which walks the cycles of the permutation
`i -> i + right (mod left + right)` with `read` / `replace` / `write`, computing the number of cycles
(the gcd) as a side effect of the first cycle;
- `ptr_rotate_swap`, the Gries--Mills block-swap algorithm, which repeatedly applies
`ptr::swap_nonoverlapping` to adjacent blocks whose sizes are the residues of a Euclidean algorithm.

The safety argument at each pointer operation rests on arithmetic facts that are written only in prose:
that the gcd walk never leaves `[0, left + right)` (the `[long-safety-expl]` comments), that the value
computed as a side effect really is the cycle count and so bounds the starting offsets of the remaining
cycles, and that the block swaps stay inside the range while `mid` walks back and forth. A mistake of one
in any of these reads or writes an element outside the slice that safe code handed to `rotate_left`, or
duplicates or loses an element of a type with a destructor. We know of no soundness bug reported against
this file; the case for the challenge is that the argument is subtle, serves a safe API, and has no
machine-checked statement.

## Description

`ptr_rotate(left, mid, right)` rotates the range `[mid - left, mid + right)` so that the element at
`mid` becomes the first. It returns at once for zero-sized `T` and for a zero split. Otherwise, unless
the crate is built with `optimize_for_size`, it uses the memmove strategy when the smaller side fits in
the stack buffer (`min(left, right) <= size_of::<[usize; 32]>() / size_of::<T>()`), else the gcd strategy
when `left + right < 24` or `size_of::<T>() > size_of::<[usize; 4]>()`, else the block-swap strategy.
Its only callers are `rotate_left` and `rotate_right` in `core::slice`, which pass the length checks of
the safe API. The file also contains a `const`-compatible `const_min`.

The following are out of scope:

- The rotation-like block moves inside `core::slice::sort` (they do not call this file).
- `rotate_left` / `rotate_right` panic behavior for a split larger than the length (it is a plain
`assert!` before any unsafe code; a proof of `ptr_rotate` under its precondition covers the unsafe
part of both methods).
- Performance of the strategy choice.

No existing challenge lists a function of `core::slice::rotate`. The primitives it uses
(`ptr::copy_nonoverlapping`, `ptr::swap_nonoverlapping`, `<*mut T>::replace`) are targets of
[Challenge 2](0002-intrinsics-memory.md) and [Challenge 3](0003-pointer-arithmentic.md); their
verification is not repeated here.

### Assumptions

- `core::ptr` intrinsics and `core::mem::MaybeUninit` may be assumed correct, and their existing
verified contracts may be reused. Deductive tools may rely on their own specifications of these
primitives and on Rust's documented array/tuple layout guarantees (in particular the size and
alignment of the stack buffer `([usize; 32], [T; 0])`).
- The safety precondition of each function is the one in its `# Safety` documentation: the range
`[mid - left, mid + right)` is valid for reading and writing elements of `T`. For non-zero-sized `T`
this includes the usual requirement that the byte size of the range does not exceed `isize::MAX`.
A contract may add a side condition only where the function is in fact never called without it and
the condition is recorded next to the contract; in particular the gcd and block-swap strategies are
only ever called with `left > 0`, `right > 0` and non-zero-sized `T`, and the memmove strategy only
when the smaller side fits in its buffer.
- Proofs must cover every strategy, including the branches taken when the crate is built with
`optimize_for_size` (in that configuration only the block-swap strategy runs, so proving each
strategy under its own precondition covers both configurations).
- No user code runs during a rotation (`T` is moved, never dropped or cloned by the rotation itself),
so unwinding need not be modeled. Dropping the rotated elements afterwards must still be safe: no
element may be duplicated or lost.

### Success Criteria

Write and prove a safety contract for each of the following unsafe functions, with the precondition
above (restricted as recorded for the three strategies), stating that the range is still valid for
reading and writing afterwards:

| Function | Location |
|---------|---------|
| `ptr_rotate` | `core::slice::rotate` |
| `ptr_rotate_memmove` | `core::slice::rotate` |
| `ptr_rotate_gcd` | `core::slice::rotate` |
| `ptr_rotate_swap` | `core::slice::rotate` |

Prove the absence of undefined behavior in all four functions for arbitrary `left` and `right`
(unbounded: no fixed bound on `left + right` other than the one in the precondition), including the
early returns for zero-sized `T` and for `left == 0` or `right == 0`, all three dispatch branches of
`ptr_rotate`, and both the default and `optimize_for_size` configurations. `const_min` is safe code
with no unsafe operations; its result is the smaller of its arguments, which the dispatch proof may
rely on.

The verification must hold for generic `T` (what satisfies this clause is to be decided in
[issue #734](https://github.com/model-checking/verify-rust-std/issues/734)). In particular it must
cover zero-sized `T`, sizes that do and do not divide the memmove buffer, alignments above `usize`,
elements larger than the buffer, types with a validity invariant (such as `NonZero`), and types with a
destructor, for each of which the safety argument takes a different branch somewhere in the file.

Prove functional correctness of the rotation for arbitrary `left` and `right` across all three
strategies and `ptr_rotate`: after `ptr_rotate(left, mid, right)`, the element at each position `j`
of `[mid - left, mid + right)` is the element previously at position `(j + left) mod (left + right)`
of that range (equivalently, `append(drop(left, xs), take(left, xs))`), with every element of `T`
preserved (no element duplicated, lost, invalidated, or leaked).

### List of UBs

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):

* Accessing (loading from or storing to) a place that is dangling or based on a misaligned pointer.
* Invoking undefined behavior via compiler intrinsics.
* Reading from uninitialized memory except for padding or unions.
* Producing an invalid value

Note: All solutions to verification challenges need to satisfy the criteria established in the [challenge book](../general-rules.md)
in addition to the ones listed above.
Loading