1 // Copyright 2012 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.
11 use libc::{c_void, c_char, size_t, uintptr_t, free, malloc, realloc};
12 use managed::raw::{BoxHeaderRepr, BoxRepr};
13 use unstable::intrinsics::TyDesc;
22 fn get_box_size(body_size: uint, body_align: uint) -> uint {
23 let header_size = size_of::<BoxHeaderRepr>();
24 // FIXME (#2699): This alignment calculation is suspicious. Is it right?
25 let total_size = align_to(header_size, body_align) + body_size;
29 // Rounds |size| to the nearest |alignment|. Invariant: |alignment| is a power
32 fn align_to(size: uint, align: uint) -> uint {
34 (size + align - 1) & !(align - 1)
37 /// A wrapper around libc::malloc, aborting on out-of-memory
39 pub unsafe fn malloc_raw(size: uint) -> *c_void {
40 let p = malloc(size as size_t);
42 // we need a non-allocating way to print an error here
48 /// A wrapper around libc::realloc, aborting on out-of-memory
50 pub unsafe fn realloc_raw(ptr: *mut c_void, size: uint) -> *mut c_void {
51 let p = realloc(ptr, size as size_t);
53 // we need a non-allocating way to print an error here
59 /// The allocator for unique pointers without contained managed pointers.
61 #[lang="exchange_malloc"]
63 pub unsafe fn exchange_malloc(size: uintptr_t) -> *c_char {
64 malloc_raw(size as uint) as *c_char
69 #[lang="closure_exchange_malloc"]
71 pub unsafe fn closure_exchange_malloc_(td: *c_char, size: uintptr_t) -> *c_char {
72 closure_exchange_malloc(td, size)
76 pub unsafe fn closure_exchange_malloc(td: *c_char, size: uintptr_t) -> *c_char {
77 let td = td as *TyDesc;
78 let size = size as uint;
80 assert!(td.is_not_null());
82 let total_size = get_box_size(size, (*td).align);
83 let p = malloc_raw(total_size as uint);
85 let box: *mut BoxRepr = p as *mut BoxRepr;
86 (*box).header.type_desc = td;
91 // NB: Calls to free CANNOT be allowed to fail, as throwing an exception from
92 // inside a landing pad may corrupt the state of the exception handler.
94 #[lang="exchange_free"]
96 pub unsafe fn exchange_free_(ptr: *c_char) {
101 pub unsafe fn exchange_free(ptr: *c_char) {
102 free(ptr as *c_void);