Skip to content

Commit

Permalink
Fixed mac build by allocating tls with malloc_zone_malloc, bypassing …
Browse files Browse the repository at this point in the history
…malloc
  • Loading branch information
drowaudio committed May 24, 2024
1 parent 4963bc8 commit cbe2833
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 7 deletions.
49 changes: 47 additions & 2 deletions src/lib_rt_check.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,60 @@
#if __APPLE__
#include <libkern/OSAtomic.h>
#include <os/lock.h>
#include <malloc/malloc.h>
#endif

#include "lib_rt_check.h"
#include "interception.h"

static bool has_initialised = false;

#if __APPLE__
realtime_context_state& get_realtime_context_state()
{
struct malloc_zone_wrapper
{
static void* internal_alloc (size_t size)
{
return malloc_zone_malloc (malloc_default_zone(), size);
}

static void internal_free (void *ptr)
{
malloc_zone_free (malloc_default_zone(), ptr);
}
};

static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

auto make_tls_key = []
{
[[ maybe_unused ]]auto res = pthread_key_create (&key, malloc_zone_wrapper::internal_free);
assert(res == 0);
};

pthread_once (&key_once, make_tls_key);

auto *ptr = static_cast<realtime_context_state*> (pthread_getspecific (key));

if (ptr == nullptr)
{
ptr = static_cast<realtime_context_state*> (malloc_zone_wrapper::internal_alloc(sizeof (realtime_context_state)));
new(ptr) realtime_context_state();
pthread_setspecific (key, ptr);
}

return *ptr;
}
#else
realtime_context_state& get_realtime_context_state()
{
thread_local realtime_context_state rcs;
return rcs;
}
#endif

void log_function_if_realtime_context (const char* function_name)
{
if (! has_initialised)
Expand All @@ -36,15 +83,13 @@ void log_function_if_realtime_context (const char* function_name)
//==============================================================================
// memory
//==============================================================================
#ifndef __APPLE__
INTERCEPTOR(void*, malloc, size_t size)
{
log_function_if_realtime_context (__func__);
INTERCEPT_FUNCTION(void*, malloc, size_t);

return REAL(malloc)(size);
}
#endif


INTERCEPTOR(void*, calloc, size_t size, size_t item_size)
Expand Down
6 changes: 1 addition & 5 deletions src/lib_rt_check.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,7 @@ struct realtime_context_state

//==============================================================================
/** Returns a realtime_context_state for the current thread. */
inline realtime_context_state& get_realtime_context_state()
{
thread_local realtime_context_state rcs;
return rcs;
}
realtime_context_state& get_realtime_context_state();

//==============================================================================
inline bool is_real_time_context()
Expand Down

0 comments on commit cbe2833

Please sign in to comment.