even more https
[web.git] / ralf / _posts / 2017-07-14-undefined-behavior.md
1 ---
2 title: Undefined Behavior and Unsafe Code Guidelines
3 categories: internship rust
4 ---
5
6 Last year, the [Rust unsafe code guidelines strike team](https://internals.rust-lang.org/t/next-steps-for-unsafe-code-guidelines/3864) was founded, and I am on it. :-)
7 So, finally, just one year later, this post is my take at what the purpose of that team is.
8 <!-- MORE -->
9 Warning:  This post may contain opinions.  You have been warned.
10
11 ## When are Optimizations Legal?
12
13 Currently, we have a pretty good understanding of what the intended behavior of *safe* Rust is.
14 That is, there is general agreement (modulo some [bugs](https://github.com/rust-lang/rust/issues/27868)) about the order in which operations are to be performed, and about what each individual operation does.
15
16 For unsafe Rust, this is very different.
17 There are multiple reasons for this.
18 One particularly nasty one is related to compiler optimizations that rustc/LLVM either already perform today, or want to perform some day in the future.
19 Consider the following simple function:
20 {% highlight rust %}
21 fn simple(x: &mut i32, y: &mut f32) -> i32 {
22     *x = 3;
23     *y = 4.0;
24     *x
25 }
26 {% endhighlight %}
27 We would like the compiler to be able to *reorder* these two stores without changing program behavior.
28 After all, `x` and `y` are both mutable references, which the type system ensures are unique pointers, so they cannot possibly alias (i.e., the memory ranges they point to cannot overlap).
29 After this transformation, the code contains `*x = 3; *x`, which can be further optimized to `*x = 3; 3`, saving a memory access.
30 Compilers are able to get a lot of performance out of code by figuring out which operations are independent of each other, and then moving code around to either eliminate certain operations entirely (like the load of `x`), or making code faster to execute with clever scheduling that exploits the [parallelism](https://en.wikipedia.org/wiki/Instruction-level_parallelism) in modern CPU cores (this is per-core parallelism we are talking about, not the parallelism arising from having multiple cores).
31
32 Optimizations like reordering stores are based on the compiler making *assumptions* about the code, and then using these assumptions to justify a program transformation.
33 In this case, the assumption is that the two stores never affect the same address.
34 Usually, if a compiler wants to make such an assumption, it has to do some static analysis to *prove* that this assumption actually holds in any possible program execution.
35 After all, if there is any execution for which the assumption does *not* hold, the optimization may be incorrect -- it could change what the program does!
36
37 Now, it turns out that it is often really hard to obtain precise aliasing information.
38 This could be the end of the game:  No alias information, no way to verify our assumptions, no optimizations.
39
40 ## Shifting Responsibility
41
42 However, it turns out that compiler writers consider these optimizations important enough that they came up with an alternative solution:
43 Instead of having the compiler verify such assumptions, they declared the programmer responsible.
44
45 For example, the C standard says that memory accesses have to happen with the right "effective type":  If data was stored with a `float` pointer, it must not be read with an `int` pointer.
46 If you violate this rule, your program has *undefined behavior* (UB) -- which is to say, the program may do *anything* when executed.
47 Now, if the compiler wants to make a transformation like reordering the two stores in our example, it can argue as follows:
48 In any particular execution of the given function, either `x` and `y` alias or they do not.
49 If they do not, reordering the two writes is just fine.
50 However, if they *do* alias, that would violate the effective type restriction, which would make the code UB -- so the compiler is permitted to do anything.
51 *In particular*, it is permitted to reorder the two writes.
52 As we have seen, in both of the possible cases, the reordering is correct; the compiler is thus free to perform the transformation.
53
54 Undefined behavior moves the burden of proving the correctness of this optimization from the compiler to the programmer.
55 In the example above, what the "effective type" rule really means is that every single memory read of a `float` comes with a *proof obligation*:
56 The programmer has to show that that the last write to this memory actually happened through a `float` pointer (baring some exceptions around union and character pointers).
57 Similarly, the (in)famous rule that [signed integer overflow is undefined behavior](https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c) means that every single arithmetic operation on signed integers comes with the proof obligation that this operation will never, ever, overflow.
58 The compiler performs its optimization under the assumption that the programmer actually went through the effort and convinced itself that this is the case.
59
60 Considering that the compiler can only be so smart, this is a great way to justify optimizations that would otherwise be difficult or impossible to perform.
61 Unfortunately, it is often not easy to say whether a program has undefined behavior or not -- after all, such an analysis being difficult is the entire reason compilers have to rely on UB to perform their optimizations.
62 Furthermore, while C compilers are happy to exploit the fact that a particular program *has* UB, they do not provide a way to test that executing a program *does not* trigger UB.
63 It also turns out that programmers' intuition often [does not match what the compiler does](https://www.cl.cam.ac.uk/~pes20/cerberus/notes50-survey-discussion.html), which leads to miscompilations (in the eye of the programmer) and sometimes to security [vulnerabilities](https://lwn.net/Articles/342330/).
64 As a consequence, UB has a pretty bad reputation.
65 (The fact that most people will not expect an innocent-looking `+` operation to come with subtle proof obligations concerning overflow probably also plays a role in this.
66 In other words, this is also an API design problem.)
67
68 There are various sanitizers that watch a program while it is being executed and try to detect UB, but they are not able to catch all possible sources of UB.
69 Part of the reason this is so hard is that the standard has not been written with such sanitizers in mind.
70 This [recent blog post](https://blog.regehr.org/archives/1520) discusses the situation in much more detail.
71 For example, for the effective type restriction (also sometimes called "strict aliasing" or "type-based alias analysis") we discussed above, the mitigation -- the way to check or otherwise make sure your programs are not affected -- is to turn off optimizations that rely on this.
72 That is not very satisfying.
73
74 ## Undefined Behavior in Rust
75
76 Coming back to Rust, where are we at?
77 Safe Rust is [free from UB]({% post_url 2017-07-08-rustbelt %}), but we still have to worry about unsafe Rust.
78 For example, what if unsafe code crafts two aliasing mutable references (something that is prevented in safe Rust) and passes them to our `simple` function?
79 This violates the assumptions we made when we reordered the two writes.
80 If we want to permit this optimization (which we do!), we have to argue why it cannot change program behavior.
81 It should be forbidden for unsafe Rust code to pass aliasing pointers to `simple`; doing so should result in UB.
82 So we have to come up with rules for when Rust code is UB.
83 This is what the unsafe code guidelines strike team set out to do.
84
85 We could of course just copy what C does, but I hope I convinced you that this is not a great solution.
86 When defining UB for Rust, I hope we can do better than C.
87 I think we should strive for programmers' intuition agreeing with the standard and the compiler on what the rules are.
88 If that means we have to be a little more conservative around our optimizations, that seems to be a prize worth paying for more confidence in the compiled program.
89
90 I also think that tooling to *detect* UB is of paramount importance, and can help shape intuition and maybe even permit us to be less conservative.
91 To this end, the specification should be written in a way that such tooling is feasible.
92 In fact, specifying a dynamic UB checker is a very good way to specify UB!
93 Such a specification would describe the additional state that is needed at run-time to then *check* at every operation whether we are running into UB.
94 It is with such considerations in my mind that I have previously written about [miri as an executable specification]({% post_url 2017-06-06-MIR-semantics %}).
95
96 Coming up next on this channel:  During my [internship]({% post_url 2017-05-23-internship-starting %}), I am working on such a specification.
97 My ideas are concrete enough now that I can write down a draft, which I will share with the world to see what the world thinks about it.
98
99 **Update:** [Writing down has happened]({% post_url 2017-07-17-types-as-contracts %}).
100
101 **Update:** Clarified "Shifting Responsibility".