Skip to content

Commit 3f8a13b

Browse files
tautschnigkiro-agentfeliperodri
authored
Use byte-wise memchr under Kani to cut symbolic execution cost (#628)
Profiling `ffi::c_str::verify::check_to_bytes` (via CBMC `--program-only` SSA attribution) showed that a third of all SSA steps came from a single function: `slice::memchr::memchr_aligned`'s runtime arm — the word-at-a-time scan behind slice `contains`, which `CStr`'s safety invariant and contract clauses evaluate repeatedly. Symbolically, the word-optimized scan is ~13× more expensive than the semantically equivalent byte-wise `memchr_naive` loop while providing zero benefit: there is no word-level parallelism in symbolic execution. This PR routes `memchr` to `memchr_naive` under `cfg(kani)`. Measured effect (Kani 152c6a8c + CBMC 6.10.0, `--jobs=4`): the full `ffi::c_str` suite runs 12/12 in 2:13 wall; `check_to_bytes` alone drops from 3:28 wall / 170 s CBMC solve to 14.6 s solve, and from 606 s to 21 s solve when dependency contracts are asserted. `check_from_bytes_until_nul` needs its unwind bound raised from 32 to 33 (the byte-wise loop needs one more iteration than the word scan); it now solves in 3.1 s where the old bound's comment recorded 33.1 s. Since the CStr harnesses were the only indirect verification coverage of `memchr_aligned`'s unsafe word-sized reads, the PR adds an equivalence harness checking `memchr_aligned` against `memchr_naive` on all inputs up to 24 bytes (documenting the `len >= 2*USIZE_BYTES` precondition its caller establishes), so the optimized implementation stays verified. All `str::` and `slice::memchr` harnesses (15 + 13) pass with this change. By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses. --------- Co-authored-by: Kiro <kiro-agent@users.noreply.github.com> Co-authored-by: Felipe R. Monteiro <rms.felipe@gmail.com>
1 parent d106d2f commit 3f8a13b

2 files changed

Lines changed: 47 additions & 6 deletions

File tree

‎library/core/src/ffi/c_str.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -901,7 +901,7 @@ mod verify {
901901

902902
// pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError>
903903
#[kani::proof]
904-
#[kani::unwind(32)] // 7.3 seconds when 16; 33.1 seconds when 32
904+
#[kani::unwind(33)]
905905
fn check_from_bytes_until_nul() {
906906
const MAX_SIZE: usize = 32;
907907
let string: [u8; MAX_SIZE] = kani::any();

‎library/core/src/slice/memchr.rs‎

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
33

44
use crate::intrinsics::const_eval_select;
5+
#[cfg(kani)]
6+
use crate::kani;
57

68
const LO_USIZE: usize = usize::repeat_u8(0x01);
79
const HI_USIZE: usize = usize::repeat_u8(0x80);
@@ -23,12 +25,22 @@ const fn contains_zero_byte(x: usize) -> bool {
2325
#[inline]
2426
#[must_use]
2527
pub const fn memchr(x: u8, text: &[u8]) -> Option<usize> {
26-
// Fast path for small slices.
27-
if text.len() < 2 * USIZE_BYTES {
28-
return memchr_naive(x, text);
29-
}
28+
// For Kani, always use the byte-by-byte loop: it is semantically
29+
// equivalent to the word-at-a-time `memchr_aligned` (see comment there)
30+
// but symbolically executes with a fraction of the cost, and `memchr` is
31+
// reached from many contract clauses (e.g. `CStr::is_safe`).
32+
#[cfg(kani)]
33+
return memchr_naive(x, text);
34+
35+
#[cfg(not(kani))]
36+
{
37+
// Fast path for small slices.
38+
if text.len() < 2 * USIZE_BYTES {
39+
return memchr_naive(x, text);
40+
}
3041

31-
memchr_aligned(x, text)
42+
memchr_aligned(x, text)
43+
}
3244
}
3345

3446
#[inline]
@@ -159,3 +171,32 @@ pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
159171
// Find the byte before the point the body loop stopped.
160172
text[..offset].iter().rposition(|elt| *elt == x)
161173
}
174+
175+
#[cfg(kani)]
176+
#[unstable(feature = "kani", issue = "none")]
177+
pub mod verify {
178+
use super::*;
179+
180+
/// With `cfg(kani)`, `memchr` always takes the `memchr_naive` path (see
181+
/// comment there), so the word-at-a-time `memchr_aligned` is no longer
182+
/// exercised by the harnesses of its callers (e.g. `CStr`). This harness
183+
/// keeps `memchr_aligned` covered by checking it against `memchr_naive`
184+
/// for all inputs up to MAX_SIZE, including all UB checks in its unsafe
185+
/// word-sized reads.
186+
///
187+
/// MAX_SIZE needs to exceed 2 * size_of::<usize>() so that the aligned
188+
/// word-scanning loop is reachable (smaller inputs take an early naive
189+
/// path inside `memchr_aligned`'s compile-time branch counterpart).
190+
#[kani::proof]
191+
#[kani::unwind(26)]
192+
pub fn check_memchr_aligned_equiv_naive() {
193+
const MAX_SIZE: usize = 24;
194+
let x: u8 = kani::any();
195+
let text: [u8; MAX_SIZE] = kani::any();
196+
let slice = kani::slice::any_slice_of_array(&text);
197+
// Implicit precondition of `memchr_aligned`, established by its only
198+
// caller `memchr`: short slices are handled by `memchr_naive` there.
199+
kani::assume(slice.len() >= 2 * USIZE_BYTES);
200+
assert_eq!(memchr_aligned(x, slice), memchr_naive(x, slice));
201+
}
202+
}

0 commit comments

Comments
 (0)