Skip to content
This repository has been archived by the owner on Apr 9, 2020. It is now read-only.

Commit

Permalink
mononoke: allocation_tracing: support realloc + handle errors
Browse files Browse the repository at this point in the history
Summary: This makes the implementation a little more comprehensive.

Reviewed By: mitrandir77

Differential Revision: D19308863

fbshipit-source-id: b265ea645e390a9638eeb66301f69c2211b0cfa4
  • Loading branch information
krallin authored and facebook-github-bot committed Jan 8, 2020
1 parent 04f0733 commit 264a815
Showing 1 changed file with 63 additions and 5 deletions.
68 changes: 63 additions & 5 deletions common/allocation_tracing/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,50 @@ struct TracingAllocator;
// if it did allocate, any allocation with TracingAllocator would hang forever.
unsafe impl GlobalAlloc for TracingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCATION_STATS.with(|cell| {
(*cell.get()).allocated += layout.size() as u64;
});
let ret = System.alloc(layout);

if !ret.is_null() {
ALLOCATION_STATS.with(|cell| {
(*cell.get()).allocated += layout.size() as u64;
});
}

ret
}

unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let ret = System.alloc_zeroed(layout);

if !ret.is_null() {
ALLOCATION_STATS.with(|cell| {
(*cell.get()).allocated += layout.size() as u64;
});
}

ret
}

unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let ret = System.realloc(ptr, layout, new_size);

if !ret.is_null() {
ALLOCATION_STATS.with(|cell| {
(*cell.get()).freed += layout.size() as u64;
(*cell.get()).allocated += new_size as u64;
});
}

System.alloc(layout)
ret
}

unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
let ret = System.dealloc(ptr, layout);

ALLOCATION_STATS.with(|cell| {
(*cell.get()).freed += layout.size() as u64;
});

System.dealloc(ptr, layout)
ret
}
}

Expand Down Expand Up @@ -179,4 +210,31 @@ mod test {
run_test::<TestStruct5>()?;
Ok(())
}

#[test]
fn test_realloc() -> Result<(), Error> {
fn run_test<T: Default>() -> Result<(), Error> {
let (_, stats) = trace_allocations(|| {
let mut v = Vec::<T>::with_capacity(2);
v.push(T::default());
v.push(T::default());
v.push(T::default());
v.push(T::default());
v.push(T::default());
v.pop();
v.shrink_to_fit();
v
});

assert_eq!(stats.delta()?, (mem::size_of::<T>() * 4) as i64);
Ok(())
}

run_test::<TestStruct1>()?;
run_test::<TestStruct2>()?;
run_test::<TestStruct3>()?;
run_test::<TestStruct4>()?;
run_test::<TestStruct5>()?;
Ok(())
}
}

0 comments on commit 264a815

Please sign in to comment.