Stacked Borrows 2
[web.git] / ralf / _posts / 2018-11-16-stacked-borrows-implementation.md
1 ---
2 title: "Stacked Borrows Implemented"
3 categories: internship rust
4 forum: https://internals.rust-lang.org/t/stacked-borrows-implemented/8847
5 ---
6
7 Three months ago, I proposed [Stacked Borrows]({% post_url
8 2018-08-07-stacked-borrows %}) as a model for defining what kinds of aliasing
9 are allowed in Rust, and the idea of a [validity invariant]({% post_url
10 2018-08-22-two-kinds-of-invariants %}) that has to be maintained by all code at
11 all times.  Since then I have been busy implementing both of these, and
12 developed Stacked Borrows further in doing so.  This post describes the latest
13 version of Stacked Borrows, and reports my findings from the implementation
14 phase: What worked, what did not, and what remains to be done.  There will also
15 be an opportunity for you to help the effort!
16
17 <!-- MORE -->
18
19 What Stacked Borrows does is that it defines a semantics for Rust programs such
20 that some things about references always hold true for every valid execution
21 (meaning executions where no [undefined behavior]({% post_url
22 2017-07-14-undefined-behavior %}) occurred): `&mut` references are unique (we
23 can rely on no accesses by other functions happening to the memory they point
24 to), and `&` references are immutable (we can rely on no writes happening to the
25 memory they point to, unless there is an `UnsafeCell`).  Usually we have the
26 borrow checker guarding us against such nefarious violations of reference type
27 guarantees, but alas, when we are writing unsafe code, the borrow checker cannot
28 help us.  We have to define a set of rules that makes sense even for unsafe
29 code.
30
31 I will explain these rules again in this post.  The explanation is not going to
32 be the same as last time, not only because it changed a bit, but also because I
33 think I understand the model better myself now so I can do a better job
34 explaining it.
35
36 Ready?  Let's get started.  I hope you brought some time, because this is a
37 rather lengthy post.  If you are not interested in a detailed description of
38 Stacked Borrows, you can skip most of this post and go right to [section 4].  If
39 you only want to know how to help, jump to [section 6].
40
41 ## 1 Enforcing Uniqueness
42
43 Let us first ignore the part about `&` references being immutable and focus on
44 uniqueness of mutable references.  Namely, we want to define our model in a way
45 that calling the following function will trigger undefined behavior:
46
47 {% highlight rust %}
48 fn demo0() {
49   let x = &mut 1u8;
50   let y = &mut *x;
51   *y = 5;
52   // Write through a pointer aliasing `y`
53   *x = 3;
54   // Use `y` again, asserting it is still exclusive
55   let _val = *y;
56 }
57 {% endhighlight %}
58
59 We want this function to be disallowed because between two uses of `y`, there is
60 a use of another pointer for the same location, violating the fact that `y`
61 should be unique.
62
63 Notice that this function does not compile, the borrow checker won't allow it.
64 That's great!  It is undefined behavior, after all.  But the entire point of
65 this exercise is to explain *why* we have undefined behavior here *without*
66 referring to the borrow checker, because we want to have rules that also work
67 for unsafe code.  In fact, you could say that retroactively, these rules explain
68 why the borrow checker works the way it does:  We can pretend that the model came
69 first, and the borrow checker is merely doing compile-time checks to make sure
70 we follow the rules of the model.
71
72 To be able to do this, we have to pretend our machine has two things which real
73 CPUs do not have.  This is an example of adding "shadow state" or "instrumented
74 state" to the "virtual machine" that we [use to specify Rust]({% post_url
75 2017-06-06-MIR-semantics %}).  This is not an uncommon approach, often times
76 source languages make distinctions that do not appear in the actual hardware.  A
77 related example is
78 [valgrind's memcheck](http://valgrind.org/docs/manual/mc-manual.html) which
79 keeps track of which memory is initialized to be able to detect memory errors:
80 During a normal execution, uninitialized memory looks just like all other
81 memory, but to figure out whether the program is violating C's memory rules, we
82 have to keep track of some extra state.
83
84 For stacked borrows, the extra state looks as follows:
85
86 1. For every pointer, we keep track of an extra "tag" that records when and how
87    this pointer was created.
88 2. For every location in memory, we keep track of a stack of "items", indicating
89    which tag a pointer must have to be allowed to access this location.
90
91 These exist separately, i.e., when a pointer is stored in memory, then we both
92 have a tag stored as part of this pointer value (remember,
93 [bytes are more than `u8`]({% post_url 2018-07-24-pointers-and-bytes %})), and
94 every byte occupied by the pointer has a stack regulating access to this
95 location.  Also these two do not interact, i.e., when loading a pointer from
96 memory, we just load the tag that was stored as part of this pointer.  The stack
97 of a location, and the tag of a pointer stored at some location, do not have any
98 effect on each other.
99
100 In our example, there are two pointers (`x` and `y`) and one location of
101 interest (the one both of these pointers point to, initialized with `1u8`).
102 When we initially create `x`, it gets tagged `Uniq(0)` to indicate that it is a
103 unique reference, and the location's stack has `Uniq(0)` at its top to indicate
104 that this is the latest reference allowed to access said location.  When we
105 create `y`, it gets a new tag, `Uniq(1)`, so that we can distinguish it from
106 `x`.  We also push `Uniq(1)` onto the stack, indicating not only that `Uniq(1)`
107 is the latest reference allow to access, but also that it is "derived from"
108 `Uniq(0)`: The tags higher up in the stack are descendants of the ones further
109 down.
110
111 So after both references are created, we have: `x` tagged `Uniq(0)`, `y` tagged
112 `Uniq(1)`, and the stack contains `[Uniq(0), Uniq(1)]`. (Top of the stack is on
113 the right.)
114
115 When we use `y` to access the location, we make sure its tag is at the top of
116 the stack: check, no problem here.  When we use `x`, we do the same thing: Since
117 it is not at the top yet, we pop the stack until it is, which is easy.  Now the
118 stack is just `[Uniq(0)]`.  Now we use `y` again and... blast!  Its tag is not
119 on the stack.  We have undefined behavior.
120
121 In case you got lost, here is the source code with comments indicating the tags
122 and the stack of the one location that interests us:
123
124 {% highlight rust %}
125 fn demo0() {
126   let x = &mut 1u8; // tag: `Uniq(0)`
127   // stack: [Uniq(0)]
128
129   let y = &mut *x; // tag: `Uniq(1)`
130   // stack: [Uniq(0), Uniq(1)]
131
132   // Pop until `Uniq(1)`, the tag of `y`, is on top of the stack:
133   // Nothing changes.
134   *y = 5;
135   // stack: [Uniq(0), Uniq(1)]
136
137   // Pop until `Uniq(0)`, the tag of `x`, is on top of the stack:
138   // We pop `Uniq(1)`.
139   *x = 3;
140   // stack: [Uniq(0)]
141
142   // Pop until `Uniq(1)`, the tag of `y`, is on top of the stack:
143   // That is not possible, hence we have undefined behavior.
144   let _val = *y;
145 }
146 {% endhighlight %}
147
148 Well, actually having undefined behavior here is good news, since that's what we
149 wanted from the start!  And since there is an implementation of the model in
150 [Miri](https://github.com/solson/miri/), you can try this yourself: The amazing
151 @shepmaster has integrated Miri into the playground, so you can
152 [put the example there](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=d15868687f79072688a0d0dd1e053721)
153 (adjusting it slightly to circumvent the borrow checker), then select "Tools -
154 Miri" and it will complain (together with a rather unreadable backtrace, we sure
155 have to improve that one):
156
157 ```
158 error[E0080]: constant evaluation error: Borrow being dereferenced (Uniq(1037)) does not exist on the stack
159  --> src/main.rs:6:14
160   |
161 6 |   let _val = *y;
162   |              ^^ Borrow being dereferenced (Uniq(1037)) does not exist on the stack
163   |
164 ```
165
166 ## 2 Enabling Sharing
167
168 If we just had unique pointers, Rust would be a rather dull language.  Luckily
169 enough, there are also two ways to have shared access to a location: through
170 shared references (safely), and through raw pointers (unsafely).  Moreover,
171 shared references *sometimes* (but not when they point to an `UnsafeCell`)
172 assert an additional guarantee: Their destination is immutable.
173
174 For example, we want the following code to be allowed -- not least because this
175 is actually safe code accepted by the borrow checker, so we better make sure
176 this is not undefined behavior:
177
178 {% highlight rust %}
179 fn demo1() {
180   let x = &mut 1u8;
181   // Create several shared references, and we can also still read from `x`
182   let y1 = &*x;
183   let _val = *x;
184   let y2 = &*x;
185   let _val = *y1;
186   let _val = *y2;
187 }
188 {% endhighlight %}
189
190 However, the following code is *not* okay:
191
192 {% highlight rust %}
193 fn demo2() {
194   let x = &mut 1u8;
195   let y = &*x;
196   // Create raw reference aliasing `y` and write through it
197   let z = x as *const u8 as *mut u8;
198   unsafe { *z = 3; }
199   // Use `y` again, asserting it still points to the same value
200   let _val = *y;
201 }
202 {% endhighlight %}
203
204 If you
205 [try this in Miri](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=1bc8c2f432941d02246fea0808e2e4f4),
206 you will see it complain:
207
208 ```
209  --> src/main.rs:6:14
210   |
211 6 |   let _val = *y;
212   |              ^^ Location is not frozen long enough
213   |
214 ```
215
216 How is it doing that, and what is a "frozen" location?
217
218 To explain this, we have to extend the "shadow state" of our "virtual machine" a
219 bit.  First of all, we introduce a new kind of tag that a pointer can carry: A
220 *shared* tag.  The following Rust type describes the possible tags of a pointer:
221
222 {% highlight rust %}
223 pub type Timestamp = u64;
224 pub enum Borrow {
225     Uniq(Timestamp),
226     Shr(Option<Timestamp>),
227 }
228 {% endhighlight %}
229
230 You can think of the timestamp as a unique ID, but as we will see, for shared
231 references, it is also important to be able to determine which of these IDs was
232 created first.  The timestamp is optional in the shared tag because that tag is
233 also used by raw pointers, and for raw pointers, we are often not able to track
234 when and how they are created (for example, when raw pointers are converted to
235 integers and back).
236
237 We use a separate type for the items on our stack, because there we do not need
238 a timestamp for shared pointers:
239
240 {% highlight rust %}
241 pub enum BorStackItem {
242     Uniq(Timestamp),
243     Shr,
244 }
245 {% endhighlight %}
246
247 And finally, a "borrow stack" consists of a stack of `BorStackItem`, together
248 with an indication of whether the stack (and the location it governs) is
249 currently *frozen*, meaning it may only be read, not written:
250
251 {% highlight rust %}
252 pub struct Stack {
253     borrows: Vec<BorStackItem>, // used as a stack; never empty
254     frozen_since: Option<Timestamp>, // virtual frozen "item" on top of the stack
255 }
256 {% endhighlight %}
257
258 ### 2.1 Executing the Examples
259
260 Let us now look at what happens when we execute our two example programs.  To
261 this end, I will embed comments in the source code.  There is only one location
262 of interest here, so whenever I talk about a "stack", I am referring to the
263 stack of that location.
264
265 {% highlight rust %}
266 fn demo1() {
267   let x = &mut 1u8; // tag: `Uniq(0)`
268   // stack: [Uniq(0)]; not frozen
269
270   let y1 = &*x; // tag: `Shr(Some(1))`
271   // stack: [Uniq(0), Shr]; frozen since 1
272
273   // Access through `x`.  We first check whether its tag `Uniq(0)` is in the
274   // stack (it is).  Next, we make sure that either our item *or* `Shr` is on
275   // top *or* the location is frozen.  The latter is the case, so we go on.
276   let _val = *x;
277   // stack: [Uniq(0), Shr]; frozen since 1
278
279   // This is not an access, but we still dereference `x`, so we do the same
280   // actions as on a read.  Just like in the previous line, nothing happens.
281   let y2 = &*x; // tag: `Shr(Some(2))`
282   // stack: [Uniq(0), Shr]; frozen since 1
283
284   // Access through `y1`.  Since the shared tag has a timestamp (1) and the type
285   // (`u8`) does not allow interior mutability (no `UnsafeCell`), we check that
286   // the location is frozen since (at least) that timestamp.  It is.
287   let _val = *y1;
288   // stack: [Uniq(0), Shr]; frozen since 1
289
290   // Same as with `y2`: The location is frozen at least since 2 (actually, it
291   // is frozen since 1), so we are good.
292   let _val = *y2;
293   // stack: [Uniq(0), Shr]; frozen since 1
294 }
295 {% endhighlight %}
296
297 This example demonstrates a few new aspects.  First of all, there are actually
298 two operations that perform tag-related checks in this model (so far):
299 Dereferencing a pointer (whenever you have a `*`, also implicitly), and actual
300 memory accesses.  Operations like `&*x` are an example of operations that
301 dereference a pointer without accessing memory.  Secondly, *reading* through a
302 mutable reference is actually okay *even when that reference is not exclusive*.
303 It is only *writing* through a mutable reference that "re-asserts" its
304 exclusivity.  I will come back to these points later, but let us first go
305 through another example.
306
307 {% highlight rust %}
308 fn demo2() {
309   let x = &mut 1u8; // tag: `Uniq(0)`
310   // stack: [Uniq(0)]; not frozen
311   
312   let y = &*x; // tag: `Shr(Some(1))`
313   // stack: [Uniq(0), Shr]; frozen since 1
314
315   // The `x` here really is a `&*x`, but we have already seen above what
316   // happens: `Uniq(0)` must be in the stack, but we leave it unchanged.
317   let z = x as *const u8 as *mut u8; // tag erased: `Shr(None)`
318   // stack: [Uniq(0), Shr]; frozen since 1
319
320   // A write access through a raw pointer: Unfreeze the location and make sure
321   // that `Shr` is at the top of the stack.
322   unsafe { *z = 3; }
323   // stack: [Uniq(0), Shr]; not frozen
324
325   // Access through `y`.  There is a timestamp in the `Shr` tag, and the type
326   // `u8` does not allow interior mutability, but the location is not frozen.
327   // This is undefined behavior.
328   let _val = *y;
329 }
330 {% endhighlight %}
331
332 ### 2.2 Dereferencing a Pointer
333 [section 2.2]: #22-dereferencing-a-pointer
334
335 As we have seen, we consider the tag of a pointer already when dereferencing it,
336 before any memory access happens.  The operation on a dereference never mutates
337 the stack, but it performs some basic checks that might declare the program UB.
338 The reason for this is twofold: First of all, I think we should require some
339 basic validity for pointers that are dereferenced even when they do not access
340 memory. Secondly, there is the practical concern for the implementation in Miri:
341 When we dereference a pointer, we are guaranteed to have type information
342 available (crucial for things that depend on the presence of an `UnsafeCell`),
343 whereas having type information on every memory access would be quite hard to
344 achieve in Miri.
345
346 Notice that on a dereference, we have *both* a tag at the pointer *and* the type
347 of a pointer, and the two might not agree, which we do not always want to rule
348 out (after a `transmute`, we might have raw or shared pointers with a unique
349 tag, for example).
350
351 The following checks are done on every pointer dereference, for every location
352 covered by the pointer (`size_of_val` tells us how many bytes the pointer
353 covers):
354
355 1. If this is a raw pointer, do nothing.  Raw accesses are checked as little as possible.
356 2. If this is a unique reference and the tag is `Shr(Some(_))`, that's an error.
357 3. If the tag is `Uniq`, make sure there is a matching `Uniq` item with the same
358    ID on the stack.
359 4. If the tag is `Shr(None)`, make sure that either the location is frozen or
360    else there is a `Shr` item on the stack.
361 5. If the tag is `Shr(Some(t))`, then the check depends on whether the location
362    is inside an `UnsafeCell` or not, according to the type of the reference.
363     - Locations outside `UnsafeCell` must have `frozen_since` set to `t` or an
364       older timestamp.
365     - `UnsafeCell` locations must either be frozen or else have a `Shr` item in
366       their stack (same check as if the tag had no timestamp).
367
368 ### 2.3 Accessing Memory
369 [section 2.3]: #23-accessing-memory
370
371 On an actual memory access, we know the tag of the pointer that was used to
372 access (we always use the actual tag and disregard the type of the pointer), and
373 we know whether we are reading from or writing to the current location.  We
374 perform the following operations on all locations affected by the access:
375
376 1. If the location is frozen and this is a read access, nothing happens (even
377    if the tag is `Uniq`).
378 2. Otherwise, if this is a write access, unfreeze the location (set
379    `frozen_since` to `None`).  (If this is a read access and we come here, the
380    location is already unfrozen.)
381 3. Pop the stack until the top item matches the tag of the pointer.
382     - A `Uniq` item matches a `Uniq` tag with the same ID.
383     - A `Shr` item matches any `Shr` tag (with or without timestamp).
384     - When we are reading, a `Shr` item matches a `Uniq` tag.
385
386     If we pop the entire stack without finding a match, then we have undefined
387     behavior.
388
389 To understand these rules better, try going back through the three examples we
390 have seen so far and applying these rules for dereferencing pointers and
391 accessing memory to understand how they interact.
392
393 The most subtle point here is that we make a `Uniq` tag match a `Shr` item and
394 also accept `Uniq` reads on frozen locations.  This is required to make `demo1`
395 work: Rust permits read accesses through mutable references even when they are
396 not currently actually unique.  Our model hence has to do the same.
397
398 ## 3 Retagging and Creating Raw Pointers
399
400 We have talked quite a bit about what happens when we *use* a pointer.  It is
401 time we take a close look at *how pointers are created*.  However, before we go
402 there, I would like us to consider one more example:
403
404 {% highlight rust %}
405 fn demo3(x: &mut u8) -> u8 {
406     some_function();
407     *x
408 }
409 {% endhighlight %}
410
411 The question is: Can we move the load of `x` to before the function call?
412 Remember that the entire point of Stacked Borrows is to enforce a certain
413 discipline when using references, in particular, to enforce uniqueness of
414 mutable references.  So we should hope that the answer to that question is "yes"
415 (and that, in turn, is good because we might use it for optimizations).
416 Unfortunately, things are not so easy.
417
418 The uniqueness of mutable references entirely rests on the fact that the pointer
419 has a unique tag: If our tag is at the top of the stack (and the location is not
420 frozen), then any access with another tag will pop our item from the stack (or
421 cause undefined behavior).  This is ensured by the memory access checks.  Hence,
422 if our tag is *still* on the stack after some other accesses happened (and we
423 know it is still on the stack every time we dereference the pointer, as per the
424 dereference checks described above), we know that no access through a pointer
425 with a different tag can have happened.
426
427 ### 3.1 Guaranteed Freshness
428
429 However, what if `some_function` has an exact copy of `x`?  We got `x` from our
430 caller (whom we do not trust), maybe they used that same tag for another
431 reference (copied it with `transmute_copy` or so) and gave that to
432 `some_function`?  There is a simple way we can circumvent this concern: Generate
433 a new tag for `x`.  If *we* generate the tag (and we know generation never emits
434 the same tag twice, which is easy), we can be sure this tag is not used for any
435 other reference.  So let us make this explicit by putting a `Retag` instruction
436 into the code where we generate new tags:
437
438 {% highlight rust %}
439 fn demo3(x: &mut u8) -> u8 {
440     Retag(x);
441     some_function();
442     *x
443 }
444 {% endhighlight %}
445
446 These `Retag` instructions are inserted by the compiler pretty much any time
447 references are copied: At the beginning of every function, all inputs of
448 reference type get retagged.  On every assignment, if the assigned value is of
449 reference type, it gets retagged.  Moreover, we do this even when the reference
450 value is inside the field of a `struct` or `enum`, to make sure we really cover
451 all references.  (This recursive descent is already implemented, but the
452 implementation has not landed yet.)  Finally, `Box` is treated like a mutable
453 reference, to encode that it asserts unique access.  However, we do *not*
454 descend recursively through references: Retagging a `&mut &mut u8` will only
455 retag the *outer* reference.
456
457 Retagging is the *only* operation that generates fresh tags.  Taking a reference
458 simply forwards the tag of the pointer we are basing this reference on.
459
460 Here is our very first example with explicit retagging:
461
462 {% highlight rust %}
463 fn demo0() {
464   let x = &mut 1u8; // nothing interesting happens here
465   Retag(x); // tag of `x` gets changed to `Uniq(0)`
466   // stack: [Uniq(0)]; not frozen
467   
468   let y = &mut *x; // nothing interesting happens here
469   Retag(y); // tag of `y` gets changed to `Uniq(1)`
470   // stack: [Uniq(0), Uniq(1)]; not frozen
471
472   // Check that `Uniq(1)` is on the stack, then pop to bring it to the top.
473   *y = 5;
474   // stack: [Uniq(0), Uniq(1)]; not frozen
475
476   // Check that `Uniq(0)` is on the stack, then pop to bring it to the top.
477   *x = 3;
478   // stack: [Uniq(0)]; not frozen
479
480   // Check that `Uniq(1)` is on the stack -- it is not, hence UB.
481   let _val = *y;
482 }
483 {% endhighlight %}
484
485 For each reference and `Box`, `Retag` does the following (we will slightly
486 refine these instructions later) on all locations covered by the reference
487 (again, according to `size_of_val`):
488
489 1. Compute a fresh tag: `Uniq(_)` for mutable references and `Box`, and
490    `Shr(Some(_))` for shared references.
491 2. Perform the checks that would also happen when we dereference this reference.
492 3. Perform the actions that would also happen when an actual access happens
493    through this reference (for shared references a read access, for mutable
494    references a write access).
495 4. Check if the new tag is `Shr(Some(t))` and the location is inside an `UnsafeCell`.
496     - If both conditions apply, freeze the location with timestamp `t`.  If it
497       is already frozen, do nothing.
498     - Otherwise, push a new item onto the stack: `Shr` if the tag is a `Shr(_)`,
499       `Uniq(id)` if the tag is `Uniq(id)`.
500
501 One high-level way to think about retagging is that it computes a fresh tag, and
502 then performs a reborrow of the old reference with the new tag.
503
504 ### 3.2 When Pointers Escape
505
506 Creating a shared reference is not the only way to share a location: We can also
507 create raw pointers, and if we are careful enough, use them to access a location
508 from different aliasing pointers.  (Of course, "careful enough" is not very
509 precise, but the precise answer is the very model I am describing here.)
510
511 To account for this, we consider the act of casting to a raw pointer as a
512 special way of creating a reference
513 (["creating a raw reference"](https://github.com/rust-lang/rfcs/pull/2582), so
514 to speak).  As usual for creating a new reference, that operation is followed by
515 retagging.  This retagging is special though because unlike normal retagging it
516 acts on raw pointers.  Consider the
517 [following example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=253868e96b7eba85ef28e1eabd557f66):
518
519 {% highlight rust %}
520 fn demo4() {
521   let x = &mut 1u8;
522   Retag(x); // tag of `x` gets changed to `Uniq(0)`
523   // stack: [Uniq(0)]; not frozen
524
525   let y1 = x as *mut u8;
526   // Make sure what `x` points to is accessible through raw pointers.
527   Retag([raw] y1) // tag of `y` gets erased to `Shr(None)`
528   // stack: [Uniq(0), Shr]; not frozen
529
530   let y2 = y1;
531   unsafe {
532     // All of these first dereference a raw pointer (no checks, tag gets
533     // ignored) and then perform a read or write access with `Shr(None)` as
534     // the tag, which is already the top of the stack so nothing changes.
535     *y1 = 3;
536     *y2 = 5;
537     *y2 = *y1;
538   }
539
540   // Writing to `x` again pops `Shr` off the stack, as per the rules for
541   // write accesses.
542   *x = 7;
543   // stack: [Uniq(0)]; not frozen
544
545   // Any further access through the raw pointers is undefined behavior, even
546   // reads: The write to `x` re-asserted that `x` is the unique reference for
547   // this memory.
548   let _val = unsafe { *y1 };
549 }
550 {% endhighlight %}
551
552 `Retag([raw])` acts almost like a normal retag, except that it does not ignore
553 raw pointers and instead tags them `Shr(None)`, and pushes `Shr` to the stack.
554
555 This way, even if the program casts the pointer to an integer and back (where we
556 cannot always keep track of the tag, so it might get reset to `Shr(None)`),
557 there is a matching `Shr` on the stack, making sure the raw pointer can actually
558 be used.  One way to think about this is to consider the reference to "escape"
559 when it is cast to a raw pointer, which is reflected by the `Shr` item on the
560 stack.
561
562 Knowing about how `Retag` interacts with raw pointers, you can now go back to
563 `demo2` and should be able to fully explain why the stack changes the way it
564 does in that example.
565
566 ### 3.3 The Case of the Aliasing References
567
568 Everything I described so far was pretty much in working condition as of about a
569 week ago.  However, there was one thorny problem that I only discovered fairly
570 late, and as usual it is best demonstrated by an example -- entirely in safe
571 code:
572
573 {% highlight rust %}
574 fn demo_refcell() {
575   let rc: &mut RefCell<u8> = &mut RefCell::new(23u8);
576   Retag(rc); // tag gets changed to `Uniq(0)`
577   // We will consider the stack of the location where `23` is stored; the
578   // `RefCell` bookkeeping counters are not of interest.
579   // stack: [Uniq(0)]
580
581   // Taking a shared reference shares the location but does not freeze, due
582   // to the `UnsafeCell`.
583   let rc_shr: &RefCell<u8> = &*rc;
584   Retag(rc_shr); // tag gets changed to `Shr(Some(1))`
585   // stack: [Uniq(0), Shr]; not frozen
586
587   // Lots of stuff happens here but it does not matter for this example.
588   let mut bmut: RefMut<u8> = rc_shr.borrow_mut();
589   
590   // Obtain a mutable reference into the `RefCell`.
591   let mut_ref: &mut u8 = &mut *bmut;
592   Retag(mut_ref); // tag gets changed to `Uniq(2)`
593   // stack: [Uniq(0), Shr, Uniq(2)]; not frozen
594   
595   // And at the same time, a fresh shared reference to its outside!
596   // This counts as a read access through `rc`, so we have to pop until
597   // at least a `Shr` is at the top of the stack.
598   let shr_ref: &RefCell<u8> = &*rc; // tag gets changed to `Shr(Some(3))`
599   Retag(shr_ref);
600   // stack: [Uniq(0), Shr]; not frozen
601
602   // Now using `mut_ref` is UB because its tag is no longer on the stack.  But
603   // that is bad, because it is usable in safe code.
604   *mut_ref += 19;
605 }
606 {% endhighlight %}
607
608 Notice how `mut_ref` and `shr_ref` alias!  And yet, creating a shared reference
609 to the memory already covered by our unique `mut_ref` must not invalidate
610 `mut_ref`.  If we follow the instructions above, when we retag `shr_ref` after
611 it got created, we have no choice but pop the item matching `mut_ref` off the
612 stack.  Ouch.
613
614 This made me realize that creating a shared reference has to be very weak inside
615 `UnsafeCell`.  In fact, it is entirely equivalent to `Retag([raw])`: We just
616 have to make sure some kind of shared access is possible, but we have to accept
617 that there might be active mutable references assuming exclusive access to the
618 same locations.  That on its own is not enough, though.
619
620 I also added a new check to the retagging procedure: Before taking any action
621 (i.e., before step 3, which could pop items off the stack), we check if the
622 reborrow is redundant: If the new reference we want to create is already
623 dereferencable (because its item is already on the stack and, if applicable, the
624 stack is already frozen), *and* if the item that justifies this is moreover
625 "derived from" the item that corresponds to the old reference, then we just do
626 nothing.  Here, "derived from" means "further up the stack".  Basically, the
627 reborrow has already happened and the new reference is ready for use; *and*
628 because of that "derived from" check, we know that using the new reference will
629 *not* pop the item corresponding to the old reference off the stack.  In that
630 case, we avoid popping anything, to keep other references valid.
631
632 It may seem like this rule can never apply, because how can our fresh tag match
633 something that's already on the stack?  This is indeed impossible for `Uniq`
634 tags, but for `Shr` tags, matching is more liberal.  For example, this rule
635 applies in our example above when we create `shr_ref` from `mut_ref`.  We do not
636 require freezing (because there is an `UnsafeCell`), there is already a `Shr` on
637 the stack (so the new reference is dereferencable) and the item matching the old
638 reference (`Uniq(0)`) is below that `Shr` (so after using the new reference, the
639 old one remains dereferencable).  Hence we do nothing, keeping the `Uniq(2)` on
640 the stack, such that the access through `mut_ref` at the end remains valid.
641
642 This may sound like a weird rule, and it is.  I would surely not have thought of
643 this if `RefCell` would not force our hands here.  However, as we shall see in
644 [section 5], it also does not to break any of the important properties of the
645 model (mutable references being unique and shared references being immutable
646 except for `UnsafeCell`).  Moreover, when pushing an item to the stack (at the
647 end of the retag action), we can now be sure that the stack is not yet frozen:
648 if it were frozen, the reborrow would be redundant.
649
650 With this extension, the instructions for `Retag` now look as follows (again
651 executed on all locations covered by the reference, according to `size_of_val`):
652
653 1. Compute a fresh tag: `Uniq(_)` for mutable references, `Box`, `Shr(Some(_))`
654    for shared references, and `Shr(None)` for raw pointers.
655 2. Perform the checks that would also happen when we dereference this reference.
656    Remember the position of the item matching the tag in the stack.
657 3. Redundancy check: If the new tag passes the checks performed on a
658    dereference, and if the item that makes this check succeed is *above* the one
659    we remembered in step 2 (where the "frozen" state is considered above every
660    item in the stack), then stop.  We are done for this location.
661 4. Perform the actions that would also happen when an actual access happens
662    through this reference (for shared references a read access, for mutable
663    references a write access).<br>
664    Now the location cannot be frozen any more: If the fresh tag is `Uniq`, we
665    just unfroze; if the fresh tag is `Shr` and the location was already frozen,
666    then the redundancy check (step 3) would have kicked in.
667 5. Check if the new tag is `Shr(Some(t))` and the location is inside an `UnsafeCell`.
668     - If both conditions apply, freeze the location with timestamp `t`.  If it
669       is already frozen, do nothing.
670     - Otherwise, push a new item onto the stack: `Shr` if the tag is a `Shr(_)`,
671       `Uniq(id)` if the tag is `Uniq(id)`.
672
673 The one thing I find slightly unsatisfying about the redundancy check is that it
674 seems to overlap a bit with the rule that on a *read* access, a `Shr` item
675 matches a `Uniq` tag.  Both of these together enable the read-only use of
676 mutable references that have already been shared; I would prefer to have a
677 single condition enabling that instead of two working together.  Still, overall
678 I think this is a pleasingly clean model; certainly much cleaner than what I
679 proposed last year and at the same time much more compatible with existing code.
680
681 ## 4 Differences to the Original Proposal
682 [section 4]: #4-differences-to-the-original-proposal
683
684 The key differences to the original proposal is that the check performed on a
685 dereference, and the check performed on an access, are not the same check.  This
686 means there are more "moving parts" in the model, but it also means we do not
687 need a weird special exception (about reads from frozen locations) for `demo1`
688 any more like the original proposal did.  The main reason for this change,
689 however, is that on an access, we just do not know if we are inside an
690 `UnsafeCell` or not, so we cannot do all the checks we would like to do.
691 Accordingly, I also rearranged terminology a bit.  There is no longer one
692 "reactivation" action, instead there is a "deref" check and an "access" action,
693 as described above in sections [2.2][section 2.2] and [2.3][section 2.3].
694
695 Beyond that, I made the behavior of shared references and raw pointers more
696 uniform.  This helped to fix test failures around `iter_mut` on slices, which
697 first creates a raw reference and then a shared reference: In the original
698 model, creating the shared reference invalidates previously created raw
699 pointers.  As a result of the more uniform treatment, this no longer happens.
700 (Coincidentally, I did not make this change with the intention of fixing
701 `iter_mut`.  I did this change because I wanted to reduce the number of case
702 distinctions in the model.  Then I realized the relevant test suddenly passed
703 even with the full model enabled, investigated what happened, and realized I
704 accidentally had had a great idea. :D )
705
706 The tag is now "typed" (`Uniq` vs `Shr`) to be able to support `transmute`
707 between references and shared pointers.  Such `transmute` were an open question
708 in the original model and some people raised concerns about it in the ensuing
709 discussion.  I invite all of you to come up with strange things you think you
710 should be able to `transmute` and throw them at Miri so that we can see if your
711 use-cases are covered. :)
712
713 The redundancy check during retagging can be seen as refining a similar check
714 that the original model did whenever a new reference was created (where we
715 wouldn't change the state if the new borrow is already active).
716
717 Finally, the notion of "function barriers" from the original Stacked Borrows has
718 not been implemented yet.  This is the next item on my todo list.
719
720 ## 5 Key Properties
721 [section 5]: #5-key-properties
722
723 Let us look at the two key properties that I set out as design goals, and see
724 how the model guarantees that they hold true in all valid (UB-free) executions.
725
726 ### 5.1 Mutable References are Unique
727
728 The property I would like to establish here is that: After creating (retagging,
729 really) a `&mut`, if we then run some unknown code *that does not get passed the
730 reference*, and then we use the reference again (reading or writing), we can be
731 sure that this unknown code did not access the memory behind our mutable
732 reference at all (or we have UB).  For example:
733
734 {% highlight rust %}
735 fn demo_mut_unique(our: &mut i32) -> i32 {
736   Retag(our); // So we can be sure the tag is unique
737
738   *our = 5;
739
740   unknown_code();
741
742   // We know this will return 5, and moreover if `unknown_code` does not panic
743   // we know we could do the write after calling `unknown_code` (because it
744   // cannot even read from `our`).
745   *our
746 }
747 {% endhighlight %}
748
749 The proof sketch goes as follows: After retagging the reference, we know it is
750 at the top of the stack and the location is not frozen.  (The "redundant
751 reborrow" rule does not apply because a fresh `Uniq` tag can never be
752 redundant.)  For any access performed by the unknown code, we know that access
753 cannot use the tag of our reference because the tags are unique and not
754 forgeable.  Hence if the unknown code accesses our locations, that would pop our
755 tag from the stack.  When we use our reference again, we know it is on the
756 stack, and hence has not been popped off.  Thus there cannot have been an access
757 from the unknown code.
758
759 Actually this theorem applies *any time* we have a reference whose tag we can be
760 sure has not been leaked to anyone else, and which points to locations which
761 have this tag at the top of the (unfrozen) stack.  This is not just the case
762 immediately after retagging.  We know our reference is at the top of the stack
763 after writing to it, so in the following example we know that `unknown_code_2`
764 cannot access `our`:
765
766 {% highlight rust %}
767 fn demo_mut_advanced_unique(our: &mut u8) -> u8 {
768   Retag(our); // So we can be sure the tag is unique
769
770   unknown_code_1(&*our);
771
772   // This "re-asserts" uniqueness of the reference: After writing, we know
773   // our tag is at the top of the stack.
774   *our = 5;
775
776   unknown_code_2();
777
778   // We know this will return 5
779   *our
780 }
781 {% endhighlight %}
782
783 ### 5.2 Shared References (without `UnsafeCell)` are Immutable
784
785 The key property of shared references is that: After creating (retagging,
786 really) a shared reference, if we then run some unknown code (it can even have
787 our reference if it wants), and then we use the reference again, we know that
788 the value pointed to by the reference has not been changed.  For example:
789
790 {% highlight rust %}
791 fn demo_shr_frozen(our: &u8) -> u8 {
792   Retag(our); // So we can be sure the tag actually carries a timestamp
793
794   // See what's in there.
795   let val = *our;
796   
797   unknown_code(our);
798
799   // We know this will return `val`
800   *our
801 }
802 {% endhighlight %}
803
804 The proof sketch goes as follows: After retagging the reference, we know the
805 location is frozen (this is the case even if the "redundant reborrow" rule
806 applies).  If the unknown code does any write, we know this will unfreeze the
807 location.  The location might get re-frozen, but only at the then-current
808 timestamp.  When we do our read after coming back from the unknown code, this
809 checks that the location is frozen *at least* since the timestamp given in its
810 tag, so if the location is unfrozen or got re-frozen by the unknown code, the
811 check would fail.  Thus the unknown code cannot have written to the location.
812
813 One interesting observation here for both of these proofs is that all we rely on
814 when the unknown code is executed are the actions performed on every memory
815 access.  The additional checks that happen when a pointer is dereferenced only
816 matter in *our* code, not in the foreign code.  Hence we have no problem
817 reasoning about the case where we call some code via FFI that is written in a
818 language without a notion of "dereferencing", all we care about is the actual
819 memory accesses performed by that foreign code.  This also indicates that we
820 could see the checks on pointer dereference as another "shadow state operation"
821 next to `Retag`, and then these two operations plus the actions on memory
822 accesses are all that there is to Stacked Borrows.  This is difficult to
823 implement in Miri because dereferences can happen any time a path is evaluated,
824 but it is nevertheless interesting and might be useful in a "lower-level MIR"
825 that does not permit dereferences in paths.
826
827 ## 6 Evaluation, and How You Can Help
828 [section 6]: #6-evaluation-and-how-you-can-help
829
830 I have implemented both the validity invariant and the model as described above
831 in Miri. This [uncovered](https://github.com/rust-lang/rust/issues/54908) two
832 [issues](https://github.com/rust-lang/rust/issues/54957) in the standard
833 library, but both were related to validity invariants, not Stacked Borrows.
834 With these exceptions, the model passes the entire test suite.  There were some
835 more test failures in earlier versions (as mentioned in [section 4]), but the
836 final model accepts all the code covered by Miri's test suite.  (If you look
837 close enough, you can see that three libstd methods are currently whitelisted
838 and what they do is not checked.  However, even before I ran into these cases,
839 [efforts](https://github.com/rust-lang/rust/pull/54668) were already
840 [underway](https://github.com/rust-lang/rfcs/pull/2582) that would fix all of
841 them, so I am not concerned about them.)  Moreover I wrote a bunch of
842 compile-fail tests to make sure the model catches various violations of the key
843 properties it should ensure.
844
845 The most interesting change I had to make to libstd is
846 [in `NonNull::from`](https://github.com/rust-lang/rust/pull/56161).  That
847 function turned a `&mut T` into a `*const T` going through a `&T`.  This means
848 that the final raw pointer was created from a shared reference, and hence must
849 not be used for mutation.  An earlier version of this post described a model
850 that would permit such behavior, but I think we should actually at least
851 experiment with ruling it out: "no mutation through (pointers derived from)
852 shared references" is an old rule in Rust, after all.
853
854 Overall, I am quite happy with this!  I was expecting much more trouble, expecting to run
855 into cases where libstd does strange things that are common or otherwise hard to
856 declare illegal and that my model could not reasonably allow.  I see the test
857 suite passing as an indication that this model may be well-suited for Rust.
858
859 However, Miri's test suite is tiny, and I have but one brain to come up with
860 counterexamples!  In fact I am quite a bit worried because I literally came up
861 with `demo_refcell` less than two weeks ago, so what else might I have missed?
862 This where you come in.  Please test this model!  Come up with something funny
863 you think should work (I am thinking about funny `transmute` in particular,
864 using type punning through unions or raw pointers if you prefer that), or maybe
865 you have some crate that has some unsafe code and a test suite (you do have a
866 test suite, right?) that might run under Miri.
867
868 The easiest way to try the model is the
869 [playground](https://play.rust-lang.org/): Type the code, select "Tools - Miri",
870 and you'll see what it does.
871
872 For things that are too long for the playground, you have to install Miri on
873 your own computer.  Miri depends on rustc nightly and has to be updated
874 regularly to keep working, so it is not well-suited for crates.io.  Instead,
875 installation instructions for Miri are provided
876 [in the README](https://github.com/solson/miri/#running-miri).  We are still
877 working on making installing Miri easier.  Please let me know if you are having
878 trouble with anything.  You can report issues, comment on this post or find me
879 in chat (as of recently, I am partial to Zulip where we have an
880 [unsafe code guidelines stream](https://rust-lang.zulipchat.com/#narrow/stream/136281-wg-unsafe-code-guidelines)).
881
882 With Miri installed, you can `cargo miri` a project with a binary to run it in
883 Miri.  Dependencies should be fully supported, so you can use any crate you
884 like.  It is not unlikely, however, that you will run into issues because Miri
885 does not support some operation.  In that case please search the
886 [issue tracker](https://github.com/solson/miri/issues) and report the issue if
887 it is new.  We cannot support everything, but we might be able to do something
888 for your case.
889
890 Unfortunately, `cargo miri test` is currently broken; if you want to help with
891 that [here are some details](https://github.com/solson/miri/issues/479).
892 Moreover, wouldn't it be nice if we could
893 [run the entire libcore, liballoc and libstd test suite in miri](https://github.com/rust-lang/rust/issues/54914)?
894 There are tons of interesting cases of Rust's core data structures being
895 exercise there, and the comparatively tiny Miri test suite has already helped to
896 find two soundness bugs, so there are probably more.  Once `cargo miri test`
897 works again, it would be great to find a way to run it on the standard library
898 test suites, and set up something so that this happens automatically on a
899 regular basis (so that we notice regressions).
900 **Update:** `cargo miri test` has been fixed in the mean time, so you can use it on your libraries now! **/Update**
901
902 As you can see, there is more than enough work for everyone.  Don't be shy!  I
903 have a mere two weeks left on this internship, after which I will have to
904 significantly reduce my Rust activities in favor of finishing my PhD.  I won't
905 disappear entirely though, don't worry -- I will still be able to mentor you if
906 you want to help with any of the above tasks. :)
907
908 Thanks to @nikomatsakis for feedback on a draft of this post, to @shepmaster for
909 making Miri available on the playground, and to @oli-obk for reviewing all my
910 PRs at unparalleled speed. <3
911
912 If you want to
913 help or report results of your experiments, if you have any questions or
914 comments, please join the
915 [discussion in the forums](https://internals.rust-lang.org/t/stacked-borrows-implemented/8847).
916
917 ## Changelog
918
919 **2018-11-21:** Dereferencing a pointer now always preserves the tag, but
920 casting to a raw pointer resets the tag to `Shr(None)`.  `Box` is treated like a
921 mutable reference.
922
923 **2018-12-22:** Creating a shared reference does not push a `Shr` item to the
924 stack (unless there is an `UnsafeCell`).  Moreover, creating a raw pointer is a
925 special kind of retagging.