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.
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.
12 #![allow(unused_attributes)]
14 #![unstable(feature = "alloc_system",
15 reason = "this library is unlikely to be stabilized in its current \
18 #![feature(global_allocator)]
19 #![feature(allocator_api)]
21 #![feature(core_intrinsics)]
22 #![feature(staged_api)]
23 #![feature(rustc_attrs)]
24 #![cfg_attr(any(unix, target_os = "redox"), feature(libc))]
25 #![rustc_alloc_kind = "lib"]
27 // The minimum alignment guaranteed by the architecture. This value is used to
28 // add fast paths for low alignment values. In practice, the alignment is a
29 // constant at the call site and the branch will be optimized out.
30 #[cfg(all(any(target_arch = "x86",
33 target_arch = "powerpc",
34 target_arch = "powerpc64",
35 target_arch = "asmjs",
36 target_arch = "wasm32")))]
37 const MIN_ALIGN: usize = 8;
38 #[cfg(all(any(target_arch = "x86_64",
39 target_arch = "aarch64",
40 target_arch = "mips64",
41 target_arch = "s390x",
42 target_arch = "sparc64")))]
43 const MIN_ALIGN: usize = 16;
47 use self::alloc::heap::{Alloc, AllocErr, Layout, Excess, CannotReallocInPlace};
49 #[unstable(feature = "allocator_api", issue = "32838")]
52 #[unstable(feature = "allocator_api", issue = "32838")]
53 unsafe impl Alloc for System {
55 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
56 (&*self).alloc(layout)
60 unsafe fn alloc_zeroed(&mut self, layout: Layout)
61 -> Result<*mut u8, AllocErr>
63 (&*self).alloc_zeroed(layout)
67 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
68 (&*self).dealloc(ptr, layout)
72 unsafe fn realloc(&mut self,
75 new_layout: Layout) -> Result<*mut u8, AllocErr> {
76 (&*self).realloc(ptr, old_layout, new_layout)
79 fn oom(&mut self, err: AllocErr) -> ! {
84 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
85 (&self).usable_size(layout)
89 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
90 (&*self).alloc_excess(layout)
94 unsafe fn realloc_excess(&mut self,
97 new_layout: Layout) -> Result<Excess, AllocErr> {
98 (&*self).realloc_excess(ptr, layout, new_layout)
102 unsafe fn grow_in_place(&mut self,
105 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
106 (&*self).grow_in_place(ptr, layout, new_layout)
110 unsafe fn shrink_in_place(&mut self,
113 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
114 (&*self).shrink_in_place(ptr, layout, new_layout)
118 #[cfg(any(unix, target_os = "redox"))]
127 use alloc::heap::{Alloc, AllocErr, Layout};
129 #[unstable(feature = "allocator_api", issue = "32838")]
130 unsafe impl<'a> Alloc for &'a System {
132 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
133 let ptr = if layout.align() <= MIN_ALIGN {
134 libc::malloc(layout.size()) as *mut u8
136 aligned_malloc(&layout)
141 Err(AllocErr::Exhausted { request: layout })
146 unsafe fn alloc_zeroed(&mut self, layout: Layout)
147 -> Result<*mut u8, AllocErr>
149 if layout.align() <= MIN_ALIGN {
150 let ptr = libc::calloc(layout.size(), 1) as *mut u8;
154 Err(AllocErr::Exhausted { request: layout })
157 let ret = self.alloc(layout.clone());
158 if let Ok(ptr) = ret {
159 ptr::write_bytes(ptr, 0, layout.size());
166 unsafe fn dealloc(&mut self, ptr: *mut u8, _layout: Layout) {
167 libc::free(ptr as *mut libc::c_void)
171 unsafe fn realloc(&mut self,
174 new_layout: Layout) -> Result<*mut u8, AllocErr> {
175 if old_layout.align() != new_layout.align() {
176 return Err(AllocErr::Unsupported {
177 details: "cannot change alignment on `realloc`",
181 if new_layout.align() <= MIN_ALIGN {
182 let ptr = libc::realloc(ptr as *mut libc::c_void, new_layout.size());
186 Err(AllocErr::Exhausted { request: new_layout })
189 let res = self.alloc(new_layout.clone());
190 if let Ok(new_ptr) = res {
191 let size = cmp::min(old_layout.size(), new_layout.size());
192 ptr::copy_nonoverlapping(ptr, new_ptr, size);
193 self.dealloc(ptr, old_layout);
199 fn oom(&mut self, err: AllocErr) -> ! {
200 use core::fmt::{self, Write};
202 // Print a message to stderr before aborting to assist with
203 // debugging. It is critical that this code does not allocate any
204 // memory since we are in an OOM situation. Any errors are ignored
205 // while printing since there's nothing we can do about them and we
206 // are about to exit anyways.
207 drop(writeln!(Stderr, "fatal runtime error: {}", err));
209 ::core::intrinsics::abort();
214 impl Write for Stderr {
215 fn write_str(&mut self, s: &str) -> fmt::Result {
217 libc::write(libc::STDERR_FILENO,
218 s.as_ptr() as *const libc::c_void,
227 #[cfg(any(target_os = "android", target_os = "redox", target_os = "solaris"))]
229 unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
230 // On android we currently target API level 9 which unfortunately
231 // doesn't have the `posix_memalign` API used below. Instead we use
232 // `memalign`, but this unfortunately has the property on some systems
233 // where the memory returned cannot be deallocated by `free`!
235 // Upon closer inspection, however, this appears to work just fine with
236 // Android, so for this platform we should be fine to call `memalign`
237 // (which is present in API level 9). Some helpful references could
238 // possibly be chromium using memalign [1], attempts at documenting that
239 // memalign + free is ok [2] [3], or the current source of chromium
240 // which still uses memalign on android [4].
242 // [1]: https://codereview.chromium.org/10796020/
243 // [2]: https://code.google.com/p/android/issues/detail?id=35391
244 // [3]: https://bugs.chromium.org/p/chromium/issues/detail?id=138579
245 // [4]: https://chromium.googlesource.com/chromium/src/base/+/master/
246 // /memory/aligned_memory.cc
247 libc::memalign(layout.align(), layout.size()) as *mut u8
250 #[cfg(not(any(target_os = "android", target_os = "redox", target_os = "solaris")))]
252 unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
253 let mut out = ptr::null_mut();
254 let ret = libc::posix_memalign(&mut out, layout.align(), layout.size());
271 use alloc::heap::{Alloc, AllocErr, Layout, CannotReallocInPlace};
273 type LPVOID = *mut u8;
274 type HANDLE = LPVOID;
278 type LPDWORD = *mut DWORD;
279 type LPOVERLAPPED = *mut u8;
281 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
284 fn GetProcessHeap() -> HANDLE;
285 fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID;
286 fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T) -> LPVOID;
287 fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID) -> BOOL;
288 fn GetLastError() -> DWORD;
289 fn WriteFile(hFile: HANDLE,
291 nNumberOfBytesToWrite: DWORD,
292 lpNumberOfBytesWritten: LPDWORD,
293 lpOverlapped: LPOVERLAPPED)
295 fn GetStdHandle(which: DWORD) -> HANDLE;
299 struct Header(*mut u8);
301 const HEAP_ZERO_MEMORY: DWORD = 0x00000008;
302 const HEAP_REALLOC_IN_PLACE_ONLY: DWORD = 0x00000010;
304 unsafe fn get_header<'a>(ptr: *mut u8) -> &'a mut Header {
305 &mut *(ptr as *mut Header).offset(-1)
308 unsafe fn align_ptr(ptr: *mut u8, align: usize) -> *mut u8 {
309 let aligned = ptr.offset((align - (ptr as usize & (align - 1))) as isize);
310 *get_header(aligned) = Header(ptr);
315 unsafe fn allocate_with_flags(layout: Layout, flags: DWORD)
316 -> Result<*mut u8, AllocErr>
318 let ptr = if layout.align() <= MIN_ALIGN {
319 HeapAlloc(GetProcessHeap(), flags, layout.size())
321 let size = layout.size() + layout.align();
322 let ptr = HeapAlloc(GetProcessHeap(), flags, size);
326 align_ptr(ptr, layout.align())
330 Err(AllocErr::Exhausted { request: layout })
336 #[unstable(feature = "allocator_api", issue = "32838")]
337 unsafe impl<'a> Alloc for &'a System {
339 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
340 allocate_with_flags(layout, 0)
344 unsafe fn alloc_zeroed(&mut self, layout: Layout)
345 -> Result<*mut u8, AllocErr>
347 allocate_with_flags(layout, HEAP_ZERO_MEMORY)
351 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
352 if layout.align() <= MIN_ALIGN {
353 let err = HeapFree(GetProcessHeap(), 0, ptr as LPVOID);
354 debug_assert!(err != 0, "Failed to free heap memory: {}",
357 let header = get_header(ptr);
358 let err = HeapFree(GetProcessHeap(), 0, header.0 as LPVOID);
359 debug_assert!(err != 0, "Failed to free heap memory: {}",
365 unsafe fn realloc(&mut self,
368 new_layout: Layout) -> Result<*mut u8, AllocErr> {
369 if old_layout.align() != new_layout.align() {
370 return Err(AllocErr::Unsupported {
371 details: "cannot change alignment on `realloc`",
375 if new_layout.align() <= MIN_ALIGN {
376 let ptr = HeapReAlloc(GetProcessHeap(),
383 Err(AllocErr::Exhausted { request: new_layout })
386 let res = self.alloc(new_layout.clone());
387 if let Ok(new_ptr) = res {
388 let size = cmp::min(old_layout.size(), new_layout.size());
389 ptr::copy_nonoverlapping(ptr, new_ptr, size);
390 self.dealloc(ptr, old_layout);
397 unsafe fn grow_in_place(&mut self,
400 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
401 self.shrink_in_place(ptr, layout, new_layout)
405 unsafe fn shrink_in_place(&mut self,
408 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
409 if old_layout.align() != new_layout.align() {
410 return Err(CannotReallocInPlace)
413 let new = if new_layout.align() <= MIN_ALIGN {
414 HeapReAlloc(GetProcessHeap(),
415 HEAP_REALLOC_IN_PLACE_ONLY,
419 let header = get_header(ptr);
420 HeapReAlloc(GetProcessHeap(),
421 HEAP_REALLOC_IN_PLACE_ONLY,
423 new_layout.size() + new_layout.align())
426 Err(CannotReallocInPlace)
432 fn oom(&mut self, err: AllocErr) -> ! {
433 use core::fmt::{self, Write};
435 // Same as with unix we ignore all errors here
436 drop(writeln!(Stderr, "fatal runtime error: {}", err));
438 ::core::intrinsics::abort();
443 impl Write for Stderr {
444 fn write_str(&mut self, s: &str) -> fmt::Result {
446 // WriteFile silently fails if it is passed an invalid
447 // handle, so there is no need to check the result of
449 WriteFile(GetStdHandle(STD_ERROR_HANDLE),
450 s.as_ptr() as LPVOID,