blob: ce937fd81715264994ed7cfdb199871862f0d10b [file] [log] [blame]
Colin Cross7add50d2016-01-14 15:35:40 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <inttypes.h>
Colin Crossa9939e92017-06-21 13:13:00 -070018#include <string.h>
Colin Cross7add50d2016-01-14 15:35:40 -080019
20#include <functional>
21#include <iomanip>
22#include <mutex>
Colin Cross7add50d2016-01-14 15:35:40 -080023#include <sstream>
Colin Crossa83881e2017-06-22 10:50:05 -070024#include <string>
Colin Cross7a22e812016-03-04 16:36:12 -080025#include <unordered_map>
Colin Cross7add50d2016-01-14 15:35:40 -080026
Colin Cross7add50d2016-01-14 15:35:40 -080027#include <android-base/macros.h>
Colin Crossa83881e2017-06-22 10:50:05 -070028#include <backtrace.h>
Colin Cross7add50d2016-01-14 15:35:40 -080029
30#include "Allocator.h"
Colin Crossf572b912017-06-20 18:07:29 -070031#include "Binder.h"
Colin Cross7add50d2016-01-14 15:35:40 -080032#include "HeapWalker.h"
Colin Cross7a22e812016-03-04 16:36:12 -080033#include "Leak.h"
Colin Cross8e8f34c2016-03-02 17:53:39 -080034#include "LeakFolding.h"
Colin Cross7add50d2016-01-14 15:35:40 -080035#include "LeakPipe.h"
36#include "ProcessMappings.h"
37#include "PtracerThread.h"
38#include "ScopedDisableMalloc.h"
39#include "Semaphore.h"
40#include "ThreadCapture.h"
41
Colin Cross7add50d2016-01-14 15:35:40 -080042#include "bionic.h"
43#include "log.h"
Colin Crossa83881e2017-06-22 10:50:05 -070044#include "memunreachable/memunreachable.h"
Colin Cross7add50d2016-01-14 15:35:40 -080045
Colin Cross7add50d2016-01-14 15:35:40 -080046using namespace std::chrono_literals;
47
Colin Crossa9939e92017-06-21 13:13:00 -070048namespace android {
49
50const size_t Leak::contents_length;
51
Colin Cross7add50d2016-01-14 15:35:40 -080052class MemUnreachable {
53 public:
Colin Crossa83881e2017-06-22 10:50:05 -070054 MemUnreachable(pid_t pid, Allocator<void> allocator)
55 : pid_(pid), allocator_(allocator), heap_walker_(allocator_) {}
Colin Cross7add50d2016-01-14 15:35:40 -080056 bool CollectAllocations(const allocator::vector<ThreadInfo>& threads,
Colin Crossf572b912017-06-20 18:07:29 -070057 const allocator::vector<Mapping>& mappings,
58 const allocator::vector<uintptr_t>& refs);
Colin Crossa83881e2017-06-22 10:50:05 -070059 bool GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit, size_t* num_leaks,
60 size_t* leak_bytes);
Colin Cross7add50d2016-01-14 15:35:40 -080061 size_t Allocations() { return heap_walker_.Allocations(); }
62 size_t AllocationBytes() { return heap_walker_.AllocationBytes(); }
Colin Crossa83881e2017-06-22 10:50:05 -070063
Colin Cross7add50d2016-01-14 15:35:40 -080064 private:
65 bool ClassifyMappings(const allocator::vector<Mapping>& mappings,
Colin Crossa83881e2017-06-22 10:50:05 -070066 allocator::vector<Mapping>& heap_mappings,
67 allocator::vector<Mapping>& anon_mappings,
68 allocator::vector<Mapping>& globals_mappings,
69 allocator::vector<Mapping>& stack_mappings);
Colin Cross7add50d2016-01-14 15:35:40 -080070 DISALLOW_COPY_AND_ASSIGN(MemUnreachable);
71 pid_t pid_;
72 Allocator<void> allocator_;
73 HeapWalker heap_walker_;
74};
75
76static void HeapIterate(const Mapping& heap_mapping,
Colin Crossa83881e2017-06-22 10:50:05 -070077 const std::function<void(uintptr_t, size_t)>& func) {
Colin Cross7add50d2016-01-14 15:35:40 -080078 malloc_iterate(heap_mapping.begin, heap_mapping.end - heap_mapping.begin,
Colin Crossa83881e2017-06-22 10:50:05 -070079 [](uintptr_t base, size_t size, void* arg) {
80 auto f = reinterpret_cast<const std::function<void(uintptr_t, size_t)>*>(arg);
81 (*f)(base, size);
82 },
83 const_cast<void*>(reinterpret_cast<const void*>(&func)));
Colin Cross7add50d2016-01-14 15:35:40 -080084}
85
86bool MemUnreachable::CollectAllocations(const allocator::vector<ThreadInfo>& threads,
Colin Crossf572b912017-06-20 18:07:29 -070087 const allocator::vector<Mapping>& mappings,
88 const allocator::vector<uintptr_t>& refs) {
Christopher Ferris47dea712017-05-03 17:34:29 -070089 MEM_ALOGI("searching process %d for allocations", pid_);
Colin Cross3ca19762018-11-28 17:01:59 -080090
91 for (auto it = mappings.begin(); it != mappings.end(); it++) {
92 heap_walker_.Mapping(it->begin, it->end);
93 }
94
Colin Cross7add50d2016-01-14 15:35:40 -080095 allocator::vector<Mapping> heap_mappings{mappings};
96 allocator::vector<Mapping> anon_mappings{mappings};
97 allocator::vector<Mapping> globals_mappings{mappings};
98 allocator::vector<Mapping> stack_mappings{mappings};
Christopher Ferris47dea712017-05-03 17:34:29 -070099 if (!ClassifyMappings(mappings, heap_mappings, anon_mappings, globals_mappings, stack_mappings)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800100 return false;
101 }
102
103 for (auto it = heap_mappings.begin(); it != heap_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700104 MEM_ALOGV("Heap mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
105 HeapIterate(*it,
106 [&](uintptr_t base, size_t size) { heap_walker_.Allocation(base, base + size); });
Colin Cross7add50d2016-01-14 15:35:40 -0800107 }
108
109 for (auto it = anon_mappings.begin(); it != anon_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700110 MEM_ALOGV("Anon mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800111 heap_walker_.Allocation(it->begin, it->end);
112 }
113
114 for (auto it = globals_mappings.begin(); it != globals_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700115 MEM_ALOGV("Globals mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800116 heap_walker_.Root(it->begin, it->end);
117 }
118
119 for (auto thread_it = threads.begin(); thread_it != threads.end(); thread_it++) {
120 for (auto it = stack_mappings.begin(); it != stack_mappings.end(); it++) {
121 if (thread_it->stack.first >= it->begin && thread_it->stack.first <= it->end) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700122 MEM_ALOGV("Stack %" PRIxPTR "-%" PRIxPTR " %s", thread_it->stack.first, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800123 heap_walker_.Root(thread_it->stack.first, it->end);
124 }
125 }
126 heap_walker_.Root(thread_it->regs);
127 }
128
Colin Crossf572b912017-06-20 18:07:29 -0700129 heap_walker_.Root(refs);
130
Christopher Ferris47dea712017-05-03 17:34:29 -0700131 MEM_ALOGI("searching done");
Colin Cross7add50d2016-01-14 15:35:40 -0800132
133 return true;
134}
135
Colin Crossa83881e2017-06-22 10:50:05 -0700136bool MemUnreachable::GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit,
137 size_t* num_leaks, size_t* leak_bytes) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700138 MEM_ALOGI("sweeping process %d for unreachable memory", pid_);
Colin Cross7add50d2016-01-14 15:35:40 -0800139 leaks.clear();
140
Colin Cross8e8f34c2016-03-02 17:53:39 -0800141 if (!heap_walker_.DetectLeaks()) {
142 return false;
143 }
144
Colin Cross7a22e812016-03-04 16:36:12 -0800145 allocator::vector<Range> leaked1{allocator_};
146 heap_walker_.Leaked(leaked1, 0, num_leaks, leak_bytes);
147
Christopher Ferris47dea712017-05-03 17:34:29 -0700148 MEM_ALOGI("sweeping done");
Colin Cross7a22e812016-03-04 16:36:12 -0800149
Christopher Ferris47dea712017-05-03 17:34:29 -0700150 MEM_ALOGI("folding related leaks");
Colin Cross7a22e812016-03-04 16:36:12 -0800151
Colin Cross8e8f34c2016-03-02 17:53:39 -0800152 LeakFolding folding(allocator_, heap_walker_);
153 if (!folding.FoldLeaks()) {
154 return false;
155 }
156
157 allocator::vector<LeakFolding::Leak> leaked{allocator_};
158
Colin Cross7a22e812016-03-04 16:36:12 -0800159 if (!folding.Leaked(leaked, num_leaks, leak_bytes)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800160 return false;
161 }
162
Colin Cross7a22e812016-03-04 16:36:12 -0800163 allocator::unordered_map<Leak::Backtrace, Leak*> backtrace_map{allocator_};
164
165 // Prevent reallocations of backing memory so we can store pointers into it
166 // in backtrace_map.
167 leaks.reserve(leaked.size());
168
Colin Crossa83881e2017-06-22 10:50:05 -0700169 for (auto& it : leaked) {
Colin Cross7a22e812016-03-04 16:36:12 -0800170 leaks.emplace_back();
171 Leak* leak = &leaks.back();
172
Colin Crossa83881e2017-06-22 10:50:05 -0700173 ssize_t num_backtrace_frames = malloc_backtrace(
174 reinterpret_cast<void*>(it.range.begin), leak->backtrace.frames, leak->backtrace.max_frames);
Colin Cross7add50d2016-01-14 15:35:40 -0800175 if (num_backtrace_frames > 0) {
Colin Cross7a22e812016-03-04 16:36:12 -0800176 leak->backtrace.num_frames = num_backtrace_frames;
177
178 auto inserted = backtrace_map.emplace(leak->backtrace, leak);
179 if (!inserted.second) {
180 // Leak with same backtrace already exists, drop this one and
181 // increment similar counts on the existing one.
182 leaks.pop_back();
183 Leak* similar_leak = inserted.first->second;
184 similar_leak->similar_count++;
185 similar_leak->similar_size += it.range.size();
186 similar_leak->similar_referenced_count += it.referenced_count;
187 similar_leak->similar_referenced_size += it.referenced_size;
188 similar_leak->total_size += it.range.size();
189 similar_leak->total_size += it.referenced_size;
190 continue;
191 }
Colin Cross7add50d2016-01-14 15:35:40 -0800192 }
Colin Cross7a22e812016-03-04 16:36:12 -0800193
194 leak->begin = it.range.begin;
195 leak->size = it.range.size();
196 leak->referenced_count = it.referenced_count;
197 leak->referenced_size = it.referenced_size;
198 leak->total_size = leak->size + leak->referenced_size;
199 memcpy(leak->contents, reinterpret_cast<void*>(it.range.begin),
Colin Crossa83881e2017-06-22 10:50:05 -0700200 std::min(leak->size, Leak::contents_length));
Colin Cross7add50d2016-01-14 15:35:40 -0800201 }
202
Christopher Ferris47dea712017-05-03 17:34:29 -0700203 MEM_ALOGI("folding done");
Colin Cross7a22e812016-03-04 16:36:12 -0800204
Colin Crossa83881e2017-06-22 10:50:05 -0700205 std::sort(leaks.begin(), leaks.end(),
206 [](const Leak& a, const Leak& b) { return a.total_size > b.total_size; });
Colin Cross7a22e812016-03-04 16:36:12 -0800207
208 if (leaks.size() > limit) {
209 leaks.resize(limit);
210 }
Colin Cross7add50d2016-01-14 15:35:40 -0800211
212 return true;
213}
214
215static bool has_prefix(const allocator::string& s, const char* prefix) {
216 int ret = s.compare(0, strlen(prefix), prefix);
217 return ret == 0;
218}
219
Evgenii Stepanov3e1c6042019-03-19 17:17:47 -0700220static bool is_sanitizer_mapping(const allocator::string& s) {
221 return s == "[anon:low shadow]" || s == "[anon:high shadow]" || has_prefix(s, "[anon:hwasan");
222}
223
Colin Cross7add50d2016-01-14 15:35:40 -0800224bool MemUnreachable::ClassifyMappings(const allocator::vector<Mapping>& mappings,
Colin Crossa83881e2017-06-22 10:50:05 -0700225 allocator::vector<Mapping>& heap_mappings,
226 allocator::vector<Mapping>& anon_mappings,
227 allocator::vector<Mapping>& globals_mappings,
228 allocator::vector<Mapping>& stack_mappings) {
Colin Cross7add50d2016-01-14 15:35:40 -0800229 heap_mappings.clear();
230 anon_mappings.clear();
231 globals_mappings.clear();
232 stack_mappings.clear();
233
234 allocator::string current_lib{allocator_};
235
236 for (auto it = mappings.begin(); it != mappings.end(); it++) {
237 if (it->execute) {
238 current_lib = it->name;
239 continue;
240 }
241
242 if (!it->read) {
243 continue;
244 }
245
246 const allocator::string mapping_name{it->name, allocator_};
247 if (mapping_name == "[anon:.bss]") {
248 // named .bss section
249 globals_mappings.emplace_back(*it);
250 } else if (mapping_name == current_lib) {
251 // .rodata or .data section
252 globals_mappings.emplace_back(*it);
253 } else if (mapping_name == "[anon:libc_malloc]") {
254 // named malloc mapping
255 heap_mappings.emplace_back(*it);
Joel Fernandesed59ff42018-08-24 11:57:57 -0700256 } else if (has_prefix(mapping_name, "[anon:dalvik-")) {
Colin Cross7add50d2016-01-14 15:35:40 -0800257 // named dalvik heap mapping
258 globals_mappings.emplace_back(*it);
259 } else if (has_prefix(mapping_name, "[stack")) {
260 // named stack mapping
261 stack_mappings.emplace_back(*it);
262 } else if (mapping_name.size() == 0) {
263 globals_mappings.emplace_back(*it);
Colin Crossa83881e2017-06-22 10:50:05 -0700264 } else if (has_prefix(mapping_name, "[anon:") &&
Evgenii Stepanov3e1c6042019-03-19 17:17:47 -0700265 mapping_name != "[anon:leak_detector_malloc]" &&
266 !is_sanitizer_mapping(mapping_name)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800267 // TODO(ccross): it would be nice to treat named anonymous mappings as
268 // possible leaks, but naming something in a .bss or .data section makes
269 // it impossible to distinguish them from mmaped and then named mappings.
270 globals_mappings.emplace_back(*it);
271 }
272 }
273
274 return true;
275}
276
Colin Crossa83881e2017-06-22 10:50:05 -0700277template <typename T>
Colin Cross7a22e812016-03-04 16:36:12 -0800278static inline const char* plural(T val) {
279 return (val == 1) ? "" : "s";
280}
281
Colin Cross7add50d2016-01-14 15:35:40 -0800282bool GetUnreachableMemory(UnreachableMemoryInfo& info, size_t limit) {
Colin Cross025ed8a2019-05-20 12:55:33 -0700283 if (info.version > 0) {
284 MEM_ALOGE("unsupported UnreachableMemoryInfo.version %zu in GetUnreachableMemory",
285 info.version);
286 return false;
287 }
288
Colin Cross7add50d2016-01-14 15:35:40 -0800289 int parent_pid = getpid();
290 int parent_tid = gettid();
291
292 Heap heap;
293
294 Semaphore continue_parent_sem;
295 LeakPipe pipe;
296
297 PtracerThread thread{[&]() -> int {
298 /////////////////////////////////////////////
299 // Collection thread
300 /////////////////////////////////////////////
Christopher Ferris47dea712017-05-03 17:34:29 -0700301 MEM_ALOGI("collecting thread info for process %d...", parent_pid);
Colin Cross7add50d2016-01-14 15:35:40 -0800302
303 ThreadCapture thread_capture(parent_pid, heap);
304 allocator::vector<ThreadInfo> thread_info(heap);
305 allocator::vector<Mapping> mappings(heap);
Colin Crossf572b912017-06-20 18:07:29 -0700306 allocator::vector<uintptr_t> refs(heap);
Colin Cross7add50d2016-01-14 15:35:40 -0800307
308 // ptrace all the threads
309 if (!thread_capture.CaptureThreads()) {
Colin Crossde42af02016-01-14 15:35:40 -0800310 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800311 return 1;
312 }
313
314 // collect register contents and stacks
315 if (!thread_capture.CapturedThreadInfo(thread_info)) {
Colin Crossde42af02016-01-14 15:35:40 -0800316 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800317 return 1;
318 }
319
320 // snapshot /proc/pid/maps
321 if (!ProcessMappings(parent_pid, mappings)) {
Colin Crossde42af02016-01-14 15:35:40 -0800322 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800323 return 1;
324 }
325
Colin Crossf572b912017-06-20 18:07:29 -0700326 if (!BinderReferences(refs)) {
327 continue_parent_sem.Post();
328 return 1;
329 }
330
Colin Cross7add50d2016-01-14 15:35:40 -0800331 // malloc must be enabled to call fork, at_fork handlers take the same
332 // locks as ScopedDisableMalloc. All threads are paused in ptrace, so
333 // memory state is still consistent. Unfreeze the original thread so it
334 // can drop the malloc locks, it will block until the collection thread
335 // exits.
336 thread_capture.ReleaseThread(parent_tid);
337 continue_parent_sem.Post();
338
339 // fork a process to do the heap walking
340 int ret = fork();
341 if (ret < 0) {
342 return 1;
343 } else if (ret == 0) {
344 /////////////////////////////////////////////
345 // Heap walker process
346 /////////////////////////////////////////////
347 // Examine memory state in the child using the data collected above and
348 // the CoW snapshot of the process memory contents.
349
350 if (!pipe.OpenSender()) {
351 _exit(1);
352 }
353
354 MemUnreachable unreachable{parent_pid, heap};
355
Colin Crossf572b912017-06-20 18:07:29 -0700356 if (!unreachable.CollectAllocations(thread_info, mappings, refs)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800357 _exit(2);
358 }
359 size_t num_allocations = unreachable.Allocations();
360 size_t allocation_bytes = unreachable.AllocationBytes();
361
362 allocator::vector<Leak> leaks{heap};
363
364 size_t num_leaks = 0;
365 size_t leak_bytes = 0;
366 bool ok = unreachable.GetUnreachableMemory(leaks, limit, &num_leaks, &leak_bytes);
367
368 ok = ok && pipe.Sender().Send(num_allocations);
369 ok = ok && pipe.Sender().Send(allocation_bytes);
370 ok = ok && pipe.Sender().Send(num_leaks);
371 ok = ok && pipe.Sender().Send(leak_bytes);
372 ok = ok && pipe.Sender().SendVector(leaks);
373
374 if (!ok) {
375 _exit(3);
376 }
377
378 _exit(0);
379 } else {
380 // Nothing left to do in the collection thread, return immediately,
381 // releasing all the captured threads.
Christopher Ferris47dea712017-05-03 17:34:29 -0700382 MEM_ALOGI("collection thread done");
Colin Cross7add50d2016-01-14 15:35:40 -0800383 return 0;
384 }
385 }};
386
387 /////////////////////////////////////////////
388 // Original thread
389 /////////////////////////////////////////////
390
391 {
392 // Disable malloc to get a consistent view of memory
393 ScopedDisableMalloc disable_malloc;
394
395 // Start the collection thread
396 thread.Start();
397
398 // Wait for the collection thread to signal that it is ready to fork the
399 // heap walker process.
Colin Crossde42af02016-01-14 15:35:40 -0800400 continue_parent_sem.Wait(30s);
Colin Cross7add50d2016-01-14 15:35:40 -0800401
402 // Re-enable malloc so the collection thread can fork.
403 }
404
405 // Wait for the collection thread to exit
406 int ret = thread.Join();
407 if (ret != 0) {
408 return false;
409 }
410
411 // Get a pipe from the heap walker process. Transferring a new pipe fd
412 // ensures no other forked processes can have it open, so when the heap
413 // walker process dies the remote side of the pipe will close.
414 if (!pipe.OpenReceiver()) {
415 return false;
416 }
417
418 bool ok = true;
419 ok = ok && pipe.Receiver().Receive(&info.num_allocations);
420 ok = ok && pipe.Receiver().Receive(&info.allocation_bytes);
421 ok = ok && pipe.Receiver().Receive(&info.num_leaks);
422 ok = ok && pipe.Receiver().Receive(&info.leak_bytes);
423 ok = ok && pipe.Receiver().ReceiveVector(info.leaks);
424 if (!ok) {
425 return false;
426 }
427
Christopher Ferris47dea712017-05-03 17:34:29 -0700428 MEM_ALOGI("unreachable memory detection done");
429 MEM_ALOGE("%zu bytes in %zu allocation%s unreachable out of %zu bytes in %zu allocation%s",
430 info.leak_bytes, info.num_leaks, plural(info.num_leaks), info.allocation_bytes,
431 info.num_allocations, plural(info.num_allocations));
Colin Cross7add50d2016-01-14 15:35:40 -0800432 return true;
433}
434
435std::string Leak::ToString(bool log_contents) const {
Colin Cross7add50d2016-01-14 15:35:40 -0800436 std::ostringstream oss;
437
438 oss << " " << std::dec << size;
Colin Crossde42af02016-01-14 15:35:40 -0800439 oss << " bytes unreachable at ";
Colin Cross7add50d2016-01-14 15:35:40 -0800440 oss << std::hex << begin;
441 oss << std::endl;
Colin Cross7a22e812016-03-04 16:36:12 -0800442 if (referenced_count > 0) {
443 oss << std::dec;
444 oss << " referencing " << referenced_size << " unreachable bytes";
445 oss << " in " << referenced_count << " allocation" << plural(referenced_count);
446 oss << std::endl;
447 }
448 if (similar_count > 0) {
449 oss << std::dec;
450 oss << " and " << similar_size << " similar unreachable bytes";
451 oss << " in " << similar_count << " allocation" << plural(similar_count);
452 oss << std::endl;
453 if (similar_referenced_count > 0) {
454 oss << " referencing " << similar_referenced_size << " unreachable bytes";
455 oss << " in " << similar_referenced_count << " allocation" << plural(similar_referenced_count);
456 oss << std::endl;
457 }
458 }
Colin Cross7add50d2016-01-14 15:35:40 -0800459
460 if (log_contents) {
461 const int bytes_per_line = 16;
462 const size_t bytes = std::min(size, contents_length);
463
464 if (bytes == size) {
465 oss << " contents:" << std::endl;
466 } else {
Colin Cross7a22e812016-03-04 16:36:12 -0800467 oss << " first " << bytes << " bytes of contents:" << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800468 }
469
470 for (size_t i = 0; i < bytes; i += bytes_per_line) {
471 oss << " " << std::hex << begin + i << ": ";
472 size_t j;
473 oss << std::setfill('0');
474 for (j = i; j < bytes && j < i + bytes_per_line; j++) {
475 oss << std::setw(2) << static_cast<int>(contents[j]) << " ";
476 }
477 oss << std::setfill(' ');
478 for (; j < i + bytes_per_line; j++) {
479 oss << " ";
480 }
481 for (j = i; j < bytes && j < i + bytes_per_line; j++) {
482 char c = contents[j];
483 if (c < ' ' || c >= 0x7f) {
484 c = '.';
485 }
486 oss << c;
487 }
488 oss << std::endl;
489 }
490 }
Colin Cross7a22e812016-03-04 16:36:12 -0800491 if (backtrace.num_frames > 0) {
492 oss << backtrace_string(backtrace.frames, backtrace.num_frames);
Colin Cross7add50d2016-01-14 15:35:40 -0800493 }
494
495 return oss.str();
496}
497
498std::string UnreachableMemoryInfo::ToString(bool log_contents) const {
499 std::ostringstream oss;
500 oss << " " << leak_bytes << " bytes in ";
Colin Cross7a22e812016-03-04 16:36:12 -0800501 oss << num_leaks << " unreachable allocation" << plural(num_leaks);
Colin Cross7add50d2016-01-14 15:35:40 -0800502 oss << std::endl;
Colin Cross11185af2016-03-04 16:37:02 -0800503 oss << " ABI: '" ABI_STRING "'" << std::endl;
504 oss << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800505
506 for (auto it = leaks.begin(); it != leaks.end(); it++) {
Colin Crossa83881e2017-06-22 10:50:05 -0700507 oss << it->ToString(log_contents);
508 oss << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800509 }
510
511 return oss.str();
512}
513
Colin Crossca71f172018-05-14 14:55:39 -0700514UnreachableMemoryInfo::~UnreachableMemoryInfo() {
515 // Clear the memory that holds the leaks, otherwise the next attempt to
516 // detect leaks may find the old data (for example in the jemalloc tcache)
517 // and consider all the leaks to be referenced.
518 memset(leaks.data(), 0, leaks.capacity() * sizeof(Leak));
519
520 std::vector<Leak> tmp;
521 leaks.swap(tmp);
522
523 // Disable and re-enable malloc to flush the jemalloc tcache to make sure
524 // there are no copies of the leaked pointer addresses there.
525 malloc_disable();
526 malloc_enable();
527}
528
Colin Cross7add50d2016-01-14 15:35:40 -0800529std::string GetUnreachableMemoryString(bool log_contents, size_t limit) {
530 UnreachableMemoryInfo info;
531 if (!GetUnreachableMemory(info, limit)) {
Colin Cross72d38812017-06-13 16:41:58 -0700532 return "Failed to get unreachable memory\n"
533 "If you are trying to get unreachable memory from a system app\n"
534 "(like com.android.systemui), disable selinux first using\n"
535 "setenforce 0\n";
Colin Cross7add50d2016-01-14 15:35:40 -0800536 }
537
538 return info.ToString(log_contents);
539}
540
Colin Crossa9939e92017-06-21 13:13:00 -0700541} // namespace android
542
Colin Cross7add50d2016-01-14 15:35:40 -0800543bool LogUnreachableMemory(bool log_contents, size_t limit) {
Colin Crossa9939e92017-06-21 13:13:00 -0700544 android::UnreachableMemoryInfo info;
545 if (!android::GetUnreachableMemory(info, limit)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800546 return false;
547 }
548
549 for (auto it = info.leaks.begin(); it != info.leaks.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700550 MEM_ALOGE("%s", it->ToString(log_contents).c_str());
Colin Cross7add50d2016-01-14 15:35:40 -0800551 }
552 return true;
553}
554
Colin Cross7add50d2016-01-14 15:35:40 -0800555bool NoLeaks() {
Colin Crossa9939e92017-06-21 13:13:00 -0700556 android::UnreachableMemoryInfo info;
557 if (!android::GetUnreachableMemory(info, 0)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800558 return false;
559 }
560
561 return info.num_leaks == 0;
562}