# Volatile and sensitive memory

**URL:** <https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188>\
**Category:** language design\
**Created:** [February 18, 2016, 8:37pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188 "2016-02-18T20:37:52Z")\
**Posts on this page:** 20\
**Page:** 3

<div class="post-metadata">

**Author:** ![huon](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/huon/32/3698_2.png) [@huon](https://internals.rust-lang.org/u/huon)\
**Post date:** [February 22, 2016, 11:57am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/41 "2016-02-22T11:57:36Z")

</div>

> [@ahmedcharles](#):
>
> As for VolatileCell, I don't see how it is useful given that the address of the volatile variable can't be controlled. I suppose one could transmute a memory location into a VolatileCell and then it could work, but then why have a new method that accepts T by value? I suppose I just don't understand.

One can have a `VolatileCell` in a `static` that gets placed at a specific significant address (with a `const fn` `new` method). That said, the `new` method isn't the interesting part: unless you're making a point I don't understand, the core here is `get` and `set` since they're the gate-keepers of the actual volatile reads/writes (i.e. one can ignore the `new` methods entirely).

---

<div class="post-metadata">

**Author:** ![ahmedcharles](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ahmedcharles/32/4041_2.png) [@ahmedcharles](https://internals.rust-lang.org/u/ahmedcharles)\
**Post date:** [February 23, 2016, 11:47am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/42 "2016-02-23T11:47:55Z")

</div>

Now I’m curious… what’s the syntax for placing a static at a specific address at run time?

---

<div class="post-metadata">

**Author:** ![huon](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/huon/32/3698_2.png) [@huon](https://internals.rust-lang.org/u/huon)\
**Post date:** [February 23, 2016, 12:05pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/43 "2016-02-23T12:05:05Z")

</div>

There’s no syntax in Rust itself, and so I believe the easiest way at the moment is by running a linker manually and using its support for that sort of thing, e.g. [http://stackoverflow.com/a/19831133/1256624](http://stackoverflow.com/a/19831133/1256624) or [http://mcuoneclipse.com/2012/11/01/defining-variables-at-absolute-addresses-with-gcc/](http://mcuoneclipse.com/2012/11/01/defining-variables-at-absolute-addresses-with-gcc/) in C, with `#[link_section = "..."]` the Rust equivalent to the `section("...")` attribute. (This is obviously somewhat unfortunate, but I suspect almost all cases when one has specific memory addresses of interest are bare metal/embedded situations, where one is probably going to have to be interacting with a linker directly anyway.)

---

<div class="post-metadata">

**Author:** ![Zoxc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zoxc/32/4000_2.png) [@Zoxc](https://internals.rust-lang.org/u/Zoxc)\
**Post date:** [February 24, 2016, 11:57am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/44 "2016-02-24T11:57:25Z")

</div>

Does UnsafeCell guarantee that no accesses are generated into it without actual accesses in the code?

---

<div class="post-metadata">

**Author:** ![Amanieu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/amanieu/32/4095_2.png) [@Amanieu](https://internals.rust-lang.org/u/Amanieu)\
**Post date:** [February 24, 2016, 7:51pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/45 "2016-02-24T19:51:56Z")

</div>

> [@Zoxc](#):
>
> Does UnsafeCell guarantee that no accesses are generated into it without actual accesses in the code?

No

---

<div class="post-metadata">

**Author:** ![nikomatsakis](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nikomatsakis/32/5410_2.png) [@nikomatsakis](https://internals.rust-lang.org/u/nikomatsakis)\
**Post date:** [March 2, 2016, 3:50pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/46 "2016-03-02T15:50:33Z")

</div>

Sorry for dropping out of this thread. I've just read the entire thing and wanted to throw in my two cents.

**First, a meta-comment: I don't believe we can expect a "definitive answer" to the questions that @briansmith is raising at this time, because the "Rust memory model" is not yet defined.** As @arielb1 says, we "ought to" -- and we are working on settling it, but it is a complex equation with a lot of variables, and frankly one with an unclear priority. As a starting point, I've been going through all the discussion threads and so forth and trying to gather up a list of important examples, along with collecting discussion. This can be found in this repository:

> **[rust-lang/rust-memory-model](https://github.com/rust-lang/rust-memory-model)**
>
> Collecting examples and information to help design a memory model for Rust. - rust-lang/rust-memory-model

At the moment, these examples are culled directly from discussion threads. I do plan to go back over them and try to eliminate duplicates / simplify / coallesce. Then I hope we can evaluate some various proposals and see how they "score" related to the examples. I've added in the various examples from this discussion as well.

All that being said, @briansmith needs to write some code **today**. For the time being, we have de facto adopted LLVM's "volatile access model". Personally, I am pretty comfortable with this, and I would not expect major changes. This implies to me that @huon's example of a [volatile wrapper](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/6) is currently correct (as @huon points out, the `VolatileCell` example is not, though for a reason that is orthogonal to volatility).

The key point is that the compiler will not randomly introduce reads of an `&T` -- it will only introduce reads that it can prove _may_ happen at some point in the future. This is (I believe) true even with the derefenceable attribute. So if you have a field `x: T` and it is only ever read via a `volatile-read`, then the compiler will not introduce spurious, non-volatile reads of it. I believe this is the LLVM's (and hence Rust's) **current** semantics (@briansmith seems to have [come to the same conclusion](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/33)).

So TL;DR I think @briansmith should adopt a volatile wrapper like @huon's example. It will work fine today. It may need some adjustment in the future, but that seems fairly unlikely, and should not affect consumers of the API.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [March 25, 2019, 8:25am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/47 "2019-03-25T08:25:48Z")

</div>

Closed on March 25, 2019, 8:25am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [May 20, 2019, 2:42pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/48 "2019-05-20T14:42:02Z")

</div>

Opened on May 20, 2019, 2:42pm UTC



---

<div class="post-metadata">

**Author:** ![RalfJung](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ralfjung/32/2415_2.png) [@RalfJung](https://internals.rust-lang.org/u/RalfJung)\
**Post date:** [May 21, 2019, 8:32am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/49 "2019-05-21T08:32:03Z")

</div>

> [@nikomatsakis](#):
>
> The key point is that the compiler will not randomly introduce reads of an `&T` – it will only introduce reads that it can prove _may_ happen at some point in the future. This is (I believe) true even with the derefenceable attribute. So if you have a field `x: T` and it is only ever read via a `volatile-read` , then the compiler will not introduce spurious, non-volatile reads of it. I believe this is the LLVM’s (and hence Rust’s) **current** semantics (@briansmith seems to have [come to the same conclusion](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/33)).

For anyone reading this thread as a reference for `volatile`: this no longer reflects our current understanding of how `volatile` and `dereferencable` interact. See [this Github thread](https://github.com/rust-lang/unsafe-code-guidelines/issues/33) for the latest discussion, and in particular this quote by @hanna-kruppe:

> > If an lvalue is accessed through only volatile loads, LLVM will not add accesses that aren't volatile.
> 
> I've not seen this guarantee stated anywhere in LLVM docs. It seems reasonable on its own but the `dereferencable` attribute may very well throw a wrench in it. Without that attribute, LLVM may not assume it can insert loads from a pointer, so it won't insert any unless it sees a pre-existing load, which can be extended (with a bit of care) to take the volatile-ness of the existing loads into account and not take pre-existing _volatile_ loads as permission to insert new loads. On the other hand, by definition `dereferencable` means it's OK to insert any loads from the address anywhere.
> 
> While one may be tempted to say "OK but don't do that if there are volatile accesses", that's not really possible. The transformation that wants to insert a load may not be able to see the volatile accesses (e.g., because they are in another function), or there may not even be any accesses at all to the location (e.g., if the source program creates a `&VolatileCell` but doesn't use it).

So, the current thinking is that you should not have references pointing to MMIO memory as the compiler is allowed to introduce spurious reads. But if you just want to zero-out memory and make sure the writes really happen, this should not affect you. (Please don't reply here but continue in [the other thread](https://github.com/rust-lang/unsafe-code-guidelines/issues/33)).

---

<div class="post-metadata">

**Author:** ![briansmith](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/briansmith/32/1306_2.png) [@briansmith](https://internals.rust-lang.org/u/briansmith)\
**Post date:** [May 22, 2019, 6:17am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/50 "2019-05-22T06:17:46Z")

</div>

> [@RalfJung](#):
>
> So, the current thinking is that you should not have references pointing to MMIO memory as the compiler is allowed to introduce spurious reads.

The idea that Rust code should avoid using references in circumstances, when the semantics of Rust references are the primary reason many people are using Rust instead of C++, seems absurd. This seems like a case where a bunch of locally-reasonable small decisions add up to a bad decision.

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 22, 2019, 9:01am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/51 "2019-05-22T09:01:32Z")

</div>

> [@briansmith](#):
>
> The idea that Rust code should avoid using references in circumstances, when the semantics of Rust references are the primary reason many people are using Rust instead of C++, seems absurd. This seems like a case where a bunch of locally-reasonable small decisions add up to a bad decision.

I don't think Rusts's — nor llvm's — machine model of their input IR provide many guarantees with regards to timing. The number of inserted spurios reads is only remotely connected to this, as even such fundamental things as

> `let a = b*c;`

are not guaranteed to be constant time. The compiler is allowed to insert _arbitrary new branches_ checking and depending on the inputs and outputs of such a value computation (e.g. may check that both smaller than half the register size, then find some clever way to exploits this). References are, in some sense, exactly the same; only their value provides reasoning about the values in their pointed-to memory as well.

**And that is a good thing**. Without it, the compiler wouldn't be allowed to do most of the awesome optimizations it does. Vectorizing an array copy for example depends on the alignment of the input, hence introduce a conditional head and tail when the source or target array is not aligned, and do a faster copy of the aligned inner part. But then the timing of the code leaks information about the alignment and I see no reason why this should not be allowed or wanted in generic code. And I think this is example is enough to conclude that `*a = b` is not nearly constant time for every type (that includes implicit assignment from `return`), and then should it be for some arbitrary subset?

So references yield non-constant time semantics completely independent of assumptions of non-spurious reads, they are _not_ special because of it. And I think this demonstrates something else: How is the compiler supposed to know which inputs are safe to leak and not? For a generic `xor` combinator it may be safe to leak the length when it does not depend on any secret inputs in any of the usages. However, leaking bits of the address is risky. There is however no inherent difference. I think anything short of checking the _fully optimized_ llvm output (maybe you don't need to go down to machine code) against a manually compiled definition of safe inputs will fall short of a constant time guarantee. The concern is somewhat different than the concern of MMIO.

---

<div class="post-metadata">

**Author:** ![RalfJung](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ralfjung/32/2415_2.png) [@RalfJung](https://internals.rust-lang.org/u/RalfJung)\
**Post date:** [May 22, 2019, 9:23am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/52 "2019-05-22T09:23:55Z")

</div>

> [@briansmith](#):
>
> The idea that Rust code should avoid using references in circumstances, when the semantics of Rust references are the primary reason many people are using Rust instead of C++, seems absurd. This seems like a case where a bunch of locally-reasonable small decisions add up to a bad decision.

First of all, I can see many other reasons to use Rust over C++, from enums to a type system providing safe abstractions to traits. References are not the primary reason IMO.

But hyperboles aside, the alternative here would be to pessimize 99.99% of the code (everyone using references that do _not_ point to MMIO memory) just to make MMIO memory (an extremely niche use case) slightly less unsafe (but still unsafe) to work with. _That_ seems absurd to me. That also violates the zero-cost principle "you don't pay for what you don't use", as _everyone_ would be paying for MMIO all the time. This is inherently a case where there is a conflict between high-level optimizations and low-level control.

Several solutions have been proposed in the [GItHub thread](https://github.com/rust-lang/unsafe-code-guidelines/issues/33), some can be implemented as a library today (such as creating a custom newtype around raw pointers and using that as "MMIO pointer type"), some require some more design and an RFC.

---

<div class="post-metadata">

**Author:** ![briansmith](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/briansmith/32/1306_2.png) [@briansmith](https://internals.rust-lang.org/u/briansmith)\
**Post date:** [May 22, 2019, 6:49pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/53 "2019-05-22T18:49:12Z")

</div>

> [@RalfJung](#):
>
> First of all, I can see many other reasons to use Rust over C++, from enums to a type system providing safe abstractions to traits. References are not the primary reason IMO.

Maybe you misunderstood my "many people" for "most people" or "all people." The memory safety properties of Rust enabled by the reference semantics and the borrow checker (without forcing the use of a GC) were the deciding factor in every project I've been involved in that switched to Rust. I don't deny that Rust has lots of other good and nice-to-have features, but borrow checking's importance is on another level, so designs should be optimized for leveraging the borrow checker.

> Several solutions have been proposed in the [GItHub thread](https://github.com/rust-lang/unsafe-code-guidelines/issues/33), some can be implemented as a library today (such as creating a custom newtype around raw pointers and using that as “MMIO pointer type”), some require some more design and an RFC.

We need a "volatile reference" type either in the language or in the libcore, and a trait that abstracts over non-volatile and volatile references. I agree that "more design and an RFC" are needed, as well as the implementation. This should be done and standardized (in libcore) before any final decision is made on how volatile memory works in Rust.

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 22, 2019, 7:18pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/54 "2019-05-22T19:18:16Z")

</div>

> [@briansmith](#):
>
> I don’t deny that Rust has lots of other good and nice-to-have features, but borrow checking’s importance is on another level, so designs should be optimized for leveraging the borrow checker.

If you really require it, would it be possible to build custom borrow checked pointer types? It's not the prettiest but would give you very precise control over which reads and writes are allow to occur and how.

```rust
struct PoorMansRef<'a, T> {
    ptr: *const T,
    lifetime: PhantomData<&'a T>,
}

```

---

<div class="post-metadata">

**Author:** ![briansmith](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/briansmith/32/1306_2.png) [@briansmith](https://internals.rust-lang.org/u/briansmith)\
**Post date:** [May 22, 2019, 11:04pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/55 "2019-05-22T23:04:56Z")

</div>

Yes, that’s the kind of interface that I think people would want. However, I’d like to see it specified in more detail. For example, it seems like one could not implement `Deref` and `DerefMut` for that because `Deref::deref` is `fn deref(&self) -> &Self::Target` and we can’t (for reasons described above) use a reference to refer to the volatile item.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [May 22, 2019, 11:38pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/56 "2019-05-22T23:38:01Z")

</div>

It’s possible we could/should create an `UnsafeDeref`[`Mut`] which is an unsafe overload of raw pointer deref, and gives out `*[const|mut] Self::Target`.

Its relationship to today’s `Deref` is complicated, however. We’d probably want them to be mutually exclusive, as they use the same syntax.

---

<div class="post-metadata">

**Author:** ![HadrienG](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hadrieng/32/3294_2.png) [@HadrienG](https://internals.rust-lang.org/u/HadrienG)\
**Post date:** [May 23, 2019, 7:05am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/57 "2019-05-23T07:05:45Z")

</div>

People were recently talking about adding something akin to C’s `->` operator to Rust. Perhaps UnsafeDeref could specifically overload that?

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 23, 2019, 7:25am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/58 "2019-05-23T07:25:54Z")

</div>

> [@HadrienG](#):
>
> People were recently talking about adding something akin to C’s `->` operator to Rust. Perhaps UnsafeDeref could specifically overload that?

C's `->` operator is merely reference-deref sugar as already performed. It makes no real sense to introduce it as such since its result is an lvalue and then we'd be stuck with a reference again. On references this is already performed automatically today.

- `foo->bar` works in C
- `(*foo).bar` works in C+Rust
- `foo.bar` works in Rust

C++ `operator->` is `Deref/DerefMut` in disguise since it as well does not allow evaluating to an actual pointer result but will dereference the final pointer as well. So yes some new operator would be nice but **not** operator `->`. I'd argue it be better to avoid reusing the same symbol with different semantics.

Returning a raw pointer in that trait seems suboptimal as well. Note that `Deref` both takes and returns a reference. The equivalent would be to take and return a pointer which defies its use for providing custom pointer types.

---

<div class="post-metadata">

**Author:** ![Lokathor](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/lokathor/32/2463_2.png) [@Lokathor](https://internals.rust-lang.org/u/Lokathor)\
**Post date:** [June 18, 2019, 6:28pm UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/59 "2019-06-18T18:28:04Z")

</div>

`(*foo).bar` works but is gross and doesn’t chain well. That’s like the whole point of adding `->`

---

<div class="post-metadata">

**Author:** ![InfernoDeity](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/infernodeity/32/7588_2.png) [@InfernoDeity](https://internals.rust-lang.org/u/InfernoDeity)\
**Post date:** [January 3, 2020, 2:47am UTC](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188/60 "2020-01-03T02:47:24Z")

</div>

Accessing a volatile variable through an lvalue to non-volatile is undefined behavior in C and C++. I would assume that doing the same from rust (w/o using the volatile intrinsics), would also be undefined behavior.

[Previous page](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188.md?page=2)

[Next page](https://internals.rust-lang.org/t/volatile-and-sensitive-memory/3188.md?page=4)
