Skip to content

Instantly share code, notes, and snippets.

@ynkdir
Last active August 2, 2025 15:45
Show Gist options
  • Save ynkdir/a8b6c5cd7d9d062201ad78149c9d9e12 to your computer and use it in GitHub Desktop.
Save ynkdir/a8b6c5cd7d9d062201ad78149c9d9e12 to your computer and use it in GitHub Desktop.
rust logging allocator
// https://doc.rust-lang.org/std/alloc/struct.System.html
use std::alloc::{GlobalAlloc, Layout, System};
use std::io::Write;
static HEX: [[u8; 1]; 16] = [
[0x30],
[0x31],
[0x32],
[0x33],
[0x34],
[0x35],
[0x36],
[0x37],
[0x38],
[0x39],
[0x41],
[0x42],
[0x43],
[0x44],
[0x45],
[0x46],
];
fn log(msg: &str, ptr: usize) {
let mut stderr = std::io::stderr();
stderr.write(msg.as_bytes()).unwrap();
stderr.write(": 0x".as_bytes()).unwrap();
stderr.write(&HEX[ptr >> 60 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 56 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 52 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 48 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 44 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 40 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 36 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 32 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 28 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 24 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 20 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 16 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 12 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 8 & 0xF]).unwrap();
stderr.write(&HEX[ptr >> 4 & 0xF]).unwrap();
stderr.write(&HEX[ptr & 0xF]).unwrap();
stderr.write("\n".as_bytes()).unwrap();
}
struct LoggingAllocator;
unsafe impl GlobalAlloc for LoggingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { System.alloc(layout) };
log(" ALLOC", ptr as usize);
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) };
log("DEALLOC", ptr as usize);
}
}
#[global_allocator]
static ALLOCATOR: LoggingAllocator = LoggingAllocator;
fn f(p: *const u8) -> *const u8 {
println!("f(): {:p}", p);
p
}
fn g(p: *const u8) {
println!("g(): {:p}", p);
}
fn main() {
println!("main(): start");
g(f(String::from("hello").as_ptr()));
println!("main(): end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment