]> git.proxmox.com Git - rustc.git/blob - src/doc/nomicon/poisoning.md
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / doc / nomicon / poisoning.md
1 % Poisoning
2
3 Although all unsafe code *must* ensure it has minimal exception safety, not all
4 types ensure *maximal* exception safety. Even if the type does, your code may
5 ascribe additional meaning to it. For instance, an integer is certainly
6 exception-safe, but has no semantics on its own. It's possible that code that
7 panics could fail to correctly update the integer, producing an inconsistent
8 program state.
9
10 This is *usually* fine, because anything that witnesses an exception is about
11 to get destroyed. For instance, if you send a Vec to another thread and that
12 thread panics, it doesn't matter if the Vec is in a weird state. It will be
13 dropped and go away forever. However some types are especially good at smuggling
14 values across the panic boundary.
15
16 These types may choose to explicitly *poison* themselves if they witness a panic.
17 Poisoning doesn't entail anything in particular. Generally it just means
18 preventing normal usage from proceeding. The most notable example of this is the
19 standard library's Mutex type. A Mutex will poison itself if one of its
20 MutexGuards (the thing it returns when a lock is obtained) is dropped during a
21 panic. Any future attempts to lock the Mutex will return an `Err` or panic.
22
23 Mutex poisons not for true safety in the sense that Rust normally cares about. It
24 poisons as a safety-guard against blindly using the data that comes out of a Mutex
25 that has witnessed a panic while locked. The data in such a Mutex was likely in the
26 middle of being modified, and as such may be in an inconsistent or incomplete state.
27 It is important to note that one cannot violate memory safety with such a type
28 if it is correctly written. After all, it must be minimally exception-safe!
29
30 However if the Mutex contained, say, a BinaryHeap that does not actually have the
31 heap property, it's unlikely that any code that uses it will do
32 what the author intended. As such, the program should not proceed normally.
33 Still, if you're double-plus-sure that you can do *something* with the value,
34 the Mutex exposes a method to get the lock anyway. It *is* safe, after all.
35 Just maybe nonsense.