]> git.proxmox.com Git - rustc.git/blob - src/doc/book/unsafe.md
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / doc / book / unsafe.md
1 % Unsafe
2
3 Rust’s main draw is its powerful static guarantees about behavior. But safety
4 checks are conservative by nature: there are some programs that are actually
5 safe, but the compiler is not able to verify this is true. To write these kinds
6 of programs, we need to tell the compiler to relax its restrictions a bit. For
7 this, Rust has a keyword, `unsafe`. Code using `unsafe` has fewer restrictions
8 than normal code does.
9
10 Let’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in
11 four contexts. The first one is to mark a function as unsafe:
12
13 ```rust
14 unsafe fn danger_will_robinson() {
15 // scary stuff
16 }
17 ```
18
19 All functions called from [FFI][ffi] must be marked as `unsafe`, for example.
20 The second use of `unsafe` is an unsafe block:
21
22 [ffi]: ffi.html
23
24 ```rust
25 unsafe {
26 // scary stuff
27 }
28 ```
29
30 The third is for unsafe traits:
31
32 ```rust
33 unsafe trait Scary { }
34 ```
35
36 And the fourth is for `impl`ementing one of those traits:
37
38 ```rust
39 # unsafe trait Scary { }
40 unsafe impl Scary for i32 {}
41 ```
42
43 It’s important to be able to explicitly delineate code that may have bugs that
44 cause big problems. If a Rust program segfaults, you can be sure the cause is
45 related to something marked `unsafe`.
46
47 # What does ‘safe’ mean?
48
49 Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also
50 important to know that there are certain behaviors that are probably not
51 desirable in your code, but are expressly _not_ unsafe:
52
53 * Deadlocks
54 * Leaks of memory or other resources
55 * Exiting without calling destructors
56 * Integer overflow
57
58 Rust cannot prevent all kinds of software problems. Buggy code can and will be
59 written in Rust. These things aren’t great, but they don’t qualify as `unsafe`
60 specifically.
61
62 In addition, the following are all undefined behaviors in Rust, and must be
63 avoided, even when writing `unsafe` code:
64
65 * Data races
66 * Dereferencing a null/dangling raw pointer
67 * Reads of [undef][undef] (uninitialized) memory
68 * Breaking the [pointer aliasing rules][aliasing] with raw pointers.
69 * `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if
70 the `&T` contains an `UnsafeCell<U>`. Unsafe code must not violate these
71 aliasing guarantees.
72 * Mutating an immutable value/reference without `UnsafeCell<U>`
73 * Invoking undefined behavior via compiler intrinsics:
74 * Indexing outside of the bounds of an object with `std::ptr::offset`
75 (`offset` intrinsic), with
76 the exception of one byte past the end which is permitted.
77 * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
78 intrinsics) on overlapping buffers
79 * Invalid values in primitive types, even in private fields/locals:
80 * Null/dangling references or boxes
81 * A value other than `false` (0) or `true` (1) in a `bool`
82 * A discriminant in an `enum` not included in its type definition
83 * A value in a `char` which is a surrogate or above `char::MAX`
84 * Non-UTF-8 byte sequences in a `str`
85 * Unwinding into Rust from foreign code or unwinding from Rust into foreign
86 code.
87
88 [noalias]: http://llvm.org/docs/LangRef.html#noalias
89 [undef]: http://llvm.org/docs/LangRef.html#undefined-values
90 [aliasing]: http://llvm.org/docs/LangRef.html#pointer-aliasing-rules
91
92 # Unsafe Superpowers
93
94 In both unsafe functions and unsafe blocks, Rust will let you do three things
95 that you normally can not do. Just three. Here they are:
96
97 1. Access or update a [static mutable variable][static].
98 2. Dereference a raw pointer.
99 3. Call unsafe functions. This is the most powerful ability.
100
101 That’s it. It’s important that `unsafe` does not, for example, ‘turn off the
102 borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its
103 semantics, it won’t start accepting anything. But it will let you write
104 things that _do_ break some of the rules.
105
106 You will also encounter the `unsafe` keyword when writing bindings to foreign
107 (non-Rust) interfaces. You're encouraged to write a safe, native Rust interface
108 around the methods provided by the library.
109
110 Let’s go over the basic three abilities listed, in order.
111
112 ## Access or update a `static mut`
113
114 Rust has a feature called ‘`static mut`’ which allows for mutable global state.
115 Doing so can cause a data race, and as such is inherently not safe. For more
116 details, see the [static][static] section of the book.
117
118 [static]: const-and-static.html#static
119
120 ## Dereference a raw pointer
121
122 Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of
123 different memory safety and security issues. In some senses, the ability to
124 dereference an arbitrary pointer is one of the most dangerous things you can
125 do. For more on raw pointers, see [their section of the book][rawpointers].
126
127 [rawpointers]: raw-pointers.html
128
129 ## Call unsafe functions
130
131 This last ability works with both aspects of `unsafe`: you can only call
132 functions marked `unsafe` from inside an unsafe block.
133
134 This ability is powerful and varied. Rust exposes some [compiler
135 intrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass
136 safety checks, trading safety for speed.
137
138 I’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks
139 and functions doesn’t mean you should. The compiler will act as though you’re
140 upholding its invariants, so be careful!
141
142 [intrinsics]: intrinsics.html