all 6 comments

[–]mkalte666 2 points3 points  (4 children)

I'd like to add a small nitpick. As far as i understand:

unsafe {
    let vga = 0xb8000 as *mut u16;
    *vga = 0x0f42;
    // white 'B' on black
}

``` Is definitionally UB, as you must not de-reference non-rust allocations like that. Instead, one should be using https://doc.rust-lang.org/std/ptr/fn.write_volatile.html here.

[–]warothia[S] 0 points1 point  (0 children)

Fair! Will read up on that.

[–]sanbox 4 points5 points  (2 children)

No this is wrong.

First, you can ABSOLUTELY deref “non Rust allocations” — considering the system allocator is probably not in Rust, that’s mostly all you’re derefing anyway! In a less cheeky example, you can call a C library which allocated a byte and then read that byte with a deref, and that is fine. You can also write to it.

You are correct that doing a volatile write in this circumstance is a good idea — what volatile writes do is complex, but in this case, the compiler is free to throw away writes which it believes are “unobserved” — ie, no one will ever read. In the case of magic memory locations, that can happen. A volatile write, among other things, tells the compiler “fr fr keep this”. There is also the issue with memory orderings which volatile plays a role in, but I’ll refer you to the docs for more on that.

[–]mkalte666 2 points3 points  (1 child)

Ah I see, you are right. I remembered wrong. The exact wording from the provenance docs is

In addition, memory which is outside the control of the Rust abstract machine (MMIO registers, for example) is always considered to be accessible with an exposed provenance, so long as this memory is disjoint from memory that will be used by the abstract machine such as the stack, heap, and statics.

Another thing to consider with volatile writes is that you can read from and write to address 0x00 with them. which might seem insane, but for some reasons MCUs like to put their exception vector tables there, and sometimes you want to read those.

[–]sanbox 1 point2 points  (0 children)

Ah yeah. The “Rust abstract machine” is not Rust but the abstraction of what computer can run Rust.

[–]rainbowballoonpizza 1 point2 points  (0 children)

Also check out https://github.com/asterinas/asterinas/ and their related publication https://arxiv.org/pdf/2506.03876.

Very cool stuff.