40 #include "boost/thread.hpp"
46 #define STATIC_TLS_KW __declspec(thread)
48 #elif defined(__APPLE__)
51 #define STATIC_TLS_KW __thread
57 #define MAX_ALLOC_INFO 1000
76 pthread_key_t g_tls_key;
77 bool g_tls_key_initialized =
false;
79 AllocInfo g_thread_alloc_info[MAX_ALLOC_INFO];
80 ros::atomic_bool g_alloc_info_used[MAX_ALLOC_INFO];
82 void tlsDestructor(
void* mem)
85 uint32_t index = info - g_thread_alloc_info;
87 g_alloc_info_used[index].store(
false);
94 int ret = pthread_key_create(&g_tls_key, tlsDestructor);
97 for (
size_t i = 0; i < MAX_ALLOC_INFO; ++i)
99 g_alloc_info_used[i].store(
false);
102 g_tls_key_initialized =
true;
107 g_tls_key_initialized =
false;
109 pthread_key_delete(g_tls_key);
112 MallocTLSInit g_malloc_tls_init;
114 AllocInfo* allocateAllocInfo()
116 if (!g_tls_key_initialized)
121 void* info = pthread_getspecific(g_tls_key);
124 for (
size_t i = 0; i < MAX_ALLOC_INFO; ++i)
126 if (g_alloc_info_used[i].exchange(
true) ==
false)
128 info = g_thread_alloc_info + i;
129 pthread_setspecific(g_tls_key, info);
135 return reinterpret_cast<AllocInfo*
>(info);
138 #endif // !HAS_TLS_KW
156 AllocInfo* tls = detail::allocateAllocInfo();
176 AllocInfo* info = detail::allocateAllocInfo();
189 AllocInfo* info = detail::allocateAllocInfo();
202 typedef void* (*MallocType)(
size_t size);
203 typedef void* (*CallocType)(
size_t nmemb,
size_t size);
204 typedef void* (*ReallocType)(
void *ptr,
size_t size);
205 typedef void* (*MemalignType)(
size_t boundary,
size_t size);
210 #define UPDATE_ALLOC_INFO(result, size, type) \
213 rosrt::detail::g_total_memory_allocated += size; \
216 ++rosrt::detail::g_##type; \
217 ++rosrt::detail::g_total_ops; \
219 if (rosrt::detail::g_break_on_alloc_or_free) \
221 std::cerr << "Issuing break due to break_on_alloc_or_free being set" << std::endl; \
225 #define UPDATE_ALLOC_INFO(result, size, type) \
226 rosrt::AllocInfo* tls = rosrt::detail::allocateAllocInfo(); \
231 tls->total_memory_allocated += size; \
237 if (tls->break_on_alloc_or_free) \
239 std::cerr << "Issuing break due to break_on_alloc_or_free being set" << std::endl; \
249 void* result = original_function(size);
265 void* result = original_function(ptr, size);
281 void* result = original_function(boundary, size);
295 static FreeType original_function =
reinterpret_cast<FreeType>(dlsym(RTLD_NEXT,
"free"));
297 original_function(ptr);
318 if (original_function == 0)
321 original_function =
reinterpret_cast<CallocType>(dlsym(RTLD_NEXT,
"calloc"));
324 void* result = original_function(nmemb, size);
333 return calloc(nmemb, size);
339 int result = original_function(ptr, alignment, size);