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.
13 // Arenas are used to quickly allocate objects that share a
14 // lifetime. The arena uses ~[u8] vectors as a backing store to
15 // allocate objects from. For each allocated object, the arena stores
16 // a pointer to the type descriptor followed by the
17 // object. (Potentially with alignment padding after each of them.)
18 // When the arena is destroyed, it iterates through all of its chunks,
19 // and uses the tydesc information to trace through the objects,
20 // calling the destructors on them.
21 // One subtle point that needs to be addressed is how to handle
22 // failures while running the user provided initializer function. It
23 // is important to not run the destructor on uninitalized objects, but
24 // how to detect them is somewhat subtle. Since alloc() can be invoked
25 // recursively, it is not sufficient to simply exclude the most recent
26 // object. To solve this without requiring extra space, we use the low
27 // order bit of the tydesc pointer to encode whether the object it
28 // describes has been fully initialized.
30 // As an optimization, objects with destructors are stored in
31 // different chunks than objects without destructors. This reduces
32 // overhead when initializing plain-old-data and means we don't need
33 // to waste time running the destructors of POD.
35 use list::{MutList, MutCons, MutNil};
39 use core::cast::{transmute, transmute_mut_region};
41 use core::libc::size_t;
43 use core::sys::TypeDesc;
49 #[abi = "rust-intrinsic"]
50 pub extern "rust-intrinsic" {
51 fn move_val_init<T>(dst: &mut T, +src: T);
52 fn needs_drop<T>() -> bool;
57 use core::libc::size_t;
58 use core::sys::TypeDesc;
62 unsafe fn rust_call_tydesc_glue(root: *u8,
68 // This probably belongs somewhere else. Needs to be kept in sync with
70 static tydesc_drop_glue_index: size_t = 3 as size_t;
72 // The way arena uses arrays is really deeply awful. The arrays are
73 // allocated, and have capacities reserved, but the fill for the array
74 // will always stay at 0.
82 // The head is seperated out from the list as a unbenchmarked
83 // microoptimization, to avoid needing to case on the list to
87 priv chunks: @mut MutList<Chunk>,
94 destroy_chunk(&self.head);
95 for self.chunks.each |chunk| {
104 fn chunk(size: uint, is_pod: bool) -> Chunk {
105 let mut v: @[u8] = @[];
106 unsafe { at_vec::raw::reserve(&mut v, size); }
108 data: unsafe { cast::transmute(v) },
114 pub fn arena_with_size(initial_size: uint) -> Arena {
116 head: chunk(initial_size, false),
117 pod_head: chunk(initial_size, true),
122 pub fn Arena() -> Arena {
127 fn round_up_to(base: uint, align: uint) -> uint {
128 (base + (align - 1)) & !(align - 1)
131 // Walk down a chunk, running the destructors for any objects stored
133 unsafe fn destroy_chunk(chunk: &Chunk) {
135 let buf = vec::raw::to_ptr(chunk.data);
136 let fill = chunk.fill;
139 let tydesc_data: *uint = transmute(ptr::offset(buf, idx));
140 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
141 let size = (*tydesc).size, align = (*tydesc).align;
143 let after_tydesc = idx + sys::size_of::<*TypeDesc>();
145 let start = round_up_to(after_tydesc, align);
147 //debug!("freeing object: idx = %u, size = %u, align = %u, done = %b",
148 // start, size, align, is_done);
150 rustrt::rust_call_tydesc_glue(
151 ptr::offset(buf, start), tydesc, tydesc_drop_glue_index);
154 // Find where the next tydesc lives
155 idx = round_up_to(start + size, sys::pref_align_of::<*TypeDesc>());
159 // We encode whether the object a tydesc describes has been
160 // initialized in the arena in the low bit of the tydesc pointer. This
161 // is necessary in order to properly do cleanup if a failure occurs
162 // during an initializer.
164 unsafe fn bitpack_tydesc_ptr(p: *TypeDesc, is_done: bool) -> uint {
165 let p_bits: uint = transmute(p);
166 p_bits | (is_done as uint)
169 unsafe fn un_bitpack_tydesc_ptr(p: uint) -> (*TypeDesc, bool) {
170 (transmute(p & !1), p & 1 == 1)
174 // Functions for the POD part of the arena
175 priv fn alloc_pod_grow(&mut self, n_bytes: uint, align: uint) -> *u8 {
176 // Allocate a new chunk.
177 let chunk_size = at_vec::capacity(self.pod_head.data);
178 let new_min_chunk_size = uint::max(n_bytes, chunk_size);
179 self.chunks = @mut MutCons(copy self.pod_head, self.chunks);
181 chunk(uint::next_power_of_two(new_min_chunk_size + 1u), true);
183 return self.alloc_pod_inner(n_bytes, align);
187 priv fn alloc_pod_inner(&mut self, n_bytes: uint, align: uint) -> *u8 {
190 let head = transmute_mut_region(&mut self.pod_head);
192 let start = round_up_to(head.fill, align);
193 let end = start + n_bytes;
194 if end > at_vec::capacity(head.data) {
195 return self.alloc_pod_grow(n_bytes, align);
199 //debug!("idx = %u, size = %u, align = %u, fill = %u",
200 // start, n_bytes, align, head.fill);
202 ptr::offset(vec::raw::to_ptr(head.data), start)
208 priv fn alloc_pod<T>(&mut self, op: &fn() -> T) -> &'self T {
210 let tydesc = sys::get_type_desc::<T>();
211 let ptr = self.alloc_pod_inner((*tydesc).size, (*tydesc).align);
212 let ptr: *mut T = transmute(ptr);
213 rusti::move_val_init(&mut (*ptr), op());
214 return transmute(ptr);
222 priv fn alloc_pod<'a, T>(&'a mut self, op: &fn() -> T) -> &'a T {
224 let tydesc = sys::get_type_desc::<T>();
225 let ptr = self.alloc_pod_inner((*tydesc).size, (*tydesc).align);
226 let ptr: *mut T = transmute(ptr);
227 rusti::move_val_init(&mut (*ptr), op());
228 return transmute(ptr);
232 // Functions for the non-POD part of the arena
233 priv fn alloc_nonpod_grow(&mut self, n_bytes: uint, align: uint)
235 // Allocate a new chunk.
236 let chunk_size = at_vec::capacity(self.head.data);
237 let new_min_chunk_size = uint::max(n_bytes, chunk_size);
238 self.chunks = @mut MutCons(copy self.head, self.chunks);
240 chunk(uint::next_power_of_two(new_min_chunk_size + 1u), false);
242 return self.alloc_nonpod_inner(n_bytes, align);
246 priv fn alloc_nonpod_inner(&mut self, n_bytes: uint, align: uint)
249 let head = transmute_mut_region(&mut self.head);
251 let tydesc_start = head.fill;
252 let after_tydesc = head.fill + sys::size_of::<*TypeDesc>();
253 let start = round_up_to(after_tydesc, align);
254 let end = start + n_bytes;
255 if end > at_vec::capacity(head.data) {
256 return self.alloc_nonpod_grow(n_bytes, align);
258 head.fill = round_up_to(end, sys::pref_align_of::<*TypeDesc>());
260 //debug!("idx = %u, size = %u, align = %u, fill = %u",
261 // start, n_bytes, align, head.fill);
263 let buf = vec::raw::to_ptr(head.data);
264 return (ptr::offset(buf, tydesc_start), ptr::offset(buf, start));
270 priv fn alloc_nonpod<T>(&mut self, op: &fn() -> T) -> &'self T {
272 let tydesc = sys::get_type_desc::<T>();
274 self.alloc_nonpod_inner((*tydesc).size, (*tydesc).align);
275 let ty_ptr: *mut uint = transmute(ty_ptr);
276 let ptr: *mut T = transmute(ptr);
277 // Write in our tydesc along with a bit indicating that it
278 // has *not* been initialized yet.
279 *ty_ptr = transmute(tydesc);
280 // Actually initialize it
281 rusti::move_val_init(&mut(*ptr), op());
282 // Now that we are done, update the tydesc to indicate that
283 // the object is there.
284 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
286 return transmute(ptr);
294 priv fn alloc_nonpod<'a, T>(&'a mut self, op: &fn() -> T) -> &'a T {
296 let tydesc = sys::get_type_desc::<T>();
298 self.alloc_nonpod_inner((*tydesc).size, (*tydesc).align);
299 let ty_ptr: *mut uint = transmute(ty_ptr);
300 let ptr: *mut T = transmute(ptr);
301 // Write in our tydesc along with a bit indicating that it
302 // has *not* been initialized yet.
303 *ty_ptr = transmute(tydesc);
304 // Actually initialize it
305 rusti::move_val_init(&mut(*ptr), op());
306 // Now that we are done, update the tydesc to indicate that
307 // the object is there.
308 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
310 return transmute(ptr);
314 // The external interface
317 fn alloc<T>(&mut self, op: &fn() -> T) -> &'self T {
320 let this = transmute_mut_region(self);
321 if !rusti::needs_drop::<T>() {
322 return this.alloc_pod(op);
325 let this = transmute_mut_region(self);
326 this.alloc_nonpod(op)
330 // The external interface
335 fn alloc<'a, T>(&'a mut self, op: &fn() -> T) -> &'a T {
338 let this = transmute_mut_region(self);
339 if !rusti::needs_drop::<T>() {
340 return this.alloc_pod(op);
343 let this = transmute_mut_region(self);
344 this.alloc_nonpod(op)
350 fn test_arena_destructors() {
352 for uint::range(0, 10) |i| {
353 // Arena allocate something with drop glue to make sure it
355 do arena.alloc { @i };
356 // Allocate something with funny size and alignment, to keep
357 // things interesting.
358 do arena.alloc { [0u8, 1u8, 2u8] };
364 #[ignore(cfg(windows))]
365 fn test_arena_destructors_fail() {
367 // Put some stuff in the arena.
368 for uint::range(0, 10) |i| {
369 // Arena allocate something with drop glue to make sure it
371 do arena.alloc { @i };
372 // Allocate something with funny size and alignment, to keep
373 // things interesting.
374 do arena.alloc { [0u8, 1u8, 2u8] };
376 // Now, fail while allocating
377 do arena.alloc::<@int> {
378 // First, recursively allocate something else; that needs to
380 do arena.alloc { @20 };