Vladimir Chtchetkine | b74ceb2 | 2009-11-17 14:13:38 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2009 The Android Open Source Project |
| 3 | * All rights reserved. |
| 4 | * |
| 5 | * Redistribution and use in source and binary forms, with or without |
| 6 | * modification, are permitted provided that the following conditions |
| 7 | * are met: |
| 8 | * * Redistributions of source code must retain the above copyright |
| 9 | * notice, this list of conditions and the following disclaimer. |
| 10 | * * Redistributions in binary form must reproduce the above copyright |
| 11 | * notice, this list of conditions and the following disclaimer in |
| 12 | * the documentation and/or other materials provided with the |
| 13 | * distribution. |
| 14 | * |
| 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 16 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 17 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
| 18 | * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
| 19 | * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 20 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
| 21 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS |
| 22 | * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
| 23 | * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 24 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT |
| 25 | * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
| 26 | * SUCH DAMAGE. |
| 27 | */ |
| 28 | |
| 29 | /* |
| 30 | * Contains definition of global variables and implementation of routines |
| 31 | * that are used by malloc leak detection code and other components in |
| 32 | * the system. The trick is that some components expect these data and |
| 33 | * routines to be defined / implemented in libc.so library, regardless |
| 34 | * whether or not MALLOC_LEAK_CHECK macro is defined. To make things even |
| 35 | * more tricky, malloc leak detection code, implemented in |
| 36 | * libc_malloc_debug.so also requires access to these variables and routines |
| 37 | * (to fill allocation entry hash table, for example). So, all relevant |
| 38 | * variables and routines are defined / implemented here and exported |
| 39 | * to all, leak detection code and other components via dynamic (libc.so), |
| 40 | * or static (libc.a) linking. |
| 41 | */ |
| 42 | |
| 43 | #include <stdlib.h> |
| 44 | #include <pthread.h> |
| 45 | #include <unistd.h> |
| 46 | #include "dlmalloc.h" |
| 47 | #include "malloc_debug_common.h" |
| 48 | |
| 49 | /* |
| 50 | * In a VM process, this is set to 1 after fork()ing out of zygote. |
| 51 | */ |
| 52 | int gMallocLeakZygoteChild = 0; |
| 53 | |
| 54 | pthread_mutex_t gAllocationsMutex = PTHREAD_MUTEX_INITIALIZER; |
| 55 | HashTable gHashTable; |
| 56 | |
| 57 | // ============================================================================= |
| 58 | // output functions |
| 59 | // ============================================================================= |
| 60 | |
| 61 | static int hash_entry_compare(const void* arg1, const void* arg2) |
| 62 | { |
| 63 | HashEntry* e1 = *(HashEntry**)arg1; |
| 64 | HashEntry* e2 = *(HashEntry**)arg2; |
| 65 | |
| 66 | size_t nbAlloc1 = e1->allocations; |
| 67 | size_t nbAlloc2 = e2->allocations; |
| 68 | size_t size1 = e1->size & ~SIZE_FLAG_MASK; |
| 69 | size_t size2 = e2->size & ~SIZE_FLAG_MASK; |
| 70 | size_t alloc1 = nbAlloc1 * size1; |
| 71 | size_t alloc2 = nbAlloc2 * size2; |
| 72 | |
| 73 | // sort in descending order by: |
| 74 | // 1) total size |
| 75 | // 2) number of allocations |
| 76 | // |
| 77 | // This is used for sorting, not determination of equality, so we don't |
| 78 | // need to compare the bit flags. |
| 79 | int result; |
| 80 | if (alloc1 > alloc2) { |
| 81 | result = -1; |
| 82 | } else if (alloc1 < alloc2) { |
| 83 | result = 1; |
| 84 | } else { |
| 85 | if (nbAlloc1 > nbAlloc2) { |
| 86 | result = -1; |
| 87 | } else if (nbAlloc1 < nbAlloc2) { |
| 88 | result = 1; |
| 89 | } else { |
| 90 | result = 0; |
| 91 | } |
| 92 | } |
| 93 | return result; |
| 94 | } |
| 95 | |
| 96 | /* |
| 97 | * Retrieve native heap information. |
| 98 | * |
| 99 | * "*info" is set to a buffer we allocate |
| 100 | * "*overallSize" is set to the size of the "info" buffer |
| 101 | * "*infoSize" is set to the size of a single entry |
| 102 | * "*totalMemory" is set to the sum of all allocations we're tracking; does |
| 103 | * not include heap overhead |
| 104 | * "*backtraceSize" is set to the maximum number of entries in the back trace |
| 105 | */ |
| 106 | void get_malloc_leak_info(uint8_t** info, size_t* overallSize, |
| 107 | size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) |
| 108 | { |
| 109 | // don't do anything if we have invalid arguments |
| 110 | if (info == NULL || overallSize == NULL || infoSize == NULL || |
| 111 | totalMemory == NULL || backtraceSize == NULL) { |
| 112 | return; |
| 113 | } |
| 114 | |
| 115 | pthread_mutex_lock(&gAllocationsMutex); |
| 116 | |
| 117 | if (gHashTable.count == 0) { |
| 118 | *info = NULL; |
| 119 | *overallSize = 0; |
| 120 | *infoSize = 0; |
| 121 | *totalMemory = 0; |
| 122 | *backtraceSize = 0; |
| 123 | goto done; |
| 124 | } |
| 125 | |
| 126 | void** list = (void**)dlmalloc(sizeof(void*) * gHashTable.count); |
| 127 | |
| 128 | // get the entries into an array to be sorted |
| 129 | int index = 0; |
| 130 | int i; |
| 131 | for (i = 0 ; i < HASHTABLE_SIZE ; i++) { |
| 132 | HashEntry* entry = gHashTable.slots[i]; |
| 133 | while (entry != NULL) { |
| 134 | list[index] = entry; |
| 135 | *totalMemory = *totalMemory + |
| 136 | ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations); |
| 137 | index++; |
| 138 | entry = entry->next; |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | // XXX: the protocol doesn't allow variable size for the stack trace (yet) |
| 143 | *infoSize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * BACKTRACE_SIZE); |
| 144 | *overallSize = *infoSize * gHashTable.count; |
| 145 | *backtraceSize = BACKTRACE_SIZE; |
| 146 | |
| 147 | // now get A byte array big enough for this |
| 148 | *info = (uint8_t*)dlmalloc(*overallSize); |
| 149 | |
| 150 | if (*info == NULL) { |
| 151 | *overallSize = 0; |
| 152 | goto done; |
| 153 | } |
| 154 | |
| 155 | qsort((void*)list, gHashTable.count, sizeof(void*), hash_entry_compare); |
| 156 | |
| 157 | uint8_t* head = *info; |
| 158 | const int count = gHashTable.count; |
| 159 | for (i = 0 ; i < count ; i++) { |
| 160 | HashEntry* entry = list[i]; |
| 161 | size_t entrySize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * entry->numEntries); |
| 162 | if (entrySize < *infoSize) { |
| 163 | /* we're writing less than a full entry, clear out the rest */ |
| 164 | /* TODO: only clear out the part we're not overwriting? */ |
| 165 | memset(head, 0, *infoSize); |
| 166 | } else { |
| 167 | /* make sure the amount we're copying doesn't exceed the limit */ |
| 168 | entrySize = *infoSize; |
| 169 | } |
| 170 | memcpy(head, &(entry->size), entrySize); |
| 171 | head += *infoSize; |
| 172 | } |
| 173 | |
| 174 | dlfree(list); |
| 175 | |
| 176 | done: |
| 177 | pthread_mutex_unlock(&gAllocationsMutex); |
| 178 | } |
| 179 | |
| 180 | void free_malloc_leak_info(uint8_t* info) |
| 181 | { |
| 182 | dlfree(info); |
| 183 | } |
| 184 | |
| 185 | struct mallinfo mallinfo() |
| 186 | { |
| 187 | return dlmallinfo(); |
| 188 | } |
| 189 | |
| 190 | void* valloc(size_t bytes) { |
| 191 | /* assume page size of 4096 bytes */ |
| 192 | return memalign( getpagesize(), bytes ); |
| 193 | } |
| 194 | |
| 195 | /* Support for malloc debugging. |
| 196 | * Note that if USE_DL_PREFIX is not defined, it's assumed that memory |
| 197 | * allocation routines are implemented somewhere else, so all our custom |
| 198 | * malloc routines should not be compiled at all. |
| 199 | */ |
| 200 | #ifdef USE_DL_PREFIX |
| 201 | |
| 202 | /* Table for dispatching malloc calls, initialized with default dispatchers. */ |
| 203 | const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = |
| 204 | { |
| 205 | dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign |
| 206 | }; |
| 207 | |
| 208 | /* Selector of dispatch table to use for dispatching malloc calls. */ |
| 209 | const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch; |
| 210 | |
| 211 | void* malloc(size_t bytes) { |
| 212 | return __libc_malloc_dispatch->malloc(bytes); |
| 213 | } |
| 214 | void free(void* mem) { |
| 215 | __libc_malloc_dispatch->free(mem); |
| 216 | } |
| 217 | void* calloc(size_t n_elements, size_t elem_size) { |
| 218 | return __libc_malloc_dispatch->calloc(n_elements, elem_size); |
| 219 | } |
| 220 | void* realloc(void* oldMem, size_t bytes) { |
| 221 | return __libc_malloc_dispatch->realloc(oldMem, bytes); |
| 222 | } |
| 223 | void* memalign(size_t alignment, size_t bytes) { |
| 224 | return __libc_malloc_dispatch->memalign(alignment, bytes); |
| 225 | } |
| 226 | |
| 227 | /* We implement malloc debugging only in libc.so, so code bellow |
| 228 | * must be excluded if we compile this file for static libc.a |
| 229 | */ |
| 230 | #ifndef LIBC_STATIC |
| 231 | #include <sys/system_properties.h> |
| 232 | #include <dlfcn.h> |
| 233 | #include "logd.h" |
| 234 | |
| 235 | // ============================================================================= |
| 236 | // log functions |
| 237 | // ============================================================================= |
| 238 | |
| 239 | #define debug_log(format, ...) \ |
| 240 | __libc_android_log_print(ANDROID_LOG_DEBUG, "libc", (format), ##__VA_ARGS__ ) |
| 241 | #define error_log(format, ...) \ |
| 242 | __libc_android_log_print(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ ) |
| 243 | #define info_log(format, ...) \ |
| 244 | __libc_android_log_print(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ ) |
| 245 | |
| 246 | /* Table for dispatching malloc calls, depending on environment. */ |
| 247 | static MallocDebug gMallocUse __attribute__((aligned(32))) = { |
| 248 | dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign |
| 249 | }; |
| 250 | |
| 251 | extern char* __progname; |
| 252 | |
| 253 | /* Handle to shared library where actual memory allocation is implemented. |
| 254 | * This library is loaded and memory allocation calls are redirected there |
| 255 | * when libc.debug.malloc environment variable contains value other than |
| 256 | * zero: |
| 257 | * 1 - For memory leak detections. |
| 258 | * 5 - For filling allocated / freed memory with patterns defined by |
| 259 | * CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros. |
| 260 | * 10 - For adding pre-, and post- allocation stubs in order to detect |
| 261 | * buffer overruns. |
| 262 | * 20 - For enabling emulator memory allocation instrumentation detecting |
| 263 | * memory leaks and buffer overruns. |
| 264 | * Actual functionality for debug levels 1-10 is implemented in |
| 265 | * libc_malloc_debug_leak.so, while functionality for debug level 20 is |
| 266 | * implemented in libc_malloc_debug_qemu.so and can be run inside the |
| 267 | * emulator only. |
| 268 | */ |
| 269 | static void* libc_malloc_impl_handle = NULL; |
| 270 | |
| 271 | /* Initializes memory allocation framework once per process. */ |
| 272 | static void malloc_init_impl(void) |
| 273 | { |
| 274 | const char* so_name = NULL; |
| 275 | unsigned int debug_level = 0; |
| 276 | unsigned int qemu_running = 0; |
| 277 | int len; |
| 278 | char env[PROP_VALUE_MAX]; |
| 279 | |
| 280 | // Get custom malloc debug level. |
| 281 | len = __system_property_get("libc.debug.malloc", env); |
| 282 | if (len) { |
| 283 | debug_level = atoi(env); |
| 284 | } |
| 285 | |
| 286 | /* Debug level 0 means that we should use dlxxx allocation |
| 287 | * routines (default). |
| 288 | */ |
| 289 | if (!debug_level) { |
| 290 | return; |
| 291 | } |
| 292 | |
| 293 | // Get emulator running status. |
| 294 | len = __system_property_get("ro.kernel.qemu", env); |
| 295 | if (len) { |
| 296 | qemu_running = atoi(env); |
| 297 | } |
| 298 | |
| 299 | // Lets see which .so must be loaded for the requested debug level |
| 300 | switch (debug_level) { |
| 301 | case 1: |
| 302 | case 5: |
| 303 | case 10: |
| 304 | so_name = "/system/lib/libc_malloc_debug_leak.so"; |
| 305 | break; |
| 306 | case 20: |
| 307 | // Quick check: debug level 20 can only be handled in emulator |
| 308 | if (!qemu_running) { |
| 309 | info_log("%s: Debug level %d can only be set in emulator\n", |
| 310 | __progname, debug_level); |
| 311 | return; |
| 312 | } |
| 313 | so_name = "/system/lib/libc_malloc_debug_qemu.so"; |
| 314 | break; |
| 315 | default: |
| 316 | info_log("%s: Debug level %d is unknown\n", |
| 317 | __progname, debug_level); |
| 318 | return; |
| 319 | } |
| 320 | |
| 321 | // Load .so that implements the required malloc debugging functionality. |
| 322 | libc_malloc_impl_handle = dlopen(so_name, RTLD_LAZY); |
| 323 | if (libc_malloc_impl_handle == NULL) { |
| 324 | error_log("%s: Missing module %s required for malloc debug level %d\n", |
| 325 | __progname, so_name, debug_level); |
| 326 | return; |
| 327 | } |
| 328 | |
| 329 | // Initialize malloc dispatch table with appropriate routines. |
| 330 | switch (debug_level) { |
| 331 | case 1: |
| 332 | __libc_android_log_print(ANDROID_LOG_INFO, "libc", |
| 333 | "%s using MALLOC_DEBUG = %d (leak checker)\n", |
| 334 | __progname, debug_level); |
| 335 | gMallocUse.malloc = |
| 336 | dlsym(libc_malloc_impl_handle, "leak_malloc"); |
| 337 | gMallocUse.free = |
| 338 | dlsym(libc_malloc_impl_handle, "leak_free"); |
| 339 | gMallocUse.calloc = |
| 340 | dlsym(libc_malloc_impl_handle, "leak_calloc"); |
| 341 | gMallocUse.realloc = |
| 342 | dlsym(libc_malloc_impl_handle, "leak_realloc"); |
| 343 | gMallocUse.memalign = |
| 344 | dlsym(libc_malloc_impl_handle, "leak_memalign"); |
| 345 | break; |
| 346 | case 5: |
| 347 | __libc_android_log_print(ANDROID_LOG_INFO, "libc", |
| 348 | "%s using MALLOC_DEBUG = %d (fill)\n", |
| 349 | __progname, debug_level); |
| 350 | gMallocUse.malloc = |
| 351 | dlsym(libc_malloc_impl_handle, "fill_malloc"); |
| 352 | gMallocUse.free = |
| 353 | dlsym(libc_malloc_impl_handle, "fill_free"); |
| 354 | gMallocUse.calloc = dlcalloc; |
| 355 | gMallocUse.realloc = |
| 356 | dlsym(libc_malloc_impl_handle, "fill_realloc"); |
| 357 | gMallocUse.memalign = |
| 358 | dlsym(libc_malloc_impl_handle, "fill_memalign"); |
| 359 | break; |
| 360 | case 10: |
| 361 | __libc_android_log_print(ANDROID_LOG_INFO, "libc", |
| 362 | "%s using MALLOC_DEBUG = %d (sentinels, fill)\n", |
| 363 | __progname, debug_level); |
| 364 | gMallocUse.malloc = |
| 365 | dlsym(libc_malloc_impl_handle, "chk_malloc"); |
| 366 | gMallocUse.free = |
| 367 | dlsym(libc_malloc_impl_handle, "chk_free"); |
| 368 | gMallocUse.calloc = |
| 369 | dlsym(libc_malloc_impl_handle, "chk_calloc"); |
| 370 | gMallocUse.realloc = |
| 371 | dlsym(libc_malloc_impl_handle, "chk_realloc"); |
| 372 | gMallocUse.memalign = |
| 373 | dlsym(libc_malloc_impl_handle, "chk_memalign"); |
| 374 | break; |
| 375 | case 20: |
| 376 | __libc_android_log_print(ANDROID_LOG_INFO, "libc", |
| 377 | "%s using MALLOC_DEBUG = %d (instrumented for emulator)\n", |
| 378 | __progname, debug_level); |
| 379 | gMallocUse.malloc = |
| 380 | dlsym(libc_malloc_impl_handle, "qemu_instrumented_malloc"); |
| 381 | gMallocUse.free = |
| 382 | dlsym(libc_malloc_impl_handle, "qemu_instrumented_free"); |
| 383 | gMallocUse.calloc = |
| 384 | dlsym(libc_malloc_impl_handle, "qemu_instrumented_calloc"); |
| 385 | gMallocUse.realloc = |
| 386 | dlsym(libc_malloc_impl_handle, "qemu_instrumented_realloc"); |
| 387 | gMallocUse.memalign = |
| 388 | dlsym(libc_malloc_impl_handle, "qemu_instrumented_memalign"); |
| 389 | break; |
| 390 | default: |
| 391 | break; |
| 392 | } |
| 393 | |
| 394 | // Make sure dispatch table is initialized |
| 395 | if ((gMallocUse.malloc == NULL) || |
| 396 | (gMallocUse.free == NULL) || |
| 397 | (gMallocUse.calloc == NULL) || |
| 398 | (gMallocUse.realloc == NULL) || |
| 399 | (gMallocUse.memalign == NULL)) { |
| 400 | error_log("%s: Cannot initialize malloc dispatch table for debug level" |
| 401 | " %d: %p, %p, %p, %p, %p\n", |
| 402 | __progname, debug_level, |
| 403 | gMallocUse.malloc, gMallocUse.free, |
| 404 | gMallocUse.calloc, gMallocUse.realloc, |
| 405 | gMallocUse.memalign); |
| 406 | dlclose(libc_malloc_impl_handle); |
| 407 | libc_malloc_impl_handle = NULL; |
| 408 | } else { |
| 409 | __libc_malloc_dispatch = &gMallocUse; |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT; |
| 414 | |
| 415 | #endif // !LIBC_STATIC |
| 416 | #endif // USE_DL_PREFIX |
| 417 | |
| 418 | /* Initializes memory allocation framework. |
| 419 | * This routine is called from __libc_init routines implemented |
| 420 | * in libc_init_static.c and libc_init_dynamic.c files. |
| 421 | */ |
| 422 | void malloc_debug_init(void) |
| 423 | { |
| 424 | /* We need to initialize malloc iff we impelement here custom |
| 425 | * malloc routines (i.e. USE_DL_PREFIX is defined) for libc.so |
| 426 | */ |
| 427 | #if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC) |
| 428 | if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) { |
| 429 | error_log("Unable to initialize malloc_debug component."); |
| 430 | } |
| 431 | #endif // USE_DL_PREFIX && !LIBC_STATIC |
| 432 | } |