Reading this only OoC, since I know 0 about the lower levels or hardware.
But I did wonder, can the idea be represented as a single diagram? Or maybe simplified a bit for beginners?
One seems clear:
let a:u8;
Can not be read in safe Rust. It can in unsafe Rust, I think? And either way, it does not contains random bit pattern.
It seems one needs to imagine a Rust AM rather than hardware. A separate model where bytes have a 2nd state of "unitialized" but after going through I am still unsure what to imagine in its place.
It is like an extra abstraction on top of a raw byte contents ? Because, I dont think imagining actually uninitialized memory makes sense, since it will always be something.
No. UB is not unsafe Rust (or C or C++ if in those languages.) It is some text that you trick the compiler into producing a application for. (If lucky it will reject compiling.)
Think of it like me changing a character in an English word to one of the Greek alphabet. It is no longer a word but you might get tricked into thinking it still is. (Or If you are like me will not care to say it isn't, when not being pedantic. tolerance)
Undefined behaviour means that the compiler can do anything it wants to do. Including making demons fly from your nose. Reading uninitialized memory in Rust is undefined behaviour. So thinking about memory "always being something" is futile. From Ralf's article you posted:
Many people will tell you that “uninitialized memory contains a random bit pattern”. This is wrong. They might also talk about the system allocator or how the OS kernel allocates pages for the program to use. That is just irrelevant information.
Below this excerpt is a very nice, real-world example demonstrating this:
Here is an example to demonstrate why “random bit pattern” cannot describe uninitialized memory:
use std::mem;
fn always_returns_true(x: u8) -> bool {
x < 120 || x == 120 || x > 120
}
fn main() {
let x: u8 = unsafe { mem::MaybeUninit::uninit().assume_init() };
assert!(always_returns_true(x));
}
[...]
always_returns_true is a function that, clearly, will return true for any possible 8-bit unsigned integer. After all, every possible value for x will be either less than 120, equal to 120, or bigger than 120. A quick loop confirms this. However, if you run the example, you can see the assertion fail.
Edit: not the whole answer, see the breakdown of the "optimized" parts in the post below.
It looks like you're trying to mix the abstract with the concrete: the higher level concept of an "unitialized" memory with the basic building blocks making up that memory in the first place.
RAM is just a bunch of transistors. If you want details, see Core Dumped.
In essence: for every byte of your RAM you may want to "store" a bunch of 0's and 1's into, there's a hardware mechanism in place that allows you to do just that. This "raw" mechanism is usually protected by the OS itself, mainly to prevent you from overwriting a bunch of 0's and 1's that the OS or other processes are using for their own purpose.
When you run a process, perhaps the one you compiled yourself with cargo build which turns the whole of your program source code into raw machine instructions as per your CPU/OS specification, the OS does a bunch of work behind the scenes setting up that process for you.
This includes the allocation of both the executable machine code itself, which is going to execute one instruction at a time, and the "stack" for this process: a free chunk of available memory in the RAM where the grand most of your let <var>: <type> = <init> are going to end up.
In your case:
means taking the current stack pointer / the current address in the RAM within the "chunk" allocated for your process itself (a.k.a. once again: the "stack"), reserve an u8's worth of memory (most likely by simply "bumping up" / moving the stack pointer one's u8's worth of space up/down in the address space, depending once again on the particular architecture and OS), and period.
If you had instead wrote:
let b: u8 = 255;
The output instruction combo would have included not merely the "stack allocation" and the "pointer bump" itself, but also "storage" or "writing" or "copying" the bytes of this particular value (255 in decimal is 0b1111_1111 in binary) into that particular location.
Since you didn't do that, and until you've written some valid value into your own let a: u8, the compiler will keep track of that particular space on the stack and prohibit you from reading it. Not because it's "bad" or "wrong" or "unsafe" per se. But because reading from a reserved, yet not explicitly initialized memory space, can give you "undefined behaviour": a violation of some implicitly assumed constraints by the language or compiler or OS or CPU which turns your whole process from a deterministic, well-defined, "A then B then C then D" into "all bets are off".
For your particular toy example, your a: u8 is actually perfectly "safe" to read. A byte (u8) can take any value from 0 to 255. Which matches perfectly with any possible arrangement of bits (0b0000_0000 to 0b1111_1111) within your stack allocation. Now consider something akin to:
enum Example {
Empty,
Number(i32),
TextVec {
text: &str,
vec: Vec<Example>
}
}
let c: Example;
If you try to read the c now, what happens?
The answer is: nobody knows. It might (magically) match the expected layout and data structure of the enum Example itself. It most likely won't. How should the compiler, or the program, or the machine code, or the rest of your code relying on c being a valid Example behave?
Nobody knows. Which is bad. Very bad. Programmers very much like to know exactly what happens, at which point in the program, and why. This is what allows for all the "debugging" and "fighting the borrow checker" and crying out about how hard Rust is, to happen. Without clear expectations and an effort on the part of the language and the compiler and the people writing code and everything in between to enforce those expectations, anything can happen. Anything can follow out of that anything that happened, and so on and so forth and so it goes ad nauseum.
"Uninitialized" memory itself makes perfect sense on its own. Just a chunk of allocated memory that might be filled with any arrangement of 0's and 1's at the individual bit level. It's the fact that very few types (besides the basic built-in's) tolerate an arbitrarily chaotic arrangement of 0's and 1's within themselves, as per their inner structure and all that's based on it, that matters here.
P.S. For a bit more interesting and practical, yet still inherently "safe", example - try running:
fn main() {
use std::mem::MaybeUninit;
let a: [u8; 16] = unsafe { MaybeUninit::uninit().assume_init() };
// try to guess what's going to be printed here
println!("{a:#?}")
}
P.P.S. The article you've mentioned deals primarily with the "compiler magic": all the different ways in which the rustc and LLVM itself might choose to "optimize away" a given value depending on whether it is ever initialized, how and where it is read and so forth. Doesn't change the core basic mechanics of the process itself. Merely introduces another layer of hidden complexity on top.
Accessing uninitialled memory is UB in C.
See how it works:
void do() {
int a; // What is the value of a here?
if (a == 1) {
printf("1");
} else {
printf("2");
}
}
The compiler might set initial value to 0. Or to 42. Or it may remove the first branch and leave printf("2"). Or both branches.
It is up to compiler to decide.
In some environments, it might lead to a hardware error (in theory). Your program might crash. Or freeze. Or delete all your files.
In other words, accessing uninitialled memory in C means the whole application is broken.
Rust forces you to initialize memory: you can't access a variable before you initialize it explicitly. It will not compile.
I dont think imagining actually uninitialized memory makes sense, since it will always be something.
Yes, if we are talking about local (stack aka automatic) variables.
But it is an implementation detail. If your code violates standard -- it is broken, even if it works perfectly on your CPU and your compiler.
Anyway: this is not a problem in Rust: you can't compile code with uninitialled memory access.
However, you can have all kinds of other UBs in unsafe code. But in safe code we have no UBs.
Rust isn't executed line-by-line. The compiled program doesn't have to do literally what the source code says. The language only promises what observable effects the program will have, not how it makes them happen.
let a: u8 line doesn't have to make the program perform any action. It only informs the compiler that you want to have a variable a somehow, and that you want the compiler to only allow using it with u8. What actually happens depends on the later code, where the value of the variable is used, what it's used for, whether it has a value that is a constant known at compile time or not, etc.
Variables are only an abstract concept made for humans. They don't exist in hardware. CPUs have registers, stack, and RAM that don't directly correspond to what variables are. It's compiler's job to figure out how to express equivalent behavior in real hardware, and the Rust language intentionally gives the compiler a lot of flexibility in deciding how to do it.
Compilers often treat every assignment to a variable like a creation of a new immutable variable (SSA form), so what you think of as a single variable can end up being several separate variables that come in and out of existence.
And then their values may end up being stored in some memory location, or in a register, or be moved between locations to free up space for more important data, or may not even exist at all if the value wasn't used or got folded into another expression.
Uninitialized memory is also a fictional concept. In hardware all memory is initialized to some value. However, because variables are also abstract, and don't have to exist in memory, there may not be a garbage value to read. When they do exist in memory, it may not be a single location, or it may not be the same location for the lifetime of the variable. Either the compiler would have to do extra work to pick an initial garbage value and ensure it's preserved with the same care as values of initialized variables, or you could see program-breaking paradoxes caused by different uses of the variable end up using different garbage values from different places at different times.
If I understand correctly, your confusion is this.
OK, I hear an uninitialized variable has no value, and that kind of makes sense
but, like, it's RAM, right?
is the RAM capable of not having a value? how does this work?
I think the only really satisfying answer is to know a little bit about compiler optimizations. All undefined behavior is there to allow compilers to produce more efficient code by assuming that UB does not happen.
Example: Reading off the end of an array is undefined behavior. This licenses C/C++ compilers to assume array reads are always OK and skip bounds checks.
Example: Writing through an invalid pointer is undefined behavior. So the compiler isn't required to track when pointers become dangling, for example.
Now an uninitialized memory example. Optimizing compilers love to delete code. Truly one of the most powerful optimizations they do is inlining a function and deleting the parts that aren't used at that call site. A compiler is entitled to assume that programs never read uninitialized memory, so if it sees code that does read uninitialized memory, well, the only possible conclusion is that that code must never actually run. So the compiler can delete it—and everything after it in the same block—and everything before it, back to the previous branch. Some compilers really do this. It's wild.
tl;dr - The uninitialized variable is not a byte of RAM. The compiler might put it in RAM, or into a register, or optimize it away entirely (in which case it really truly doesn't have a value, even behind the scenes). In any case, violating the compiler's assumptions is a very bad idea.
So to me it reads like the original example should've passed the boolean test I'd say.
And this example passes too?
use std::mem;
fn always_returns_true(x: u8) -> bool {
x < 120 || x == 120 || x > 120
}
fn main() {
let x: u8 = unsafe { mem::MaybeUninit::uninit().assume_init() };
assert!(always_returns_true(x));
}
I didn't originally test, I assumed it wouldn't. So I think the claims make sense.
So this said in the post, doesn't work for new Rust versions?
Update (2024-10-18): See here for a version that works with Rust 1.82.
always_returns_true is a function that, clearly, will return true for any possible 8-bit unsigned integer. After all, every possible value for x will be either less than 120, equal to 120, or bigger than 120. A quick loop confirms this. However, if you run the example, you can see the assertion fail.
First - think of a memory bit as a coin - it is either in the heads or tails position. Representing a 0 or a 1. Think of a byte of memory as 8 coins. Think of memory - say 1 mega byte of memory as 8 million coins organized in some way.
When memory is powered off - the coins have not specific state, they are kind of "floating around" sort of oscillating between heads and tails some what randomly.
Suddenly power is turned on - they coins snap into some specific state - some are heads, some are tails. You can call it random - but technically - some bits will tend to be more heads (1s) or tails(0s) so its not perfectly random - it really depends upon the structure of the memory cells and the way they where designed.
One could design a memory bit to always OPTION 1 - power up in one specific state (ie: always heads, or always tails, ie: always 0 or 1) - but that would require at least 1 more thing in the structure inside that memory cell (that bit or coin). Or OPTION 2 - you can let the data be random.
Remember that 1Mbit of memory is 1 million things on that chip. The question is how large are those things? What if you could get rid of 1 million things? Maybe you can make the chip smaller, or fit more things on the chip.
The chip company starts with a wafer and slices & dices it into little chips - the more chips they can get per wafer the more money they make. So.. By removing the "force 0 or 1" parts, the chip company can remove more then 1 million parts from the 1 mega bit chip and thus they can fit more per wafer and make more money. That is a good thing the memory chip is cheaper!
You could OPTION 1 - design and purchase chips that self initialize - but they would cost ALOT more. Or OPTION 2 - tell the customer that on power up the data is random and they can initialize the memory to a specific value via software - which is way cheaper (probably 2x to 3x cheaper) - which one do you think will sell more? Obviously option 2 (let it be random) is cheaper so it wins over the long term and that is what we have today.
Next I want to talk about "global memory variables" - things that are on the heap or global RAM".
The compiler/linker determine the memory location for your variable. That means the memory location where your variable is located now starts at power up with some random value. Your application startup code could - zero all of that memory - Linux and Windows does that with the "bss" section of your application, the other section "data" is initialized to your specified values. Often Embedded (bare metal) startup code does that - this is code that executes before you reach the "main" function.
Rust takes it a bit further and requires that YOU explicitly initialize all memory. always.
Next I want to talk about local variables private to a function (Often these are variables on the stack) Or you could have variables that are stored inside a data structure and are allocate from the HEAP. Thus they are are soft of the same situation.
There are two sub things to talk about here: (A) the content of the stack memory (or heap) at power up - this falls sort of into the first category - the system could initialize it or it might not, that is an OS or PLATFORM decision - the RUST compiler does not know which one - So it assumes the worse and requires that YOU initialize the memory cells (just like the above)
Now - lets talk about the HEAP and the STACK memory LONGAFTER power up. After it has been used for a while. Both of STACK/HEAP can be related to scraps of paper where you keep your notes {variables}. At powerup the note paper is clean/fresh and empty. But the purpose of the HEAP/STACK is that it can be allocated and later released or reused.
So the scrap of paper starts as "clean" - I allocate some of it - and I scribble all over it with my notes (variables). I am done, I release it - and then you need some "heap/stack" (note paper) space and allocate it.
When you get the paper is it clean? Or is it scribbled all over with random garbage (my old notes)? What is the most likely scenario: ANSWER: Quite possibly my old notes -
Why? Because the memory system did not zero or clean or erase that memory when I released it - and it did not clean or erase it when you allocate it. It could have but that's extra work and makes the application slower - and we wall want faster applications so we do not zero or clean it - faster wins! So if you just use the contents of that memory location the value will be some random value - not clean not zero. You need to initialize that memory before you use it.
Instead - rust assumes the worst and requires that *YOU initialize the memory cells (just like the above). Otherwise the values are effectively 'some form of random data'.
And RANDOM is defined as UB (undefined behavior) - that is bad really bad. Imagine driving your car down the mountain road and the steering wheel and brakes decide to "randomly work or not work" - this would be called: "UNDEFINED BEHAVIOR" - this is not good. You crash your car, or your application crashes.. in bad ways.
I suspected this is a fictional concept by saying "Rust-AM" which is the Rust Abstract Machine in the original post.
However, it also says there:
The x that is passed to always_return_true is not the 8-bit representation of some number, it is an uninitialized byte.
But the overall sense seems to be: uninitialized byte is just not really a byte at the low level, it's some part of this higher level world, where we are adding a state to the "byte" which is "uninitialized" for convenience of thought.
But I am unsure whether you agree or what is the correction.
In any case, the code does currently run in Rust, it does not throw any error.
It’s not strictly true that this always happens. In some cases, a memory cell can remain in an intermediate state. (Flash/EEPROM memory is the most straightforward case — if it is written with too little voltage, it can be permanently in a middle level that might be interpreted one way or another when read, depending on noise. But I have heard it can happen to some types of volatile RAM too.) In these cases, if you read such a value without overwriting it first, you will get actual UB at the hardware level — it may be interpreted as both 1 and 0 at different times, or an incorrect logic level can, sometimes, actually reach the CPU and cause it to behave in otherwise-impossible ways.
All digital logic is built on analog behaviors. We design things to make the probability that any intermediate states will actually be observed very, very small, but it can never be impossible, and reading storage that hasn't been properly written is one of the more accessible ways to have such a problem.
UB can exist at all levels of the system executing your program, not just the abstract one.
That's correct. Whether bytes are initialized or not is an abstract concept, tracked only by the compiler. You can't ask the hardware about it.
However, it doesn't make sense to draw conclusions from what happens when you violate the Undefined Behavior rules. It doesn't tell you what "really" happens. The effect you're going to get won't be anything intentional. It hasn't been designed to do this or that, and what you get in simple cases probably won't be representative of what you can get in less obvious cases.
Compilers assume that Undefined Behavior never happens. Compilers don't try to detect UB and do something else. They just ignore consequences of UB existing in the program, because it's assumed to be impossible, and do whatever they'd do if UB was impossible.
For example, a Unicorn teleporting right in front of you is an Undefined Behavior. You've planned your day assuming that a Unicorn won't teleport right in front of you. It's hard to give a definitive answer to what Teleporting Unicorns do, because your TODO list doesn't have plans for everything that can't happen. What Teleporting Unicorns do depends what you were going to do anyway, and how disruptive a Unicorn will be at any given moment.
The effect of Teleporting Unicorns is said to be undefined and could be anything. You could be sleeping and not even notice a Unicorn teleporting. Or you could be a surgeon and a Unicorn teleporting right in front of you during an operation could cause mayhem.
When I clicked the "if you run the example" link, and clicked "Run", I got this:
Exited with signal 4 (SIGILL): illegal instruction
When I clicked the "See here for a version that works with Rust 1.82" link, and clicked "Run", I got the output below. Note the assertion failure on the last 3 lines.
Compiling playground v0.0.1 (/playground)
warning: the type `u8` does not permit being left uninitialized
--> src/main.rs:4:26
|
4 | let x: u8 = unsafe { mem::MaybeUninit::uninit().assume_init() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| this code causes undefined behavior when executed
| help: use `MaybeUninit<T>` instead, and only call `assume_init` after initialization is done
|
= note: integers must be initialized
= note: `#[warn(invalid_value)]` on by default
warning: `playground` (bin "playground") generated 1 warning
Finished `release` profile [optimized] target(s) in 0.76s
Running `target/release/playground`
thread 'main' (13) panicked at src/main.rs:5:5:
assertion failed: x < 120 || x == 120 || x > 120
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The explanation up to this point (about RAM, stack, heap, and memory reuse) is right, and helpful background.
But Ralf Jung's examples prove that uninitialized variables are not just "random data". If x was set to random data, the assertion x < 120 || x == 120 || x > 120 could not possibly fail.
I don't think so. addr_of!(a) doesn't compile for uninitialized variables, so it seems impossible to write code that tries to read it.
It's not really "fictional". It's just that we're talking about two different languages: Rust and machine code.
In Rust, MaybeUninit<u8> has 257 possible values: 0, 1, ..., 255, "uninitialized". It's true, it's not a fiction. What happens when you read "uninitialized" is undefined.
In machine code bytes have 256 possible values.
Rust code gets translated to machine code, MaybeUninit<u8> values get translated to machine code bytes, and undefined behavior gets translated to some arbitrary unpredictable behavior.