641b4bb2e86e71e2ba3d5381e82a8574ac7707d0
[web.git] / ralf / _drafts / the-scope-of-unsafe.md
1 ---
2 title: The scope of unsafe
3 categories: research rust
4 ---
5
6 I'd like to talk about an important aspect of dealing with unsafe code, that still regularly seems to catch people on the wrong foot:
7
8 > *When checking unsafe code, it is not enough to just check the contents of every `unsafe` block.*
9
10 The "scope" in the title refers to the extent of the code that has to be manually checked for correctness, once `unsafe` is used.
11 What I am saying is that the scope of `unsafe` is larger than the `unsafe` block itself.
12
13 It turns out that the underlying reason for this observation is also a nice illustration for the concept of *semantic types* that comes up in my [work on formalizing Rust]({{ site.baseurl }}{% post_url 2015-10-12-formalizing-rust %}) (or rather, its type system).
14 Finally, this discussion will once again lead us to realize that we rely on our type systems to provide much more than just type safety.
15
16 <!-- MORE -->
17
18 ## An Example
19
20 Before we dive into the deeper reasons for *why* we have to check (seemingly) safe code, let me start by convincing your that this is actually the case.
21
22 Consider the type `Vec`, which is roughly defined as follows:
23 {% highlight rust %}
24 pub struct Vec<T> {
25     ptr: *mut T,
26     cap: usize,
27     len: usize,
28 }
29 {% endhighlight %}
30 (I know this definition is not entirely right. If you want to know how the actual `Vec` works, check out the [corresponding section of the Rustonomicon](https://doc.rust-lang.org/nightly/nomicon/vec.html).)
31
32 Roughly speaking, `ptr` points to the heap-allocated block of memory holding the contents of the vector, `cap` holds the size of that memory block (counted in number of `T`), and `len` stores how many elements are actually stored in the vector right now.
33 `cap` and `len` can be different if the memory block contains some extra (uninitialized) space beyond the end of the vector, which speeds up pushing an element to the end of the vector (at the cost of some extra memory usage).
34
35 It is very easy to add a function to `Vec` that contains no `unsafe` code, and still breaks the safety of the data structure:
36 {% highlight rust %}
37 impl Vec<T> {
38     fn evil(&mut self) {
39         self.len += 2;
40     }
41 }
42 {% endhighlight %}
43
44 Why is this bad?
45 We can now "access" two more elements of the vector that have never been added!
46 This means we will read from uninitialized memory, or worse, from unallocated memory.
47 Oops!
48
49 So, this example clearly shows that to evaluate the safety of types like `Vec`, we have to look at *every single function* provided by that data structure, even if it does not contain any `unsafe` code.
50
51 ## The reason why
52
53 Why is it the case that a safe function can break `Vec`?
54 How can we even say that it is the safe function which is at fault, rather than some piece of `unsafe` code elsewhere in `Vec`?
55
56 The intuitive answer is that `Vec` has *additional invariants* on its fields.
57 For example, `cap` must be greater than or equal to `len`.
58 More precisely speaking, `ptr` points to an array of type `T` and size `cap`, of which the first `len` elements have already been initialized.
59 The function `evil` above violates this invariant, while all the functions actually provided by `Vec` (including the ones that are implemented unsafely) preserve the invariant.
60 That's why `evil` is the bad guy. (The name kind of gave it away, didn't it?)
61
62 This may seem obvious in hindsight, but I think it is actually fairly subtle.
63 There used to be claims on the interwebs that "if a Rust program crashes, the bug must be in some `unsafe` block". (And there probably still are.)
64 Even academic researchers working on Rust got this wrong, arguing that in order to detect bugs in data structures like `Vec` it suffices to check functions involving unsafe code.
65 That's why I think it's worth dedicating an entire blog post to this point.
66 But we are not done yet, we can actually use this observation to learn more about types and type systems.
67
68 ## The semantic perspective
69
70 There is another way to phrase the intuition of types having additional invariants:
71
72 > *There is more to types like `Vec` than their definition gives away*.
73
74 Imagine we define another type in our Rust program:
75 {% highlight rust %}
76 pub struct MyType<T> {
77     ptr: *mut T,
78     cap: usize,
79     len: usize,
80 }
81 {% endhighlight %}
82 We will define only one function for this type:
83 {% highlight rust %}
84 impl MyType<T> {
85     fn evil(&mut self) {
86         self.len += 2;
87     }
88 }
89 {% endhighlight %}
90 This type *looks* exactly like `Vec`, doesn't it?
91 The two types are *syntactically* equal, and the same goes for the two `evil` functions.
92 Still, `MyType::evil` is a perfeclty benign function (despite its name).
93 How can this be?
94
95 Remember that in a [previous blog post]({{ site.baseurl }}{% post_url 2015-10-12-formalizing-rust %}), I argued that types have a *semantic* aspect.
96 For example, a function is semantically well-typed if it *behaves* properly on all valid arguments, independently of how, *syntactically*, the function body has been written down.
97
98 The reason for `MyType::evil` being fine, while `Vec::evil` is bad, is that semantically speaking, `Vec` is very different from `MyType` -- even though they look so similar.
99 If I have a `Vec`, I actually know that `ptr` is valid, that `len <= cap`, and so on.
100 I know nothing like that about an arbitrary instance of `MyType`: All I have here is that `cap` and `len` are valid elements of `usize`.
101 In other words, the additional invariants that we associate with `Vec` actually make this an *entirely different type*.
102 In order to formally describe what it means to be a `Vec`, we can't just say "well, that's a `struct` with these three fields".
103 That would be *wrong*.
104 But still, that's actually all the Rust compiler knows, and it is all that it actually checks:
105 When type checking `Vec::evil`, the compiler *thinks* that `Vec` is like `MyType`, and under that assumption, it deems `evil` a good function.
106 (Clearly, the compiler did not watch enough movies with serious villains.)
107
108 In other words, we have to look beyond the mere syntactic appearance of a type, and into its deeper, semantic meaning.
109 As part of my work on formalizing Rust, I will eventually want to prove the soundness of types like `Vec` or `RefCell` and their associated operations.
110 In order to do so, I will first have to figure out what exactly the semantics of these types are. (This will be fairly easy for `Vec`, but really hard for `RefCell`. Can you guess why?)
111 Then I will have to check *every* function operating on these types and prove that they are actually well-typed.
112 Even if the Rust compiler says "yup, that function over there is fine, I checked every single statement of it", that's not enough because the Rust compiler has no idea about which types these functions are *actually* about.
113 All it sees is the syntactic surface.
114
115 While proving soundness of `Vec`, it would then turn out that `Vec::evil` is actually not a semantically well-typed function. It may leave an invalid `Vec` in `self`.
116 This is just as bad as a function assigning `*f = 42u32` to a `f: &mut f32`.
117 The difference between `Vec` and `MyType` is no less significant than the difference between `f32` and `u32`.
118 It's just that the compiler has been specifically taught about `f32`, while it doesn't know enough about the semantics of `Vec`.
119
120 ## The actual scope of unsafe
121
122 At this point, you may be slightly worried about the safety of the Rust ecosystem.
123 I just spent two sections arguing that the Rust compiler actually dosn't know what it is doing when it comes to checking functions that work on `Vec`.
124 How does it come that people carelessly use `Vec` in their programs without causing havoc all the time?
125 Or, to put it slightly differently: If the scope of `unsafe` grows beyond the syntactc `unsafe` blocks, then how far does it reach?
126 Does it sprawl through all our code, silently infecting everything we write -- or is there some limit to its effect?
127
128 As you probably imagined, of course there *is* a limit. Rust would not be a useful language otherwise.
129 The scope of `unsafe` ends at the next *abstraction boundary*.
130 This means that everything outside of the `std::vec` module does not have to worry about `Vec`.
131 Due to the privacy rules enforced by the compiler, code outside of that module cannot access the private fields of `Vec`, and hence it cannot tell the difference between the syntactic appearance of `Vec` and its actual, semantic meaning.
132 Of course, this also means that *everything* inside `std::vec` is potentially dangerous and needs to be proven to respect the semantics of `Vec`.
133
134 ## Abstraction Safety
135
136 This nicely brings us to another important point, which I can only glimpse at here:
137
138 > *The purpose of type systems goes far beyond type safety: They (also) serve to establish safe abstractions.*
139
140 If the type system of Rust lacked a mechanism to establish abstraction (i.e., if there were no private fields), type safety would not be affected.
141 However, it would be very dangerous to write a type like `Vec` that has a semantic meaning beyond its syntactic appearance.
142 Since users of `Vec` can accidentally perform invalid operations, there would actually be *no bound to the scope of `unsafe`*.
143 To formally establish safety, one would have to literally go over the entire program and prove that it doesn't misuse `Vec`.
144 The safety promise of Rust would be pretty much useless.
145
146 This should not be entirely surprising if you read the aforementioned [post about formalizing Rust's type system]({{ site.baseurl }}{% post_url 2015-10-12-formalizing-rust %}), where I already argued that a proof of (syntactic) type safety does not help to justify safety of most Rust programs out there.
147 I am now making a similar point, coming from a different angle.
148
149 The fact that Rust programmers *can* use `Vec` and many other types without much care is a property of the type system that is independent of type safety.
150 We rely on the fact that the type system lets us build abstraction boundaries that cannot be violated by safe code.
151 We may call this *abstraction safety*.
152 Many type systems have this property, just think of `private` fields in Java or C++, or opaque signatures in ML.
153 However, few languages embrace using unsafe primitives and encapsulating them behind a layer of abstraction as much as Rust does.
154 In some sense, Rust relies way more on abstraction safety than most languages -- though in practice, programmers of all languages rely on abstraction safety a lot, if it is available.
155 (Most scripting languages, I am looking at you.)
156
157 Abstraction safety is a very deep point that deserves its own blog post, I only skimmed the surface.
158 Watch this space, a link to such a post will eventually appear. (And I hope I don't have to write it myself.)
159
160