]> git.lizzy.rs Git - rust.git/blob - src/liballoc/heap.rs
rollup merge of #23549: aturon/stab-num
[rust.git] / src / liballoc / heap.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
12
13 /// Return a pointer to `size` bytes of memory aligned to `align`.
14 ///
15 /// On failure, return a null pointer.
16 ///
17 /// Behavior is undefined if the requested size is 0 or the alignment is not a
18 /// power of 2. The alignment must be no larger than the largest supported page
19 /// size on the platform.
20 #[inline]
21 pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
22     imp::allocate(size, align)
23 }
24
25 /// Resize the allocation referenced by `ptr` to `size` bytes.
26 ///
27 /// On failure, return a null pointer and leave the original allocation intact.
28 ///
29 /// If the allocation was relocated, the memory at the passed-in pointer is
30 /// undefined after the call.
31 ///
32 /// Behavior is undefined if the requested size is 0 or the alignment is not a
33 /// power of 2. The alignment must be no larger than the largest supported page
34 /// size on the platform.
35 ///
36 /// The `old_size` and `align` parameters are the parameters that were used to
37 /// create the allocation referenced by `ptr`. The `old_size` parameter may be
38 /// any value in range_inclusive(requested_size, usable_size).
39 #[inline]
40 pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
41     imp::reallocate(ptr, old_size, size, align)
42 }
43
44 /// Resize the allocation referenced by `ptr` to `size` bytes.
45 ///
46 /// If the operation succeeds, it returns `usable_size(size, align)` and if it
47 /// fails (or is a no-op) it returns `usable_size(old_size, align)`.
48 ///
49 /// Behavior is undefined if the requested size is 0 or the alignment is not a
50 /// power of 2. The alignment must be no larger than the largest supported page
51 /// size on the platform.
52 ///
53 /// The `old_size` and `align` parameters are the parameters that were used to
54 /// create the allocation referenced by `ptr`. The `old_size` parameter may be
55 /// any value in range_inclusive(requested_size, usable_size).
56 #[inline]
57 pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize,
58                                  align: usize) -> usize {
59     imp::reallocate_inplace(ptr, old_size, size, align)
60 }
61
62 /// Deallocates the memory referenced by `ptr`.
63 ///
64 /// The `ptr` parameter must not be null.
65 ///
66 /// The `old_size` and `align` parameters are the parameters that were used to
67 /// create the allocation referenced by `ptr`. The `old_size` parameter may be
68 /// any value in range_inclusive(requested_size, usable_size).
69 #[inline]
70 pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
71     imp::deallocate(ptr, old_size, align)
72 }
73
74 /// Returns the usable size of an allocation created with the specified the
75 /// `size` and `align`.
76 #[inline]
77 pub fn usable_size(size: usize, align: usize) -> usize {
78     imp::usable_size(size, align)
79 }
80
81 /// Prints implementation-defined allocator statistics.
82 ///
83 /// These statistics may be inconsistent if other threads use the allocator
84 /// during the call.
85 #[unstable(feature = "alloc")]
86 pub fn stats_print() {
87     imp::stats_print();
88 }
89
90 /// An arbitrary non-null address to represent zero-size allocations.
91 ///
92 /// This preserves the non-null invariant for types like `Box<T>`. The address may overlap with
93 /// non-zero-size memory allocations.
94 pub const EMPTY: *mut () = 0x1 as *mut ();
95
96 /// The allocator for unique pointers.
97 #[cfg(not(test))]
98 #[lang="exchange_malloc"]
99 #[inline]
100 unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
101     if size == 0 {
102         EMPTY as *mut u8
103     } else {
104         let ptr = allocate(size, align);
105         if ptr.is_null() { ::oom() }
106         ptr
107     }
108 }
109
110 #[cfg(not(test))]
111 #[lang="exchange_free"]
112 #[inline]
113 unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
114     deallocate(ptr, old_size, align);
115 }
116
117 // The minimum alignment guaranteed by the architecture. This value is used to
118 // add fast paths for low alignment values. In practice, the alignment is a
119 // constant at the call site and the branch will be optimized out.
120 #[cfg(all(not(feature = "external_funcs"),
121           not(feature = "external_crate"),
122           any(target_arch = "arm",
123               target_arch = "mips",
124               target_arch = "mipsel",
125               target_arch = "powerpc")))]
126 const MIN_ALIGN: usize = 8;
127 #[cfg(all(not(feature = "external_funcs"),
128           not(feature = "external_crate"),
129           any(target_arch = "x86",
130               target_arch = "x86_64",
131               target_arch = "aarch64")))]
132 const MIN_ALIGN: usize = 16;
133
134 #[cfg(feature = "external_funcs")]
135 mod imp {
136     extern {
137         fn rust_allocate(size: usize, align: usize) -> *mut u8;
138         fn rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
139         fn rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
140         fn rust_reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize,
141                                    align: usize) -> usize;
142         fn rust_usable_size(size: usize, align: usize) -> usize;
143         fn rust_stats_print();
144     }
145
146     #[inline]
147     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
148         rust_allocate(size, align)
149     }
150
151     #[inline]
152     pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
153         rust_deallocate(ptr, old_size, align)
154     }
155
156     #[inline]
157     pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
158         rust_reallocate(ptr, old_size, size, align)
159     }
160
161     #[inline]
162     pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize,
163                                      align: usize) -> usize {
164         rust_reallocate_inplace(ptr, old_size, size, align)
165     }
166
167     #[inline]
168     pub fn usable_size(size: usize, align: usize) -> usize {
169         unsafe { rust_usable_size(size, align) }
170     }
171
172     #[inline]
173     pub fn stats_print() {
174         unsafe { rust_stats_print() }
175     }
176 }
177
178 #[cfg(feature = "external_crate")]
179 mod imp {
180     extern crate external;
181     pub use self::external::{allocate, deallocate, reallocate_inplace, reallocate};
182     pub use self::external::{usable_size, stats_print};
183 }
184
185 #[cfg(all(not(feature = "external_funcs"),
186           not(feature = "external_crate"),
187           jemalloc))]
188 mod imp {
189     use core::option::Option;
190     use core::option::Option::None;
191     use core::ptr::{null_mut, null};
192     use libc::{c_char, c_int, c_void, size_t};
193     use super::MIN_ALIGN;
194
195     #[link(name = "jemalloc", kind = "static")]
196     #[cfg(not(test))]
197     extern {}
198
199     extern {
200         #[allocator]
201         fn je_mallocx(size: size_t, flags: c_int) -> *mut c_void;
202         fn je_rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void;
203         fn je_xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t;
204         fn je_sdallocx(ptr: *mut c_void, size: size_t, flags: c_int);
205         fn je_nallocx(size: size_t, flags: c_int) -> size_t;
206         fn je_malloc_stats_print(write_cb: Option<extern "C" fn(cbopaque: *mut c_void,
207                                                                 *const c_char)>,
208                                  cbopaque: *mut c_void,
209                                  opts: *const c_char);
210     }
211
212     // -lpthread needs to occur after -ljemalloc, the earlier argument isn't enough
213     #[cfg(all(not(windows), not(target_os = "android")))]
214     #[link(name = "pthread")]
215     extern {}
216
217     // MALLOCX_ALIGN(a) macro
218     #[inline(always)]
219     fn mallocx_align(a: usize) -> c_int { a.trailing_zeros() as c_int }
220
221     #[inline(always)]
222     fn align_to_flags(align: usize) -> c_int {
223         if align <= MIN_ALIGN { 0 } else { mallocx_align(align) }
224     }
225
226     #[inline]
227     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
228         let flags = align_to_flags(align);
229         je_mallocx(size as size_t, flags) as *mut u8
230     }
231
232     #[inline]
233     pub unsafe fn reallocate(ptr: *mut u8, _old_size: usize, size: usize, align: usize) -> *mut u8 {
234         let flags = align_to_flags(align);
235         je_rallocx(ptr as *mut c_void, size as size_t, flags) as *mut u8
236     }
237
238     #[inline]
239     pub unsafe fn reallocate_inplace(ptr: *mut u8, _old_size: usize, size: usize,
240                                      align: usize) -> usize {
241         let flags = align_to_flags(align);
242         je_xallocx(ptr as *mut c_void, size as size_t, 0, flags) as usize
243     }
244
245     #[inline]
246     pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
247         let flags = align_to_flags(align);
248         je_sdallocx(ptr as *mut c_void, old_size as size_t, flags)
249     }
250
251     #[inline]
252     pub fn usable_size(size: usize, align: usize) -> usize {
253         let flags = align_to_flags(align);
254         unsafe { je_nallocx(size as size_t, flags) as usize }
255     }
256
257     pub fn stats_print() {
258         unsafe {
259             je_malloc_stats_print(None, null_mut(), null())
260         }
261     }
262 }
263
264 #[cfg(all(not(feature = "external_funcs"),
265           not(feature = "external_crate"),
266           not(jemalloc),
267           unix))]
268 mod imp {
269     use core::cmp;
270     use core::ptr;
271     use libc;
272     use super::MIN_ALIGN;
273
274     extern {
275         fn posix_memalign(memptr: *mut *mut libc::c_void,
276                           align: libc::size_t,
277                           size: libc::size_t) -> libc::c_int;
278     }
279
280     #[inline]
281     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
282         if align <= MIN_ALIGN {
283             libc::malloc(size as libc::size_t) as *mut u8
284         } else {
285             let mut out = ptr::null_mut();
286             let ret = posix_memalign(&mut out,
287                                      align as libc::size_t,
288                                      size as libc::size_t);
289             if ret != 0 {
290                 ptr::null_mut()
291             } else {
292                 out as *mut u8
293             }
294         }
295     }
296
297     #[inline]
298     pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
299         if align <= MIN_ALIGN {
300             libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8
301         } else {
302             let new_ptr = allocate(size, align);
303             ptr::copy(ptr, new_ptr, cmp::min(size, old_size));
304             deallocate(ptr, old_size, align);
305             new_ptr
306         }
307     }
308
309     #[inline]
310     pub unsafe fn reallocate_inplace(_ptr: *mut u8, old_size: usize, _size: usize,
311                                      _align: usize) -> usize {
312         old_size
313     }
314
315     #[inline]
316     pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, _align: usize) {
317         libc::free(ptr as *mut libc::c_void)
318     }
319
320     #[inline]
321     pub fn usable_size(size: usize, _align: usize) -> usize {
322         size
323     }
324
325     pub fn stats_print() {}
326 }
327
328 #[cfg(all(not(feature = "external_funcs"),
329           not(feature = "external_crate"),
330           not(jemalloc),
331           windows))]
332 mod imp {
333     use libc::{c_void, size_t};
334     use libc;
335     use super::MIN_ALIGN;
336
337     extern {
338         fn _aligned_malloc(size: size_t, align: size_t) -> *mut c_void;
339         fn _aligned_realloc(block: *mut c_void, size: size_t,
340                             align: size_t) -> *mut c_void;
341         fn _aligned_free(ptr: *mut c_void);
342     }
343
344     #[inline]
345     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
346         if align <= MIN_ALIGN {
347             libc::malloc(size as size_t) as *mut u8
348         } else {
349             _aligned_malloc(size as size_t, align as size_t) as *mut u8
350         }
351     }
352
353     #[inline]
354     pub unsafe fn reallocate(ptr: *mut u8, _old_size: usize, size: usize, align: usize) -> *mut u8 {
355         if align <= MIN_ALIGN {
356             libc::realloc(ptr as *mut c_void, size as size_t) as *mut u8
357         } else {
358             _aligned_realloc(ptr as *mut c_void, size as size_t, align as size_t) as *mut u8
359         }
360     }
361
362     #[inline]
363     pub unsafe fn reallocate_inplace(_ptr: *mut u8, old_size: usize, _size: usize,
364                                      _align: usize) -> usize {
365         old_size
366     }
367
368     #[inline]
369     pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, align: usize) {
370         if align <= MIN_ALIGN {
371             libc::free(ptr as *mut libc::c_void)
372         } else {
373             _aligned_free(ptr as *mut c_void)
374         }
375     }
376
377     #[inline]
378     pub fn usable_size(size: usize, _align: usize) -> usize {
379         size
380     }
381
382     pub fn stats_print() {}
383 }
384
385 #[cfg(test)]
386 mod test {
387     extern crate test;
388     use self::test::Bencher;
389     use boxed::Box;
390     use heap;
391
392     #[test]
393     fn basic_reallocate_inplace_noop() {
394         unsafe {
395             let size = 4000;
396             let ptr = heap::allocate(size, 8);
397             if ptr.is_null() { ::oom() }
398             let ret = heap::reallocate_inplace(ptr, size, size, 8);
399             heap::deallocate(ptr, size, 8);
400             assert_eq!(ret, heap::usable_size(size, 8));
401         }
402     }
403
404     #[bench]
405     fn alloc_owned_small(b: &mut Bencher) {
406         b.iter(|| {
407             let _: Box<_> = box 10;
408         })
409     }
410 }