Skip to content

Commit 48a0690

Browse files
authored
Merge pull request #54 from dsprenkels/master
Harden stable implementation of black_box
2 parents 8cf1aa9 + 7958922 commit 48a0690

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

README.md

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,6 @@ To prevent the latter possibility, when using the `nightly` feature
1919
from the optimizer, by passing it through an inline assembly block. For more
2020
information, see the _About_ section below.
2121

22-
When not using the `nightly` feature, there is no protection against b). This
23-
is unfortunate, but is at least no worse than C code, and has the advantange
24-
that if a suitable black box is stabilized, we will be able to transparently
25-
enable it with no changes to the external interface).
26-
2722
```toml
2823
[dependencies.subtle]
2924
version = "2.1"

src/lib.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,23 @@ fn black_box(mut input: u8) -> u8 {
155155
#[inline(never)]
156156
fn black_box(input: u8) -> u8 {
157157
debug_assert!((input == 0u8) | (input == 1u8));
158-
// We don't have access to inline assembly or test::black_box or ...
158+
// We don't have access to inline assembly or test::black_box, so we use the fact that
159+
// volatile values will never be elided to register values.
159160
//
160-
// Bailing out, hopefully the compiler doesn't use the fact that `input` is 0 or 1.
161-
input
161+
// Note: Rust's notion of "volatile" is subject to change over time. While this code may break
162+
// in a non-destructive way in the future, it is better than doing nothing.
163+
164+
unsafe {
165+
// Optimization barrier
166+
//
167+
// Unsafe is ok, because:
168+
// - &input is not NULL;
169+
// - size of input is not zero;
170+
// - u8 is neither Sync, nor Send;
171+
// - u8 is Copy, so input is always live;
172+
// - u8 type is always properly aligned.
173+
core::ptr::read_volatile(&input as *const u8)
174+
}
162175
}
163176

164177
impl From<u8> for Choice {

0 commit comments

Comments
 (0)