Skip to content

Instantly share code, notes, and snippets.

@siddontang
Created July 26, 2019 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddontang/d2b49ed89bbb7db90b55eff9920161bb to your computer and use it in GitHub Desktop.
Save siddontang/d2b49ed89bbb7db90b55eff9920161bb to your computer and use it in GitHub Desktop.
extern crate backtrace;
extern crate libc;
use backtrace::BytesOrWideString;
use std::alloc::{System, GlobalAlloc, Layout};
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
struct Counter;
static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counter {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ret = System.alloc(layout);
if !ret.is_null() {
ALLOCATED.fetch_add(layout.size(), SeqCst);
}
backtrace::trace_unsynchronized(|frame| {
let ip = frame.ip();
let symbol_address = frame.symbol_address();
backtrace::resolve_frame_unsynchronized(frame, |symbol|{
if let Some(name) = symbol.name() {
unsafe{
::libc::printf(name.as_bytes().as_ptr() as *const ::libc::c_char);
::libc::printf(b"\t".as_ptr() as *const ::libc::c_char);
}
}
if let Some(filename) = symbol.filename_raw() {
if let BytesOrWideString::Bytes(b) = filename {
unsafe{
::libc::printf(b.as_ptr() as *const ::libc::c_char);
}
}
}
if let Some(lineno) = symbol.lineno() {
unsafe{
::libc::printf(b":%d".as_ptr() as *const ::libc::c_char, lineno);
}
}
unsafe{
::libc::printf(b"\n".as_ptr() as *const ::libc::c_char);
}
});
true
});
unsafe{
::libc::printf(b"\n\n".as_ptr() as *const ::libc::c_char);
}
return ret
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout);
ALLOCATED.fetch_sub(layout.size(), SeqCst);
}
}
#[global_allocator]
static A: Counter = Counter;
fn test_c() {
let a = Box::new(4);
println!("hello world {:?}", a);
}
fn test_b() {
test_c()
}
fn test_a() {
test_b()
}
fn main() {
test_a();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment