]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/unsafe.md
debuginfo: Make debuginfo source location assignment more stable (Pt. 1)
[rust.git] / src / doc / trpl / unsafe.md
1 % Unsafe and Low-Level Code
2
3 # Introduction
4
5 Rust aims to provide safe abstractions over the low-level details of
6 the CPU and operating system, but sometimes one needs to drop down and
7 write code at that level. This guide aims to provide an overview of
8 the dangers and power one gets with Rust's unsafe subset.
9
10 Rust provides an escape hatch in the form of the `unsafe { ... }`
11 block which allows the programmer to dodge some of the compiler's
12 checks and do a wide range of operations, such as:
13
14 - dereferencing [raw pointers](#raw-pointers)
15 - calling a function via FFI ([covered by the FFI guide](ffi.html))
16 - casting between types bitwise (`transmute`, aka "reinterpret cast")
17 - [inline assembly](#inline-assembly)
18
19 Note that an `unsafe` block does not relax the rules about lifetimes
20 of `&` and the freezing of borrowed data.
21
22 Any use of `unsafe` is the programmer saying "I know more than you" to
23 the compiler, and, as such, the programmer should be very sure that
24 they actually do know more about why that piece of code is valid.  In
25 general, one should try to minimize the amount of unsafe code in a
26 code base; preferably by using the bare minimum `unsafe` blocks to
27 build safe interfaces.
28
29 > **Note**: the low-level details of the Rust language are still in
30 > flux, and there is no guarantee of stability or backwards
31 > compatibility. In particular, there may be changes that do not cause
32 > compilation errors, but do cause semantic changes (such as invoking
33 > undefined behaviour). As such, extreme care is required.
34
35 # Pointers
36
37 ## References
38
39 One of Rust's biggest features is memory safety.  This is achieved in
40 part via [the ownership system](ownership.html), which is how the
41 compiler can guarantee that every `&` reference is always valid, and,
42 for example, never pointing to freed memory.
43
44 These restrictions on `&` have huge advantages. However, they also
45 constrain how we can use them. For example, `&` doesn't behave
46 identically to C's pointers, and so cannot be used for pointers in
47 foreign function interfaces (FFI). Additionally, both immutable (`&`)
48 and mutable (`&mut`) references have some aliasing and freezing
49 guarantees, required for memory safety.
50
51 In particular, if you have an `&T` reference, then the `T` must not be
52 modified through that reference or any other reference. There are some
53 standard library types, e.g. `Cell` and `RefCell`, that provide inner
54 mutability by replacing compile time guarantees with dynamic checks at
55 runtime.
56
57 An `&mut` reference has a different constraint: when an object has an
58 `&mut T` pointing into it, then that `&mut` reference must be the only
59 such usable path to that object in the whole program. That is, an
60 `&mut` cannot alias with any other references.
61
62 Using `unsafe` code to incorrectly circumvent and violate these
63 restrictions is undefined behaviour. For example, the following
64 creates two aliasing `&mut` pointers, and is invalid.
65
66 ```
67 use std::mem;
68 let mut x: u8 = 1;
69
70 let ref_1: &mut u8 = &mut x;
71 let ref_2: &mut u8 = unsafe { mem::transmute(&mut *ref_1) };
72
73 // oops, ref_1 and ref_2 point to the same piece of data (x) and are
74 // both usable
75 *ref_1 = 10;
76 *ref_2 = 20;
77 ```
78
79 ## Raw pointers
80
81 Rust offers two additional pointer types (*raw pointers*), written as
82 `*const T` and `*mut T`. They're an approximation of C's `const T*` and `T*`
83 respectively; indeed, one of their most common uses is for FFI,
84 interfacing with external C libraries.
85
86 Raw pointers have much fewer guarantees than other pointer types
87 offered by the Rust language and libraries. For example, they
88
89 - are not guaranteed to point to valid memory and are not even
90   guaranteed to be non-null (unlike both `Box` and `&`);
91 - do not have any automatic clean-up, unlike `Box`, and so require
92   manual resource management;
93 - are plain-old-data, that is, they don't move ownership, again unlike
94   `Box`, hence the Rust compiler cannot protect against bugs like
95   use-after-free;
96 - are considered sendable (if their contents is considered sendable),
97   so the compiler offers no assistance with ensuring their use is
98   thread-safe; for example, one can concurrently access a `*mut i32`
99   from two threads without synchronization.
100 - lack any form of lifetimes, unlike `&`, and so the compiler cannot
101   reason about dangling pointers; and
102 - have no guarantees about aliasing or mutability other than mutation
103   not being allowed directly through a `*const T`.
104
105 Fortunately, they come with a redeeming feature: the weaker guarantees
106 mean weaker restrictions. The missing restrictions make raw pointers
107 appropriate as a building block for implementing things like smart
108 pointers and vectors inside libraries. For example, `*` pointers are
109 allowed to alias, allowing them to be used to write shared-ownership
110 types like reference counted and garbage collected pointers, and even
111 thread-safe shared memory types (`Rc` and the `Arc` types are both
112 implemented entirely in Rust).
113
114 There are two things that you are required to be careful about
115 (i.e. require an `unsafe { ... }` block) with raw pointers:
116
117 - dereferencing: they can have any value: so possible results include
118   a crash, a read of uninitialised memory, a use-after-free, or
119   reading data as normal.
120 - pointer arithmetic via the `offset` [intrinsic](#intrinsics) (or
121   `.offset` method): this intrinsic uses so-called "in-bounds"
122   arithmetic, that is, it is only defined behaviour if the result is
123   inside (or one-byte-past-the-end) of the object from which the
124   original pointer came.
125
126 The latter assumption allows the compiler to optimize more
127 effectively. As can be seen, actually *creating* a raw pointer is not
128 unsafe, and neither is converting to an integer.
129
130 ### References and raw pointers
131
132 At runtime, a raw pointer `*` and a reference pointing to the same
133 piece of data have an identical representation. In fact, an `&T`
134 reference will implicitly coerce to an `*const T` raw pointer in safe code
135 and similarly for the `mut` variants (both coercions can be performed
136 explicitly with, respectively, `value as *const T` and `value as *mut T`).
137
138 Going the opposite direction, from `*const` to a reference `&`, is not
139 safe. A `&T` is always valid, and so, at a minimum, the raw pointer
140 `*const T` has to point to a valid instance of type `T`. Furthermore,
141 the resulting pointer must satisfy the aliasing and mutability laws of
142 references. The compiler assumes these properties are true for any
143 references, no matter how they are created, and so any conversion from
144 raw pointers is asserting that they hold. The programmer *must*
145 guarantee this.
146
147 The recommended method for the conversion is
148
149 ```
150 let i: u32 = 1;
151 // explicit cast
152 let p_imm: *const u32 = &i as *const u32;
153 let mut m: u32 = 2;
154 // implicit coercion
155 let p_mut: *mut u32 = &mut m;
156
157 unsafe {
158     let ref_imm: &u32 = &*p_imm;
159     let ref_mut: &mut u32 = &mut *p_mut;
160 }
161 ```
162
163 The `&*x` dereferencing style is preferred to using a `transmute`.
164 The latter is far more powerful than necessary, and the more
165 restricted operation is harder to use incorrectly; for example, it
166 requires that `x` is a pointer (unlike `transmute`).
167
168
169
170 ## Making the unsafe safe(r)
171
172 There are various ways to expose a safe interface around some unsafe
173 code:
174
175 - store pointers privately (i.e. not in public fields of public
176   structs), so that you can see and control all reads and writes to
177   the pointer in one place.
178 - use `assert!()` a lot: since you can't rely on the protection of the
179   compiler & type-system to ensure that your `unsafe` code is correct
180   at compile-time, use `assert!()` to verify that it is doing the
181   right thing at run-time.
182 - implement the `Drop` for resource clean-up via a destructor, and use
183   RAII (Resource Acquisition Is Initialization). This reduces the need
184   for any manual memory management by users, and automatically ensures
185   that clean-up is always run, even when the thread panics.
186 - ensure that any data stored behind a raw pointer is destroyed at the
187   appropriate time.
188
189 As an example, we give a reimplementation of owned boxes by wrapping
190 `malloc` and `free`. Rust's move semantics and lifetimes mean this
191 reimplementation is as safe as the `Box` type.
192
193 ```
194 #![feature(unsafe_destructor)]
195
196 extern crate libc;
197 use libc::{c_void, size_t, malloc, free};
198 use std::mem;
199 use std::ptr;
200
201 // Define a wrapper around the handle returned by the foreign code.
202 // Unique<T> has the same semantics as Box<T>
203 pub struct Unique<T> {
204     // It contains a single raw, mutable pointer to the object in question.
205     ptr: *mut T
206 }
207
208 // Implement methods for creating and using the values in the box.
209
210 // NB: For simplicity and correctness, we require that T has kind Send
211 // (owned boxes relax this restriction).
212 impl<T: Send> Unique<T> {
213     pub fn new(value: T) -> Unique<T> {
214         unsafe {
215             let ptr = malloc(mem::size_of::<T>() as size_t) as *mut T;
216             // we *need* valid pointer.
217             assert!(!ptr.is_null());
218             // `*ptr` is uninitialized, and `*ptr = value` would
219             // attempt to destroy it `overwrite` moves a value into
220             // this memory without attempting to drop the original
221             // value.
222             ptr::write(&mut *ptr, value);
223             Unique{ptr: ptr}
224         }
225     }
226
227     // the 'r lifetime results in the same semantics as `&*x` with
228     // Box<T>
229     pub fn borrow<'r>(&'r self) -> &'r T {
230         // By construction, self.ptr is valid
231         unsafe { &*self.ptr }
232     }
233
234     // the 'r lifetime results in the same semantics as `&mut *x` with
235     // Box<T>
236     pub fn borrow_mut<'r>(&'r mut self) -> &'r mut T {
237         unsafe { &mut *self.ptr }
238     }
239 }
240
241 // A key ingredient for safety, we associate a destructor with
242 // Unique<T>, making the struct manage the raw pointer: when the
243 // struct goes out of scope, it will automatically free the raw pointer.
244 //
245 // NB: This is an unsafe destructor, because rustc will not normally
246 // allow destructors to be associated with parameterized types, due to
247 // bad interaction with managed boxes. (With the Send restriction,
248 // we don't have this problem.) Note that the `#[unsafe_destructor]`
249 // feature gate is required to use unsafe destructors.
250 #[unsafe_destructor]
251 impl<T: Send> Drop for Unique<T> {
252     fn drop(&mut self) {
253         unsafe {
254             // Copy the object out from the pointer onto the stack,
255             // where it is covered by normal Rust destructor semantics
256             // and cleans itself up, if necessary
257             ptr::read(self.ptr);
258
259             // clean-up our allocation
260             free(self.ptr as *mut c_void)
261         }
262     }
263 }
264
265 // A comparison between the built-in `Box` and this reimplementation
266 fn main() {
267     {
268         let mut x = Box::new(5);
269         *x = 10;
270     } // `x` is freed here
271
272     {
273         let mut y = Unique::new(5);
274         *y.borrow_mut() = 10;
275     } // `y` is freed here
276 }
277 ```
278
279 Notably, the only way to construct a `Unique` is via the `new`
280 function, and this function ensures that the internal pointer is valid
281 and hidden in the private field. The two `borrow` methods are safe
282 because the compiler statically guarantees that objects are never used
283 before creation or after destruction (unless you use some `unsafe`
284 code...).
285
286 # Inline assembly
287
288 For extremely low-level manipulations and performance reasons, one
289 might wish to control the CPU directly. Rust supports using inline
290 assembly to do this via the `asm!` macro. The syntax roughly matches
291 that of GCC & Clang:
292
293 ```ignore
294 asm!(assembly template
295    : output operands
296    : input operands
297    : clobbers
298    : options
299    );
300 ```
301
302 Any use of `asm` is feature gated (requires `#![feature(asm)]` on the
303 crate to allow) and of course requires an `unsafe` block.
304
305 > **Note**: the examples here are given in x86/x86-64 assembly, but
306 > all platforms are supported.
307
308 ## Assembly template
309
310 The `assembly template` is the only required parameter and must be a
311 literal string (i.e `""`)
312
313 ```
314 #![feature(asm)]
315
316 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
317 fn foo() {
318     unsafe {
319         asm!("NOP");
320     }
321 }
322
323 // other platforms
324 #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
325 fn foo() { /* ... */ }
326
327 fn main() {
328     // ...
329     foo();
330     // ...
331 }
332 ```
333
334 (The `feature(asm)` and `#[cfg]`s are omitted from now on.)
335
336 Output operands, input operands, clobbers and options are all optional
337 but you must add the right number of `:` if you skip them:
338
339 ```
340 # #![feature(asm)]
341 # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
342 # fn main() { unsafe {
343 asm!("xor %eax, %eax"
344     :
345     :
346     : "eax"
347    );
348 # } }
349 ```
350
351 Whitespace also doesn't matter:
352
353 ```
354 # #![feature(asm)]
355 # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
356 # fn main() { unsafe {
357 asm!("xor %eax, %eax" ::: "eax");
358 # } }
359 ```
360
361 ## Operands
362
363 Input and output operands follow the same format: `:
364 "constraints1"(expr1), "constraints2"(expr2), ..."`. Output operand
365 expressions must be mutable lvalues:
366
367 ```
368 # #![feature(asm)]
369 # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
370 fn add(a: i32, b: i32) -> i32 {
371     let mut c = 0;
372     unsafe {
373         asm!("add $2, $0"
374              : "=r"(c)
375              : "0"(a), "r"(b)
376              );
377     }
378     c
379 }
380 # #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
381 # fn add(a: i32, b: i32) -> i32 { a + b }
382
383 fn main() {
384     assert_eq!(add(3, 14159), 14162)
385 }
386 ```
387
388 ## Clobbers
389
390 Some instructions modify registers which might otherwise have held
391 different values so we use the clobbers list to indicate to the
392 compiler not to assume any values loaded into those registers will
393 stay valid.
394
395 ```
396 # #![feature(asm)]
397 # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
398 # fn main() { unsafe {
399 // Put the value 0x200 in eax
400 asm!("mov $$0x200, %eax" : /* no outputs */ : /* no inputs */ : "eax");
401 # } }
402 ```
403
404 Input and output registers need not be listed since that information
405 is already communicated by the given constraints. Otherwise, any other
406 registers used either implicitly or explicitly should be listed.
407
408 If the assembly changes the condition code register `cc` should be
409 specified as one of the clobbers. Similarly, if the assembly modifies
410 memory, `memory` should also be specified.
411
412 ## Options
413
414 The last section, `options` is specific to Rust. The format is comma
415 separated literal strings (i.e `:"foo", "bar", "baz"`). It's used to
416 specify some extra info about the inline assembly:
417
418 Current valid options are:
419
420 1. *volatile* - specifying this is analogous to
421    `__asm__ __volatile__ (...)` in gcc/clang.
422 2. *alignstack* - certain instructions expect the stack to be
423    aligned a certain way (i.e SSE) and specifying this indicates to
424    the compiler to insert its usual stack alignment code
425 3. *intel* - use intel syntax instead of the default AT&T.
426
427 # Avoiding the standard library
428
429 By default, `std` is linked to every Rust crate. In some contexts,
430 this is undesirable, and can be avoided with the `#![no_std]`
431 attribute attached to the crate.
432
433 ```ignore
434 // a minimal library
435 #![crate_type="lib"]
436 #![no_std]
437 # // fn main() {} tricked you, rustdoc!
438 ```
439
440 Obviously there's more to life than just libraries: one can use
441 `#[no_std]` with an executable, controlling the entry point is
442 possible in two ways: the `#[start]` attribute, or overriding the
443 default shim for the C `main` function with your own.
444
445 The function marked `#[start]` is passed the command line parameters
446 in the same format as C:
447
448 ```
449 #![no_std]
450 #![feature(lang_items, start)]
451
452 // Pull in the system libc library for what crt0.o likely requires
453 extern crate libc;
454
455 // Entry point for this program
456 #[start]
457 fn start(_argc: isize, _argv: *const *const u8) -> isize {
458     0
459 }
460
461 // These functions and traits are used by the compiler, but not
462 // for a bare-bones hello world. These are normally
463 // provided by libstd.
464 #[lang = "stack_exhausted"] extern fn stack_exhausted() {}
465 #[lang = "eh_personality"] extern fn eh_personality() {}
466 #[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
467 # // fn main() {} tricked you, rustdoc!
468 ```
469
470 To override the compiler-inserted `main` shim, one has to disable it
471 with `#![no_main]` and then create the appropriate symbol with the
472 correct ABI and the correct name, which requires overriding the
473 compiler's name mangling too:
474
475 ```ignore
476 #![no_std]
477 #![no_main]
478 #![feature(lang_items, start)]
479
480 extern crate libc;
481
482 #[no_mangle] // ensure that this symbol is called `main` in the output
483 pub extern fn main(argc: i32, argv: *const *const u8) -> i32 {
484     0
485 }
486
487 #[lang = "stack_exhausted"] extern fn stack_exhausted() {}
488 #[lang = "eh_personality"] extern fn eh_personality() {}
489 #[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
490 # // fn main() {} tricked you, rustdoc!
491 ```
492
493
494 The compiler currently makes a few assumptions about symbols which are available
495 in the executable to call. Normally these functions are provided by the standard
496 library, but without it you must define your own.
497
498 The first of these three functions, `stack_exhausted`, is invoked whenever stack
499 overflow is detected.  This function has a number of restrictions about how it
500 can be called and what it must do, but if the stack limit register is not being
501 maintained then a thread always has an "infinite stack" and this function
502 shouldn't get triggered.
503
504 The second of these three functions, `eh_personality`, is used by the
505 failure mechanisms of the compiler. This is often mapped to GCC's
506 personality function (see the
507 [libstd implementation](../std/rt/unwind/index.html) for more
508 information), but crates which do not trigger a panic can be assured
509 that this function is never called. The final function, `panic_fmt`, is
510 also used by the failure mechanisms of the compiler.
511
512 ## Using libcore
513
514 > **Note**: the core library's structure is unstable, and it is recommended to
515 > use the standard library instead wherever possible.
516
517 With the above techniques, we've got a bare-metal executable running some Rust
518 code. There is a good deal of functionality provided by the standard library,
519 however, that is necessary to be productive in Rust. If the standard library is
520 not sufficient, then [libcore](../core/index.html) is designed to be used
521 instead.
522
523 The core library has very few dependencies and is much more portable than the
524 standard library itself. Additionally, the core library has most of the
525 necessary functionality for writing idiomatic and effective Rust code.
526
527 As an example, here is a program that will calculate the dot product of two
528 vectors provided from C, using idiomatic Rust practices.
529
530 ```
531 #![no_std]
532 #![feature(lang_items, start)]
533
534 # extern crate libc;
535 extern crate core;
536
537 use core::prelude::*;
538
539 use core::mem;
540
541 #[no_mangle]
542 pub extern fn dot_product(a: *const u32, a_len: u32,
543                           b: *const u32, b_len: u32) -> u32 {
544     use core::raw::Slice;
545
546     // Convert the provided arrays into Rust slices.
547     // The core::raw module guarantees that the Slice
548     // structure has the same memory layout as a &[T]
549     // slice.
550     //
551     // This is an unsafe operation because the compiler
552     // cannot tell the pointers are valid.
553     let (a_slice, b_slice): (&[u32], &[u32]) = unsafe {
554         mem::transmute((
555             Slice { data: a, len: a_len as usize },
556             Slice { data: b, len: b_len as usize },
557         ))
558     };
559
560     // Iterate over the slices, collecting the result
561     let mut ret = 0;
562     for (i, j) in a_slice.iter().zip(b_slice.iter()) {
563         ret += (*i) * (*j);
564     }
565     return ret;
566 }
567
568 #[lang = "panic_fmt"]
569 extern fn panic_fmt(args: &core::fmt::Arguments,
570                     file: &str,
571                     line: u32) -> ! {
572     loop {}
573 }
574
575 #[lang = "stack_exhausted"] extern fn stack_exhausted() {}
576 #[lang = "eh_personality"] extern fn eh_personality() {}
577 # #[start] fn start(argc: isize, argv: *const *const u8) -> isize { 0 }
578 # fn main() {}
579 ```
580
581 Note that there is one extra lang item here which differs from the examples
582 above, `panic_fmt`. This must be defined by consumers of libcore because the
583 core library declares panics, but it does not define it. The `panic_fmt`
584 lang item is this crate's definition of panic, and it must be guaranteed to
585 never return.
586
587 As can be seen in this example, the core library is intended to provide the
588 power of Rust in all circumstances, regardless of platform requirements. Further
589 libraries, such as liballoc, add functionality to libcore which make other
590 platform-specific assumptions, but continue to be more portable than the
591 standard library itself.
592
593 # Interacting with the compiler internals
594
595 > **Note**: this section is specific to the `rustc` compiler; these
596 > parts of the language may never be fully specified and so details may
597 > differ wildly between implementations (and even versions of `rustc`
598 > itself).
599 >
600 > Furthermore, this is just an overview; the best form of
601 > documentation for specific instances of these features are their
602 > definitions and uses in `std`.
603
604 The Rust language currently has two orthogonal mechanisms for allowing
605 libraries to interact directly with the compiler and vice versa:
606
607 - intrinsics, functions built directly into the compiler providing
608   very basic low-level functionality,
609 - lang-items, special functions, types and traits in libraries marked
610   with specific `#[lang]` attributes
611
612 ## Intrinsics
613
614 > **Note**: intrinsics will forever have an unstable interface, it is
615 > recommended to use the stable interfaces of libcore rather than intrinsics
616 > directly.
617
618 These are imported as if they were FFI functions, with the special
619 `rust-intrinsic` ABI. For example, if one was in a freestanding
620 context, but wished to be able to `transmute` between types, and
621 perform efficient pointer arithmetic, one would import those functions
622 via a declaration like
623
624 ```
625 # #![feature(intrinsics)]
626 # fn main() {}
627
628 extern "rust-intrinsic" {
629     fn transmute<T, U>(x: T) -> U;
630
631     fn offset<T>(dst: *const T, offset: isize) -> *const T;
632 }
633 ```
634
635 As with any other FFI functions, these are always `unsafe` to call.
636
637 ## Lang items
638
639 > **Note**: lang items are often provided by crates in the Rust distribution,
640 > and lang items themselves have an unstable interface. It is recommended to use
641 > officially distributed crates instead of defining your own lang items.
642
643 The `rustc` compiler has certain pluggable operations, that is,
644 functionality that isn't hard-coded into the language, but is
645 implemented in libraries, with a special marker to tell the compiler
646 it exists. The marker is the attribute `#[lang="..."]` and there are
647 various different values of `...`, i.e. various different "lang
648 items".
649
650 For example, `Box` pointers require two lang items, one for allocation
651 and one for deallocation. A freestanding program that uses the `Box`
652 sugar for dynamic allocations via `malloc` and `free`:
653
654 ```
655 #![no_std]
656 #![feature(lang_items, box_syntax, start)]
657
658 extern crate libc;
659
660 extern {
661     fn abort() -> !;
662 }
663
664 #[lang = "owned_box"]
665 pub struct Box<T>(*mut T);
666
667 #[lang="exchange_malloc"]
668 unsafe fn allocate(size: usize, _align: usize) -> *mut u8 {
669     let p = libc::malloc(size as libc::size_t) as *mut u8;
670
671     // malloc failed
672     if p as usize == 0 {
673         abort();
674     }
675
676     p
677 }
678 #[lang="exchange_free"]
679 unsafe fn deallocate(ptr: *mut u8, _size: usize, _align: usize) {
680     libc::free(ptr as *mut libc::c_void)
681 }
682
683 #[start]
684 fn main(argc: isize, argv: *const *const u8) -> isize {
685     let x = box 1;
686
687     0
688 }
689
690 #[lang = "stack_exhausted"] extern fn stack_exhausted() {}
691 #[lang = "eh_personality"] extern fn eh_personality() {}
692 #[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
693 ```
694
695 Note the use of `abort`: the `exchange_malloc` lang item is assumed to
696 return a valid pointer, and so needs to do the check internally.
697
698 Other features provided by lang items include:
699
700 - overloadable operators via traits: the traits corresponding to the
701   `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all
702   marked with lang items; those specific four are `eq`, `ord`,
703   `deref`, and `add` respectively.
704 - stack unwinding and general failure; the `eh_personality`, `fail`
705   and `fail_bounds_checks` lang items.
706 - the traits in `std::marker` used to indicate types of
707   various kinds; lang items `send`, `sync` and `copy`.
708 - the marker types and variance indicators found in
709   `std::marker`; lang items `covariant_type`,
710   `contravariant_lifetime`, `no_sync_bound`, etc.
711
712 Lang items are loaded lazily by the compiler; e.g. if one never uses
713 `Box` then there is no need to define functions for `exchange_malloc`
714 and `exchange_free`. `rustc` will emit an error when an item is needed
715 but not found in the current crate or any that it depends on.