]> git.lizzy.rs Git - rust.git/blob - src/liballoc_system/lib.rs
Auto merge of #42398 - redox-os:master, r=sfackler
[rust.git] / src / liballoc_system / lib.rs
1 // Copyright 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 #![crate_name = "alloc_system"]
12 #![crate_type = "rlib"]
13 #![no_std]
14 #![allocator]
15 #![deny(warnings)]
16 #![unstable(feature = "alloc_system",
17             reason = "this library is unlikely to be stabilized in its current \
18                       form or name",
19             issue = "27783")]
20 #![feature(allocator)]
21 #![feature(staged_api)]
22 #![cfg_attr(any(unix, target_os = "redox"), feature(libc))]
23
24 // The minimum alignment guaranteed by the architecture. This value is used to
25 // add fast paths for low alignment values. In practice, the alignment is a
26 // constant at the call site and the branch will be optimized out.
27 #[cfg(all(any(target_arch = "x86",
28               target_arch = "arm",
29               target_arch = "mips",
30               target_arch = "powerpc",
31               target_arch = "powerpc64",
32               target_arch = "asmjs",
33               target_arch = "wasm32")))]
34 const MIN_ALIGN: usize = 8;
35 #[cfg(all(any(target_arch = "x86_64",
36               target_arch = "aarch64",
37               target_arch = "mips64",
38               target_arch = "s390x",
39               target_arch = "sparc64")))]
40 const MIN_ALIGN: usize = 16;
41
42 #[no_mangle]
43 pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
44     unsafe { imp::allocate(size, align) }
45 }
46
47 #[no_mangle]
48 pub extern "C" fn __rust_allocate_zeroed(size: usize, align: usize) -> *mut u8 {
49     unsafe { imp::allocate_zeroed(size, align) }
50 }
51
52 #[no_mangle]
53 pub extern "C" fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize) {
54     unsafe { imp::deallocate(ptr, old_size, align) }
55 }
56
57 #[no_mangle]
58 pub extern "C" fn __rust_reallocate(ptr: *mut u8,
59                                     old_size: usize,
60                                     size: usize,
61                                     align: usize)
62                                     -> *mut u8 {
63     unsafe { imp::reallocate(ptr, old_size, size, align) }
64 }
65
66 #[no_mangle]
67 pub extern "C" fn __rust_reallocate_inplace(ptr: *mut u8,
68                                             old_size: usize,
69                                             size: usize,
70                                             align: usize)
71                                             -> usize {
72     unsafe { imp::reallocate_inplace(ptr, old_size, size, align) }
73 }
74
75 #[no_mangle]
76 pub extern "C" fn __rust_usable_size(size: usize, align: usize) -> usize {
77     imp::usable_size(size, align)
78 }
79
80 #[cfg(any(unix, target_os = "redox"))]
81 mod imp {
82     extern crate libc;
83
84     use core::cmp;
85     use core::ptr;
86     use MIN_ALIGN;
87
88     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
89         if align <= MIN_ALIGN {
90             libc::malloc(size as libc::size_t) as *mut u8
91         } else {
92             aligned_malloc(size, align)
93         }
94     }
95
96     #[cfg(any(target_os = "android", target_os = "redox"))]
97     unsafe fn aligned_malloc(size: usize, align: usize) -> *mut u8 {
98         // On android we currently target API level 9 which unfortunately
99         // doesn't have the `posix_memalign` API used below. Instead we use
100         // `memalign`, but this unfortunately has the property on some systems
101         // where the memory returned cannot be deallocated by `free`!
102         //
103         // Upon closer inspection, however, this appears to work just fine with
104         // Android, so for this platform we should be fine to call `memalign`
105         // (which is present in API level 9). Some helpful references could
106         // possibly be chromium using memalign [1], attempts at documenting that
107         // memalign + free is ok [2] [3], or the current source of chromium
108         // which still uses memalign on android [4].
109         //
110         // [1]: https://codereview.chromium.org/10796020/
111         // [2]: https://code.google.com/p/android/issues/detail?id=35391
112         // [3]: https://bugs.chromium.org/p/chromium/issues/detail?id=138579
113         // [4]: https://chromium.googlesource.com/chromium/src/base/+/master/
114         //                                       /memory/aligned_memory.cc
115         libc::memalign(align as libc::size_t, size as libc::size_t) as *mut u8
116     }
117
118     #[cfg(not(any(target_os = "android", target_os = "redox")))]
119     unsafe fn aligned_malloc(size: usize, align: usize) -> *mut u8 {
120         let mut out = ptr::null_mut();
121         let ret = libc::posix_memalign(&mut out, align as libc::size_t, size as libc::size_t);
122         if ret != 0 {
123             ptr::null_mut()
124         } else {
125             out as *mut u8
126         }
127     }
128
129     pub unsafe fn allocate_zeroed(size: usize, align: usize) -> *mut u8 {
130         if align <= MIN_ALIGN {
131             libc::calloc(size as libc::size_t, 1) as *mut u8
132         } else {
133             let ptr = aligned_malloc(size, align);
134             if !ptr.is_null() {
135                 ptr::write_bytes(ptr, 0, size);
136             }
137             ptr
138         }
139     }
140
141     pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
142         if align <= MIN_ALIGN {
143             libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8
144         } else {
145             let new_ptr = allocate(size, align);
146             if !new_ptr.is_null() {
147                 ptr::copy(ptr, new_ptr, cmp::min(size, old_size));
148                 deallocate(ptr, old_size, align);
149             }
150             new_ptr
151         }
152     }
153
154     pub unsafe fn reallocate_inplace(_ptr: *mut u8,
155                                      old_size: usize,
156                                      _size: usize,
157                                      _align: usize)
158                                      -> usize {
159         old_size
160     }
161
162     pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, _align: usize) {
163         libc::free(ptr as *mut libc::c_void)
164     }
165
166     pub fn usable_size(size: usize, _align: usize) -> usize {
167         size
168     }
169 }
170
171 #[cfg(windows)]
172 #[allow(bad_style)]
173 mod imp {
174     use core::cmp::min;
175     use core::ptr::copy_nonoverlapping;
176     use MIN_ALIGN;
177
178     type LPVOID = *mut u8;
179     type HANDLE = LPVOID;
180     type SIZE_T = usize;
181     type DWORD = u32;
182     type BOOL = i32;
183
184     extern "system" {
185         fn GetProcessHeap() -> HANDLE;
186         fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID;
187         fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T) -> LPVOID;
188         fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL;
189         fn GetLastError() -> DWORD;
190     }
191
192     #[repr(C)]
193     struct Header(*mut u8);
194
195
196     const HEAP_ZERO_MEMORY: DWORD = 0x00000008;
197     const HEAP_REALLOC_IN_PLACE_ONLY: DWORD = 0x00000010;
198
199     unsafe fn get_header<'a>(ptr: *mut u8) -> &'a mut Header {
200         &mut *(ptr as *mut Header).offset(-1)
201     }
202
203     unsafe fn align_ptr(ptr: *mut u8, align: usize) -> *mut u8 {
204         let aligned = ptr.offset((align - (ptr as usize & (align - 1))) as isize);
205         *get_header(aligned) = Header(ptr);
206         aligned
207     }
208
209     #[inline]
210     unsafe fn allocate_with_flags(size: usize, align: usize, flags: DWORD) -> *mut u8 {
211         if align <= MIN_ALIGN {
212             HeapAlloc(GetProcessHeap(), flags, size as SIZE_T) as *mut u8
213         } else {
214             let ptr = HeapAlloc(GetProcessHeap(), flags, (size + align) as SIZE_T) as *mut u8;
215             if ptr.is_null() {
216                 return ptr;
217             }
218             align_ptr(ptr, align)
219         }
220     }
221
222     pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
223         allocate_with_flags(size, align, 0)
224     }
225
226     pub unsafe fn allocate_zeroed(size: usize, align: usize) -> *mut u8 {
227         allocate_with_flags(size, align, HEAP_ZERO_MEMORY)
228     }
229
230     pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
231         if align <= MIN_ALIGN {
232             HeapReAlloc(GetProcessHeap(), 0, ptr as LPVOID, size as SIZE_T) as *mut u8
233         } else {
234             let new = allocate(size, align);
235             if !new.is_null() {
236                 copy_nonoverlapping(ptr, new, min(size, old_size));
237                 deallocate(ptr, old_size, align);
238             }
239             new
240         }
241     }
242
243     pub unsafe fn reallocate_inplace(ptr: *mut u8,
244                                      old_size: usize,
245                                      size: usize,
246                                      align: usize)
247                                      -> usize {
248         let new = if align <= MIN_ALIGN {
249             HeapReAlloc(GetProcessHeap(),
250                         HEAP_REALLOC_IN_PLACE_ONLY,
251                         ptr as LPVOID,
252                         size as SIZE_T) as *mut u8
253         } else {
254             let header = get_header(ptr);
255             HeapReAlloc(GetProcessHeap(),
256                         HEAP_REALLOC_IN_PLACE_ONLY,
257                         header.0 as LPVOID,
258                         size + align as SIZE_T) as *mut u8
259         };
260         if new.is_null() { old_size } else { size }
261     }
262
263     pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, align: usize) {
264         if align <= MIN_ALIGN {
265             let err = HeapFree(GetProcessHeap(), 0, ptr as LPVOID);
266             debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError());
267         } else {
268             let header = get_header(ptr);
269             let err = HeapFree(GetProcessHeap(), 0, header.0 as LPVOID);
270             debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError());
271         }
272     }
273
274     pub fn usable_size(size: usize, _align: usize) -> usize {
275         size
276     }
277 }