getsentry / sentry-native

Sentry SDK for C, C++ and native applications.
MIT License
400 stars 169 forks source link

add custom memory allocator #606

Open irov opened 2 years ago

irov commented 2 years ago

add custom memory allocator for sentry_malloc and sentry_free

thanks!

Swatinem commented 2 years ago

That is a good idea! In which form would you prefer that?

irov commented 2 years ago

I think in the simplest way, to make a define SENTRY_EXTRA_STATIC_ALLOCATION, and give the opportunity to implement these functions yourself (this is a static version).

like extern sentry_malloc & sentry_free

Dynamic - is also a definition SENTRY_EXTRA_DYNAMIC_ALLOCATION (optional, so as not to do an extra IF) and a function that sets two pointers to a function sentry_malloc & sentry_free.

Swatinem commented 2 years ago

I’m not sure making this dynamic (as in: changable at runtime) is a good idea in general.

The other thing we have to consider is that sentry-native has its own signal safe allocator which is very barebones and intentionally leaks. We want to keep that for sure.

I think it might be possible to expose two compile time options: SENTRY_SYSTEM_MALLOC / SENTRY_SYSTEM_FREE, and those two are being used instead of libc malloc/free when defined.

irov commented 2 years ago

I think it's easiest with just one define ^^

#ifndef SENTRY_EXTRA_ALLOCATOR
void *
sentry_malloc(size_t size)
{
#ifdef WITH_PAGE_ALLOCATOR
    if (sentry__page_allocator_enabled()) {
        return sentry__page_allocator_alloc(size);
    }
#endif
    return malloc(size);
}

void
sentry_free(void *ptr)
{
#ifdef WITH_PAGE_ALLOCATOR
    /* page allocator can't free */
    if (sentry__page_allocator_enabled()) {
        return;
    }
#endif
    free(ptr);
}
#endif
p0358 commented 2 years ago

I’m not sure making this dynamic (as in: changable at runtime) is a good idea in general.

Many SDKs do this with a DLL. For example Epic Online SDK (EOS). But not really "changable", just passing the pointers to functions during initialization call.