Skip to content

#[track_caller] for allocator APIs? #74763

Closed
@anp

Description

@anp
Member

Apologies if this has been raised before, but I've been playing around with trying to track where allocations happen with something like so:

use libc_print::libc_println;
use std::alloc::{GlobalAlloc, Layout};
use std::panic::Location;

pub struct TracedAlloc<T: GlobalAlloc> {
    pub allocator: T,
}

unsafe impl<T> GlobalAlloc for TracedAlloc<T>
where
    T: GlobalAlloc,
{
    #[track_caller]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        libc_println!("Alloc {:?} at {:?}", layout, Location::caller());
        self.allocator.alloc(layout)
    }

    #[track_caller]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        libc_println!("Dealloc {:?} at {:?}", layout, Location::caller());
        self.allocator.dealloc(ptr, layout)
    }
}

However the caller location is always the line I've put #[global_allocator] which makes #[track_caller] useless in this context.

Originally posted by @xd009642 in #47809 (comment)


note from @anp: I'm not sure how the global allocator hooks in but this might be possible?

Activity

jdm

jdm commented on Jul 25, 2020

@jdm
Contributor

I'm not sure if this will work, given the indirection in

#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
unsafe { __rust_alloc(layout.size(), layout.align()) }
}
. That method is called by the methods generated by #[global_alloc], per this comment.

anp

anp commented on Jul 25, 2020

@anp
MemberAuthor

Yeah, the only way to carry #[track_caller] through an extern "Rust" block is if both sides have it declared. It's technically possible but it would be a new (breaking) requirement on all allocators so I don't think that's feasible.

lqd

lqd commented on Jul 26, 2020

@lqd
Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jdm@lqd@anp

        Issue actions

          #[track_caller] for allocator APIs? · Issue #74763 · rust-lang/rust