blob: 5b6e415cfe3fae59b351c1653412b24b13b62614 [file] [log] [blame]
Christopher Ferris63860cb2015-11-16 17:30:32 -08001/*
2 * Copyright (C) 2012 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#include <errno.h>
30#include <inttypes.h>
31#include <malloc.h>
32#include <string.h>
33#include <sys/cdefs.h>
34#include <sys/param.h>
35#include <unistd.h>
36
37#include <vector>
38
39#include <private/bionic_malloc_dispatch.h>
40
41#include "backtrace.h"
Christopher Ferris72df6702016-02-11 15:51:31 -080042#include "Config.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080043#include "DebugData.h"
44#include "debug_disable.h"
45#include "debug_log.h"
46#include "malloc_debug.h"
47
48// ------------------------------------------------------------------------
49// Global Data
50// ------------------------------------------------------------------------
51DebugData* g_debug;
52
53int* g_malloc_zygote_child;
54
55const MallocDispatch* g_dispatch;
56// ------------------------------------------------------------------------
57
58// ------------------------------------------------------------------------
59// Use C style prototypes for all exported functions. This makes it easy
60// to do dlsym lookups during libc initialization when malloc debug
61// is enabled.
62// ------------------------------------------------------------------------
63__BEGIN_DECLS
64
65bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child);
66void debug_finalize();
67void debug_get_malloc_leak_info(
68 uint8_t** info, size_t* overall_size, size_t* info_size, size_t* total_memory,
69 size_t* backtrace_size);
70void debug_free_malloc_leak_info(uint8_t* info);
71size_t debug_malloc_usable_size(void* pointer);
72void* debug_malloc(size_t size);
73void debug_free(void* pointer);
74void* debug_memalign(size_t alignment, size_t bytes);
75void* debug_realloc(void* pointer, size_t bytes);
76void* debug_calloc(size_t nmemb, size_t bytes);
77struct mallinfo debug_mallinfo();
78int debug_posix_memalign(void** memptr, size_t alignment, size_t size);
Colin Cross869691c2016-01-29 12:48:18 -080079int debug_iterate(uintptr_t base, size_t size,
80 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg);
81void debug_malloc_disable();
82void debug_malloc_enable();
Christopher Ferris63860cb2015-11-16 17:30:32 -080083
84#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
85void* debug_pvalloc(size_t bytes);
86void* debug_valloc(size_t size);
87#endif
88
89__END_DECLS
90// ------------------------------------------------------------------------
91
Colin Cross7a28a3c2016-02-07 22:51:15 -080092static void InitAtfork() {
93 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
94 pthread_once(&atfork_init, [](){
95 pthread_atfork(
96 [](){
97 if (g_debug != nullptr) {
98 g_debug->PrepareFork();
99 }
100 },
101 [](){
102 if (g_debug != nullptr) {
103 g_debug->PostForkParent();
104 }
105 },
106 [](){
107 if (g_debug != nullptr) {
108 g_debug->PostForkChild();
109 }
110 }
111 );
112 });
113}
Christopher Ferris63860cb2015-11-16 17:30:32 -0800114static void LogTagError(const Header* header, const void* pointer, const char* name) {
115 ScopedDisableDebugCalls disable;
116
117 error_log(LOG_DIVIDER);
Christopher Ferris7993b802016-01-28 18:35:05 -0800118 if (header->tag == DEBUG_FREE_TAG) {
119 error_log("+++ ALLOCATION %p USED AFTER FREE (%s)", pointer, name);
120 if (g_debug->config().options & FREE_TRACK) {
121 g_debug->free_track->LogBacktrace(header);
122 }
123 } else {
124 error_log("+++ ALLOCATION %p HAS INVALID TAG %" PRIx32 " (%s)", pointer, header->tag, name);
125 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800126 error_log("Backtrace at time of failure:");
127 std::vector<uintptr_t> frames(64);
128 size_t frame_num = backtrace_get(frames.data(), frames.size());
129 frames.resize(frame_num);
130 backtrace_log(frames.data(), frames.size());
131 error_log(LOG_DIVIDER);
132}
133
134static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
135 header->tag = DEBUG_TAG;
136 header->orig_pointer = orig_pointer;
137 header->size = size;
138 if (*g_malloc_zygote_child) {
139 header->set_zygote();
140 }
141 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
142 if (header->usable_size == 0) {
143 g_dispatch->free(orig_pointer);
144 return nullptr;
145 }
146 header->usable_size -= g_debug->pointer_offset() +
147 reinterpret_cast<uintptr_t>(orig_pointer) - reinterpret_cast<uintptr_t>(header);
148
149 if (g_debug->config().options & FRONT_GUARD) {
150 uint8_t* guard = g_debug->GetFrontGuard(header);
151 memset(guard, g_debug->config().front_guard_value, g_debug->config().front_guard_bytes);
152 }
153
154 if (g_debug->config().options & REAR_GUARD) {
155 uint8_t* guard = g_debug->GetRearGuard(header);
156 memset(guard, g_debug->config().rear_guard_value, g_debug->config().rear_guard_bytes);
157 // If the rear guard is enabled, set the usable size to the exact size
158 // of the allocation.
159 header->usable_size = header->real_size();
160 }
161
162 bool backtrace_found = false;
163 if (g_debug->config().options & BACKTRACE) {
164 BacktraceHeader* back_header = g_debug->GetAllocBacktrace(header);
165 if (g_debug->backtrace->enabled()) {
Christopher Ferris7993b802016-01-28 18:35:05 -0800166 back_header->num_frames = backtrace_get(
167 &back_header->frames[0], g_debug->config().backtrace_frames);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800168 backtrace_found = back_header->num_frames > 0;
169 } else {
170 back_header->num_frames = 0;
171 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800172 }
173
174 if (g_debug->config().options & TRACK_ALLOCS) {
175 g_debug->track->Add(header, backtrace_found);
176 }
177
178 return g_debug->GetPointer(header);
179}
180
181bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child) {
182 if (malloc_zygote_child == nullptr) {
183 return false;
184 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800185
186 InitAtfork();
187
Christopher Ferris63860cb2015-11-16 17:30:32 -0800188 g_malloc_zygote_child = malloc_zygote_child;
189
190 g_dispatch = malloc_dispatch;
191
192 if (!DebugDisableInitialize()) {
193 return false;
194 }
195
196 DebugData* debug = new DebugData();
197 if (!debug->Initialize()) {
198 delete debug;
199 DebugDisableFinalize();
200 return false;
201 }
202 g_debug = debug;
203
204 // Always enable the backtrace code since we will use it in a number
205 // of different error cases.
206 backtrace_startup();
207
208 return true;
209}
210
211void debug_finalize() {
212 if (g_debug == nullptr) {
213 return;
214 }
215
216 if (g_debug->config().options & FREE_TRACK) {
217 g_debug->free_track->VerifyAll(*g_debug);
218 }
219
220 if (g_debug->config().options & LEAK_TRACK) {
221 g_debug->track->DisplayLeaks(*g_debug);
222 }
223
224 backtrace_shutdown();
225
226 DebugDisableSet(true);
227
228 delete g_debug;
229 g_debug = nullptr;
230
231 DebugDisableFinalize();
232}
233
234void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size,
235 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
236 ScopedDisableDebugCalls disable;
237
238 // Verify the arguments.
239 if (info == nullptr || overall_size == nullptr || info_size == NULL ||
240 total_memory == nullptr || backtrace_size == nullptr) {
241 error_log("get_malloc_leak_info: At least one invalid parameter.");
242 return;
243 }
244
245 *info = nullptr;
246 *overall_size = 0;
247 *info_size = 0;
248 *total_memory = 0;
249 *backtrace_size = 0;
250
251 if (!(g_debug->config().options & BACKTRACE)) {
252 error_log("get_malloc_leak_info: Allocations not being tracked, to enable "
253 "set the option 'backtrace'.");
254 return;
255 }
256
257 g_debug->track->GetInfo(*g_debug, info, overall_size, info_size, total_memory, backtrace_size);
258}
259
260void debug_free_malloc_leak_info(uint8_t* info) {
261 g_dispatch->free(info);
262}
263
264size_t debug_malloc_usable_size(void* pointer) {
265 if (DebugCallsDisabled() || !g_debug->need_header() || pointer == nullptr) {
266 return g_dispatch->malloc_usable_size(pointer);
267 }
268
269 Header* header = g_debug->GetHeader(pointer);
270 if (header->tag != DEBUG_TAG) {
271 LogTagError(header, pointer, "malloc_usable_size");
272 return 0;
273 }
274
275 return header->usable_size;
276}
277
278void* debug_malloc(size_t size) {
279 if (DebugCallsDisabled()) {
280 return g_dispatch->malloc(size);
281 }
282
283 size_t real_size = size + g_debug->extra_bytes();
284 if (real_size < size) {
285 // Overflow.
286 errno = ENOMEM;
287 return nullptr;
288 }
289
290 void* pointer;
291 if (g_debug->need_header()) {
292 if (size > Header::max_size()) {
293 errno = ENOMEM;
294 return nullptr;
295 }
296
Christopher Ferris72df6702016-02-11 15:51:31 -0800297 Header* header = reinterpret_cast<Header*>(
298 g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800299 if (header == nullptr) {
300 return nullptr;
301 }
302 pointer = InitHeader(header, header, size);
303 } else {
304 pointer = g_dispatch->malloc(real_size);
305 }
306
307 if (pointer != nullptr && g_debug->config().options & FILL_ON_ALLOC) {
308 size_t bytes = debug_malloc_usable_size(pointer);
309 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes;
310 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
311 memset(pointer, g_debug->config().fill_alloc_value, bytes);
312 }
313 return pointer;
314}
315
316void debug_free(void* pointer) {
317 if (DebugCallsDisabled() || pointer == nullptr) {
318 return g_dispatch->free(pointer);
319 }
320
321 void* free_pointer = pointer;
322 size_t bytes;
323 if (g_debug->need_header()) {
324 Header* header = g_debug->GetHeader(pointer);
325 if (header->tag != DEBUG_TAG) {
326 LogTagError(header, pointer, "free");
327 return;
328 }
329 free_pointer = header->orig_pointer;
330
331 if (g_debug->config().options & FRONT_GUARD) {
332 if (!g_debug->front_guard->Valid(*g_debug, header)) {
333 g_debug->front_guard->LogFailure(*g_debug, header);
334 }
335 }
336 if (g_debug->config().options & REAR_GUARD) {
337 if (!g_debug->rear_guard->Valid(*g_debug, header)) {
338 g_debug->rear_guard->LogFailure(*g_debug, header);
339 }
340 }
341
342 if (g_debug->config().options & TRACK_ALLOCS) {
343 bool backtrace_found = false;
344 if (g_debug->config().options & BACKTRACE) {
345 BacktraceHeader* back_header = g_debug->GetAllocBacktrace(header);
346 backtrace_found = back_header->num_frames > 0;
347 }
348 g_debug->track->Remove(header, backtrace_found);
349 }
350
351 if (g_debug->config().options & FREE_TRACK) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800352 g_debug->free_track->Add(*g_debug, header);
353
354 // Do not free this pointer just yet.
355 free_pointer = nullptr;
356 }
Christopher Ferris7993b802016-01-28 18:35:05 -0800357 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800358
359 bytes = header->usable_size;
360 } else {
361 bytes = g_dispatch->malloc_usable_size(pointer);
362 }
363
364 if (g_debug->config().options & FILL_ON_FREE) {
365 size_t fill_bytes = g_debug->config().fill_on_free_bytes;
366 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
367 memset(pointer, g_debug->config().fill_free_value, bytes);
368 }
369
370 g_dispatch->free(free_pointer);
371}
372
373void* debug_memalign(size_t alignment, size_t bytes) {
374 if (DebugCallsDisabled()) {
375 return g_dispatch->memalign(alignment, bytes);
376 }
377
378 void* pointer;
379 if (g_debug->need_header()) {
380 if (bytes > Header::max_size()) {
381 errno = ENOMEM;
382 return nullptr;
383 }
384
385 // Make the alignment a power of two.
386 if (!powerof2(alignment)) {
387 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
388 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800389 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800390 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800391 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
392 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800393 }
394
395 // We don't have any idea what the natural alignment of
396 // the underlying native allocator is, so we always need to
397 // over allocate.
398 size_t real_size = alignment + bytes + g_debug->extra_bytes();
399 if (real_size < bytes) {
400 // Overflow.
401 errno = ENOMEM;
402 return nullptr;
403 }
404
405 pointer = g_dispatch->malloc(real_size);
406 if (pointer == nullptr) {
407 return nullptr;
408 }
409
410 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
411 // Now align the pointer.
412 value += (-value % alignment);
413
414 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
415 pointer = InitHeader(header, pointer, bytes);
416 } else {
417 size_t real_size = bytes + g_debug->extra_bytes();
418 if (real_size < bytes) {
419 // Overflow.
420 errno = ENOMEM;
421 return nullptr;
422 }
423 pointer = g_dispatch->memalign(alignment, real_size);
424 }
425
426 if (pointer != nullptr && g_debug->config().options & FILL_ON_ALLOC) {
427 size_t bytes = debug_malloc_usable_size(pointer);
428 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes;
429 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
430 memset(pointer, g_debug->config().fill_alloc_value, bytes);
431 }
432 return pointer;
433}
434
435void* debug_realloc(void* pointer, size_t bytes) {
436 if (DebugCallsDisabled()) {
437 return g_dispatch->realloc(pointer, bytes);
438 }
439
440 if (pointer == nullptr) {
441 return debug_malloc(bytes);
442 }
443
444 if (bytes == 0) {
445 debug_free(pointer);
446 return nullptr;
447 }
448
449 size_t real_size = bytes;
450 if (g_debug->config().options & EXPAND_ALLOC) {
451 real_size += g_debug->config().expand_alloc_bytes;
452 if (real_size < bytes) {
453 // Overflow.
454 errno = ENOMEM;
455 return nullptr;
456 }
457 }
458
459 void* new_pointer;
460 size_t prev_size;
461 if (g_debug->need_header()) {
462 if (bytes > Header::max_size()) {
463 errno = ENOMEM;
464 return nullptr;
465 }
466
467 Header* header = g_debug->GetHeader(pointer);
468 if (header->tag != DEBUG_TAG) {
469 LogTagError(header, pointer, "realloc");
470 return nullptr;
471 }
472
473 // Same size, do nothing.
474 if (real_size == header->real_size()) {
475 return pointer;
476 }
477
478 // Allocation is shrinking.
479 if (real_size < header->usable_size) {
480 header->size = real_size;
481 if (*g_malloc_zygote_child) {
482 header->set_zygote();
483 }
484 if (g_debug->config().options & REAR_GUARD) {
485 // Don't bother allocating a smaller pointer in this case, simply
486 // change the header usable_size and reset the rear guard.
487 header->usable_size = header->real_size();
488 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value,
489 g_debug->config().rear_guard_bytes);
490 }
491 return pointer;
492 }
493
494 // Allocate the new size.
495 new_pointer = debug_malloc(bytes);
496 if (new_pointer == nullptr) {
497 errno = ENOMEM;
498 return nullptr;
499 }
500
501 prev_size = header->usable_size;
502 memcpy(new_pointer, pointer, prev_size);
503 debug_free(pointer);
504 } else {
505 prev_size = g_dispatch->malloc_usable_size(pointer);
506 new_pointer = g_dispatch->realloc(pointer, real_size);
507 if (new_pointer == nullptr) {
508 return nullptr;
509 }
510 }
511
512 if (g_debug->config().options & FILL_ON_ALLOC) {
513 size_t bytes = debug_malloc_usable_size(new_pointer);
514 if (bytes > g_debug->config().fill_on_alloc_bytes) {
515 bytes = g_debug->config().fill_on_alloc_bytes;
516 }
517 if (bytes > prev_size) {
518 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
519 g_debug->config().fill_alloc_value, bytes - prev_size);
520 }
521 }
522
523 return new_pointer;
524}
525
526void* debug_calloc(size_t nmemb, size_t bytes) {
527 if (DebugCallsDisabled()) {
528 return g_dispatch->calloc(nmemb, bytes);
529 }
530
531 size_t real_size = nmemb * bytes + g_debug->extra_bytes();
532 if (real_size < bytes || real_size < nmemb) {
533 // Overflow.
534 errno = ENOMEM;
535 return nullptr;
536 }
537
538 if (g_debug->need_header()) {
539 // The above check will guarantee the multiply will not overflow.
540 if (bytes * nmemb > Header::max_size()) {
541 errno = ENOMEM;
542 return nullptr;
543 }
544
545 // Need to guarantee the alignment of the header.
Christopher Ferris72df6702016-02-11 15:51:31 -0800546 Header* header = reinterpret_cast<Header*>(
547 g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800548 if (header == nullptr) {
549 return nullptr;
550 }
551 memset(header, 0, g_dispatch->malloc_usable_size(header));
552 return InitHeader(header, header, nmemb * bytes);
553 } else {
554 return g_dispatch->calloc(1, real_size);
555 }
556}
557
558struct mallinfo debug_mallinfo() {
559 return g_dispatch->mallinfo();
560}
561
562int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
563 if (DebugCallsDisabled()) {
564 return g_dispatch->posix_memalign(memptr, alignment, size);
565 }
566
567 if (!powerof2(alignment)) {
568 return EINVAL;
569 }
570 int saved_errno = errno;
571 *memptr = debug_memalign(alignment, size);
572 errno = saved_errno;
573 return (*memptr != nullptr) ? 0 : ENOMEM;
574}
575
Colin Cross869691c2016-01-29 12:48:18 -0800576int debug_iterate(uintptr_t base, size_t size,
577 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
578 // Can't allocate, malloc is disabled
579 // Manual capture of the arguments to pass to the lambda below as void* arg
580 struct iterate_ctx {
581 decltype(callback) callback;
582 decltype(arg) arg;
583 } ctx = { callback, arg };
584
585 return g_dispatch->iterate(base, size,
586 [](uintptr_t base, size_t size, void* arg) {
587 const iterate_ctx* ctx = reinterpret_cast<iterate_ctx*>(arg);
588 const void* pointer = reinterpret_cast<void*>(base);
589 if (g_debug->need_header()) {
590 const Header* header = reinterpret_cast<const Header*>(pointer);
591 if (g_debug->config().options & TRACK_ALLOCS) {
592 if (g_debug->track->Contains(header)) {
593 // Return just the body of the allocation if we're sure the header exists
594 ctx->callback(reinterpret_cast<uintptr_t>(g_debug->GetPointer(header)),
595 header->real_size(), ctx->arg);
596 return;
597 }
598 }
599 }
600 // Fall back to returning the whole allocation
601 ctx->callback(base, size, ctx->arg);
602 }, &ctx);
603}
604
605void debug_malloc_disable() {
606 g_dispatch->malloc_disable();
607 if (g_debug->track) {
608 g_debug->track->PrepareFork();
609 }
610}
611
612void debug_malloc_enable() {
613 if (g_debug->track) {
614 g_debug->track->PostForkParent();
615 }
616 g_dispatch->malloc_enable();
617}
618
Christopher Ferris63860cb2015-11-16 17:30:32 -0800619#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
620void* debug_pvalloc(size_t bytes) {
621 if (DebugCallsDisabled()) {
622 return g_dispatch->pvalloc(bytes);
623 }
624
625 size_t pagesize = getpagesize();
626 size_t size = BIONIC_ALIGN(bytes, pagesize);
627 if (size < bytes) {
628 // Overflow
629 errno = ENOMEM;
630 return nullptr;
631 }
632 return debug_memalign(pagesize, size);
633}
634
635void* debug_valloc(size_t size) {
636 if (DebugCallsDisabled()) {
637 return g_dispatch->valloc(size);
638 }
639 return debug_memalign(getpagesize(), size);
640}
641#endif