blob: dcc6048f75f54aae5ebc00b88869dbff849b4e55 [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);
79
80#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
81void* debug_pvalloc(size_t bytes);
82void* debug_valloc(size_t size);
83#endif
84
85__END_DECLS
86// ------------------------------------------------------------------------
87
Colin Cross7a28a3c2016-02-07 22:51:15 -080088static void InitAtfork() {
89 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
90 pthread_once(&atfork_init, [](){
91 pthread_atfork(
92 [](){
93 if (g_debug != nullptr) {
94 g_debug->PrepareFork();
95 }
96 },
97 [](){
98 if (g_debug != nullptr) {
99 g_debug->PostForkParent();
100 }
101 },
102 [](){
103 if (g_debug != nullptr) {
104 g_debug->PostForkChild();
105 }
106 }
107 );
108 });
109}
Christopher Ferris63860cb2015-11-16 17:30:32 -0800110static void LogTagError(const Header* header, const void* pointer, const char* name) {
111 ScopedDisableDebugCalls disable;
112
113 error_log(LOG_DIVIDER);
Christopher Ferris7993b802016-01-28 18:35:05 -0800114 if (header->tag == DEBUG_FREE_TAG) {
115 error_log("+++ ALLOCATION %p USED AFTER FREE (%s)", pointer, name);
116 if (g_debug->config().options & FREE_TRACK) {
117 g_debug->free_track->LogBacktrace(header);
118 }
119 } else {
120 error_log("+++ ALLOCATION %p HAS INVALID TAG %" PRIx32 " (%s)", pointer, header->tag, name);
121 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800122 error_log("Backtrace at time of failure:");
123 std::vector<uintptr_t> frames(64);
124 size_t frame_num = backtrace_get(frames.data(), frames.size());
125 frames.resize(frame_num);
126 backtrace_log(frames.data(), frames.size());
127 error_log(LOG_DIVIDER);
128}
129
130static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
131 header->tag = DEBUG_TAG;
132 header->orig_pointer = orig_pointer;
133 header->size = size;
134 if (*g_malloc_zygote_child) {
135 header->set_zygote();
136 }
137 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
138 if (header->usable_size == 0) {
139 g_dispatch->free(orig_pointer);
140 return nullptr;
141 }
142 header->usable_size -= g_debug->pointer_offset() +
143 reinterpret_cast<uintptr_t>(orig_pointer) - reinterpret_cast<uintptr_t>(header);
144
145 if (g_debug->config().options & FRONT_GUARD) {
146 uint8_t* guard = g_debug->GetFrontGuard(header);
147 memset(guard, g_debug->config().front_guard_value, g_debug->config().front_guard_bytes);
148 }
149
150 if (g_debug->config().options & REAR_GUARD) {
151 uint8_t* guard = g_debug->GetRearGuard(header);
152 memset(guard, g_debug->config().rear_guard_value, g_debug->config().rear_guard_bytes);
153 // If the rear guard is enabled, set the usable size to the exact size
154 // of the allocation.
155 header->usable_size = header->real_size();
156 }
157
158 bool backtrace_found = false;
159 if (g_debug->config().options & BACKTRACE) {
160 BacktraceHeader* back_header = g_debug->GetAllocBacktrace(header);
161 if (g_debug->backtrace->enabled()) {
Christopher Ferris7993b802016-01-28 18:35:05 -0800162 back_header->num_frames = backtrace_get(
163 &back_header->frames[0], g_debug->config().backtrace_frames);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800164 backtrace_found = back_header->num_frames > 0;
165 } else {
166 back_header->num_frames = 0;
167 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800168 }
169
170 if (g_debug->config().options & TRACK_ALLOCS) {
171 g_debug->track->Add(header, backtrace_found);
172 }
173
174 return g_debug->GetPointer(header);
175}
176
177bool debug_initialize(const MallocDispatch* malloc_dispatch, int* malloc_zygote_child) {
178 if (malloc_zygote_child == nullptr) {
179 return false;
180 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800181
182 InitAtfork();
183
Christopher Ferris63860cb2015-11-16 17:30:32 -0800184 g_malloc_zygote_child = malloc_zygote_child;
185
186 g_dispatch = malloc_dispatch;
187
188 if (!DebugDisableInitialize()) {
189 return false;
190 }
191
192 DebugData* debug = new DebugData();
193 if (!debug->Initialize()) {
194 delete debug;
195 DebugDisableFinalize();
196 return false;
197 }
198 g_debug = debug;
199
200 // Always enable the backtrace code since we will use it in a number
201 // of different error cases.
202 backtrace_startup();
203
204 return true;
205}
206
207void debug_finalize() {
208 if (g_debug == nullptr) {
209 return;
210 }
211
212 if (g_debug->config().options & FREE_TRACK) {
213 g_debug->free_track->VerifyAll(*g_debug);
214 }
215
216 if (g_debug->config().options & LEAK_TRACK) {
217 g_debug->track->DisplayLeaks(*g_debug);
218 }
219
220 backtrace_shutdown();
221
222 DebugDisableSet(true);
223
224 delete g_debug;
225 g_debug = nullptr;
226
227 DebugDisableFinalize();
228}
229
230void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size,
231 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
232 ScopedDisableDebugCalls disable;
233
234 // Verify the arguments.
235 if (info == nullptr || overall_size == nullptr || info_size == NULL ||
236 total_memory == nullptr || backtrace_size == nullptr) {
237 error_log("get_malloc_leak_info: At least one invalid parameter.");
238 return;
239 }
240
241 *info = nullptr;
242 *overall_size = 0;
243 *info_size = 0;
244 *total_memory = 0;
245 *backtrace_size = 0;
246
247 if (!(g_debug->config().options & BACKTRACE)) {
248 error_log("get_malloc_leak_info: Allocations not being tracked, to enable "
249 "set the option 'backtrace'.");
250 return;
251 }
252
253 g_debug->track->GetInfo(*g_debug, info, overall_size, info_size, total_memory, backtrace_size);
254}
255
256void debug_free_malloc_leak_info(uint8_t* info) {
257 g_dispatch->free(info);
258}
259
260size_t debug_malloc_usable_size(void* pointer) {
261 if (DebugCallsDisabled() || !g_debug->need_header() || pointer == nullptr) {
262 return g_dispatch->malloc_usable_size(pointer);
263 }
264
265 Header* header = g_debug->GetHeader(pointer);
266 if (header->tag != DEBUG_TAG) {
267 LogTagError(header, pointer, "malloc_usable_size");
268 return 0;
269 }
270
271 return header->usable_size;
272}
273
274void* debug_malloc(size_t size) {
275 if (DebugCallsDisabled()) {
276 return g_dispatch->malloc(size);
277 }
278
279 size_t real_size = size + g_debug->extra_bytes();
280 if (real_size < size) {
281 // Overflow.
282 errno = ENOMEM;
283 return nullptr;
284 }
285
286 void* pointer;
287 if (g_debug->need_header()) {
288 if (size > Header::max_size()) {
289 errno = ENOMEM;
290 return nullptr;
291 }
292
Christopher Ferris72df6702016-02-11 15:51:31 -0800293 Header* header = reinterpret_cast<Header*>(
294 g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800295 if (header == nullptr) {
296 return nullptr;
297 }
298 pointer = InitHeader(header, header, size);
299 } else {
300 pointer = g_dispatch->malloc(real_size);
301 }
302
303 if (pointer != nullptr && g_debug->config().options & FILL_ON_ALLOC) {
304 size_t bytes = debug_malloc_usable_size(pointer);
305 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes;
306 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
307 memset(pointer, g_debug->config().fill_alloc_value, bytes);
308 }
309 return pointer;
310}
311
312void debug_free(void* pointer) {
313 if (DebugCallsDisabled() || pointer == nullptr) {
314 return g_dispatch->free(pointer);
315 }
316
317 void* free_pointer = pointer;
318 size_t bytes;
319 if (g_debug->need_header()) {
320 Header* header = g_debug->GetHeader(pointer);
321 if (header->tag != DEBUG_TAG) {
322 LogTagError(header, pointer, "free");
323 return;
324 }
325 free_pointer = header->orig_pointer;
326
327 if (g_debug->config().options & FRONT_GUARD) {
328 if (!g_debug->front_guard->Valid(*g_debug, header)) {
329 g_debug->front_guard->LogFailure(*g_debug, header);
330 }
331 }
332 if (g_debug->config().options & REAR_GUARD) {
333 if (!g_debug->rear_guard->Valid(*g_debug, header)) {
334 g_debug->rear_guard->LogFailure(*g_debug, header);
335 }
336 }
337
338 if (g_debug->config().options & TRACK_ALLOCS) {
339 bool backtrace_found = false;
340 if (g_debug->config().options & BACKTRACE) {
341 BacktraceHeader* back_header = g_debug->GetAllocBacktrace(header);
342 backtrace_found = back_header->num_frames > 0;
343 }
344 g_debug->track->Remove(header, backtrace_found);
345 }
346
347 if (g_debug->config().options & FREE_TRACK) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800348 g_debug->free_track->Add(*g_debug, header);
349
350 // Do not free this pointer just yet.
351 free_pointer = nullptr;
352 }
Christopher Ferris7993b802016-01-28 18:35:05 -0800353 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800354
355 bytes = header->usable_size;
356 } else {
357 bytes = g_dispatch->malloc_usable_size(pointer);
358 }
359
360 if (g_debug->config().options & FILL_ON_FREE) {
361 size_t fill_bytes = g_debug->config().fill_on_free_bytes;
362 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
363 memset(pointer, g_debug->config().fill_free_value, bytes);
364 }
365
366 g_dispatch->free(free_pointer);
367}
368
369void* debug_memalign(size_t alignment, size_t bytes) {
370 if (DebugCallsDisabled()) {
371 return g_dispatch->memalign(alignment, bytes);
372 }
373
374 void* pointer;
375 if (g_debug->need_header()) {
376 if (bytes > Header::max_size()) {
377 errno = ENOMEM;
378 return nullptr;
379 }
380
381 // Make the alignment a power of two.
382 if (!powerof2(alignment)) {
383 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
384 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800385 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800386 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800387 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
388 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800389 }
390
391 // We don't have any idea what the natural alignment of
392 // the underlying native allocator is, so we always need to
393 // over allocate.
394 size_t real_size = alignment + bytes + g_debug->extra_bytes();
395 if (real_size < bytes) {
396 // Overflow.
397 errno = ENOMEM;
398 return nullptr;
399 }
400
401 pointer = g_dispatch->malloc(real_size);
402 if (pointer == nullptr) {
403 return nullptr;
404 }
405
406 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
407 // Now align the pointer.
408 value += (-value % alignment);
409
410 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
411 pointer = InitHeader(header, pointer, bytes);
412 } else {
413 size_t real_size = bytes + g_debug->extra_bytes();
414 if (real_size < bytes) {
415 // Overflow.
416 errno = ENOMEM;
417 return nullptr;
418 }
419 pointer = g_dispatch->memalign(alignment, real_size);
420 }
421
422 if (pointer != nullptr && g_debug->config().options & FILL_ON_ALLOC) {
423 size_t bytes = debug_malloc_usable_size(pointer);
424 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes;
425 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
426 memset(pointer, g_debug->config().fill_alloc_value, bytes);
427 }
428 return pointer;
429}
430
431void* debug_realloc(void* pointer, size_t bytes) {
432 if (DebugCallsDisabled()) {
433 return g_dispatch->realloc(pointer, bytes);
434 }
435
436 if (pointer == nullptr) {
437 return debug_malloc(bytes);
438 }
439
440 if (bytes == 0) {
441 debug_free(pointer);
442 return nullptr;
443 }
444
445 size_t real_size = bytes;
446 if (g_debug->config().options & EXPAND_ALLOC) {
447 real_size += g_debug->config().expand_alloc_bytes;
448 if (real_size < bytes) {
449 // Overflow.
450 errno = ENOMEM;
451 return nullptr;
452 }
453 }
454
455 void* new_pointer;
456 size_t prev_size;
457 if (g_debug->need_header()) {
458 if (bytes > Header::max_size()) {
459 errno = ENOMEM;
460 return nullptr;
461 }
462
463 Header* header = g_debug->GetHeader(pointer);
464 if (header->tag != DEBUG_TAG) {
465 LogTagError(header, pointer, "realloc");
466 return nullptr;
467 }
468
469 // Same size, do nothing.
470 if (real_size == header->real_size()) {
471 return pointer;
472 }
473
474 // Allocation is shrinking.
475 if (real_size < header->usable_size) {
476 header->size = real_size;
477 if (*g_malloc_zygote_child) {
478 header->set_zygote();
479 }
480 if (g_debug->config().options & REAR_GUARD) {
481 // Don't bother allocating a smaller pointer in this case, simply
482 // change the header usable_size and reset the rear guard.
483 header->usable_size = header->real_size();
484 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value,
485 g_debug->config().rear_guard_bytes);
486 }
487 return pointer;
488 }
489
490 // Allocate the new size.
491 new_pointer = debug_malloc(bytes);
492 if (new_pointer == nullptr) {
493 errno = ENOMEM;
494 return nullptr;
495 }
496
497 prev_size = header->usable_size;
498 memcpy(new_pointer, pointer, prev_size);
499 debug_free(pointer);
500 } else {
501 prev_size = g_dispatch->malloc_usable_size(pointer);
502 new_pointer = g_dispatch->realloc(pointer, real_size);
503 if (new_pointer == nullptr) {
504 return nullptr;
505 }
506 }
507
508 if (g_debug->config().options & FILL_ON_ALLOC) {
509 size_t bytes = debug_malloc_usable_size(new_pointer);
510 if (bytes > g_debug->config().fill_on_alloc_bytes) {
511 bytes = g_debug->config().fill_on_alloc_bytes;
512 }
513 if (bytes > prev_size) {
514 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
515 g_debug->config().fill_alloc_value, bytes - prev_size);
516 }
517 }
518
519 return new_pointer;
520}
521
522void* debug_calloc(size_t nmemb, size_t bytes) {
523 if (DebugCallsDisabled()) {
524 return g_dispatch->calloc(nmemb, bytes);
525 }
526
527 size_t real_size = nmemb * bytes + g_debug->extra_bytes();
528 if (real_size < bytes || real_size < nmemb) {
529 // Overflow.
530 errno = ENOMEM;
531 return nullptr;
532 }
533
534 if (g_debug->need_header()) {
535 // The above check will guarantee the multiply will not overflow.
536 if (bytes * nmemb > Header::max_size()) {
537 errno = ENOMEM;
538 return nullptr;
539 }
540
541 // Need to guarantee the alignment of the header.
Christopher Ferris72df6702016-02-11 15:51:31 -0800542 Header* header = reinterpret_cast<Header*>(
543 g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800544 if (header == nullptr) {
545 return nullptr;
546 }
547 memset(header, 0, g_dispatch->malloc_usable_size(header));
548 return InitHeader(header, header, nmemb * bytes);
549 } else {
550 return g_dispatch->calloc(1, real_size);
551 }
552}
553
554struct mallinfo debug_mallinfo() {
555 return g_dispatch->mallinfo();
556}
557
558int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
559 if (DebugCallsDisabled()) {
560 return g_dispatch->posix_memalign(memptr, alignment, size);
561 }
562
563 if (!powerof2(alignment)) {
564 return EINVAL;
565 }
566 int saved_errno = errno;
567 *memptr = debug_memalign(alignment, size);
568 errno = saved_errno;
569 return (*memptr != nullptr) ? 0 : ENOMEM;
570}
571
572#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
573void* debug_pvalloc(size_t bytes) {
574 if (DebugCallsDisabled()) {
575 return g_dispatch->pvalloc(bytes);
576 }
577
578 size_t pagesize = getpagesize();
579 size_t size = BIONIC_ALIGN(bytes, pagesize);
580 if (size < bytes) {
581 // Overflow
582 errno = ENOMEM;
583 return nullptr;
584 }
585 return debug_memalign(pagesize, size);
586}
587
588void* debug_valloc(size_t size) {
589 if (DebugCallsDisabled()) {
590 return g_dispatch->valloc(size);
591 }
592 return debug_memalign(getpagesize(), size);
593}
594#endif