blob: c4add19ce4385cbc13d9ab3b42b92bf5d623cf45 [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>
Christopher Ferris5db00922019-09-18 10:30:33 -070028#include <android-base/strings.h>
Colin Crossa83881e2017-06-22 10:50:05 -070029#include <backtrace.h>
Colin Cross7add50d2016-01-14 15:35:40 -080030
31#include "Allocator.h"
Colin Crossf572b912017-06-20 18:07:29 -070032#include "Binder.h"
Colin Cross7add50d2016-01-14 15:35:40 -080033#include "HeapWalker.h"
Colin Cross7a22e812016-03-04 16:36:12 -080034#include "Leak.h"
Colin Cross8e8f34c2016-03-02 17:53:39 -080035#include "LeakFolding.h"
Colin Cross7add50d2016-01-14 15:35:40 -080036#include "LeakPipe.h"
37#include "ProcessMappings.h"
38#include "PtracerThread.h"
39#include "ScopedDisableMalloc.h"
40#include "Semaphore.h"
41#include "ThreadCapture.h"
42
Colin Cross7add50d2016-01-14 15:35:40 -080043#include "bionic.h"
44#include "log.h"
Colin Crossa83881e2017-06-22 10:50:05 -070045#include "memunreachable/memunreachable.h"
Colin Cross7add50d2016-01-14 15:35:40 -080046
Colin Cross7add50d2016-01-14 15:35:40 -080047using namespace std::chrono_literals;
48
Colin Crossa9939e92017-06-21 13:13:00 -070049namespace android {
50
51const size_t Leak::contents_length;
52
Colin Cross7add50d2016-01-14 15:35:40 -080053class MemUnreachable {
54 public:
Colin Crossa83881e2017-06-22 10:50:05 -070055 MemUnreachable(pid_t pid, Allocator<void> allocator)
56 : pid_(pid), allocator_(allocator), heap_walker_(allocator_) {}
Colin Cross7add50d2016-01-14 15:35:40 -080057 bool CollectAllocations(const allocator::vector<ThreadInfo>& threads,
Colin Crossf572b912017-06-20 18:07:29 -070058 const allocator::vector<Mapping>& mappings,
59 const allocator::vector<uintptr_t>& refs);
Colin Crossa83881e2017-06-22 10:50:05 -070060 bool GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit, size_t* num_leaks,
61 size_t* leak_bytes);
Colin Cross7add50d2016-01-14 15:35:40 -080062 size_t Allocations() { return heap_walker_.Allocations(); }
63 size_t AllocationBytes() { return heap_walker_.AllocationBytes(); }
Colin Crossa83881e2017-06-22 10:50:05 -070064
Colin Cross7add50d2016-01-14 15:35:40 -080065 private:
66 bool ClassifyMappings(const allocator::vector<Mapping>& mappings,
Colin Crossa83881e2017-06-22 10:50:05 -070067 allocator::vector<Mapping>& heap_mappings,
68 allocator::vector<Mapping>& anon_mappings,
69 allocator::vector<Mapping>& globals_mappings,
70 allocator::vector<Mapping>& stack_mappings);
Colin Cross7add50d2016-01-14 15:35:40 -080071 DISALLOW_COPY_AND_ASSIGN(MemUnreachable);
72 pid_t pid_;
73 Allocator<void> allocator_;
74 HeapWalker heap_walker_;
75};
76
77static void HeapIterate(const Mapping& heap_mapping,
Colin Crossa83881e2017-06-22 10:50:05 -070078 const std::function<void(uintptr_t, size_t)>& func) {
Colin Cross7add50d2016-01-14 15:35:40 -080079 malloc_iterate(heap_mapping.begin, heap_mapping.end - heap_mapping.begin,
Colin Crossa83881e2017-06-22 10:50:05 -070080 [](uintptr_t base, size_t size, void* arg) {
81 auto f = reinterpret_cast<const std::function<void(uintptr_t, size_t)>*>(arg);
82 (*f)(base, size);
83 },
84 const_cast<void*>(reinterpret_cast<const void*>(&func)));
Colin Cross7add50d2016-01-14 15:35:40 -080085}
86
87bool MemUnreachable::CollectAllocations(const allocator::vector<ThreadInfo>& threads,
Colin Crossf572b912017-06-20 18:07:29 -070088 const allocator::vector<Mapping>& mappings,
89 const allocator::vector<uintptr_t>& refs) {
Christopher Ferris47dea712017-05-03 17:34:29 -070090 MEM_ALOGI("searching process %d for allocations", pid_);
Colin Cross3ca19762018-11-28 17:01:59 -080091
92 for (auto it = mappings.begin(); it != mappings.end(); it++) {
93 heap_walker_.Mapping(it->begin, it->end);
94 }
95
Colin Cross7add50d2016-01-14 15:35:40 -080096 allocator::vector<Mapping> heap_mappings{mappings};
97 allocator::vector<Mapping> anon_mappings{mappings};
98 allocator::vector<Mapping> globals_mappings{mappings};
99 allocator::vector<Mapping> stack_mappings{mappings};
Christopher Ferris47dea712017-05-03 17:34:29 -0700100 if (!ClassifyMappings(mappings, heap_mappings, anon_mappings, globals_mappings, stack_mappings)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800101 return false;
102 }
103
104 for (auto it = heap_mappings.begin(); it != heap_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700105 MEM_ALOGV("Heap mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
106 HeapIterate(*it,
107 [&](uintptr_t base, size_t size) { heap_walker_.Allocation(base, base + size); });
Colin Cross7add50d2016-01-14 15:35:40 -0800108 }
109
110 for (auto it = anon_mappings.begin(); it != anon_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700111 MEM_ALOGV("Anon mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800112 heap_walker_.Allocation(it->begin, it->end);
113 }
114
115 for (auto it = globals_mappings.begin(); it != globals_mappings.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700116 MEM_ALOGV("Globals mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800117 heap_walker_.Root(it->begin, it->end);
118 }
119
120 for (auto thread_it = threads.begin(); thread_it != threads.end(); thread_it++) {
121 for (auto it = stack_mappings.begin(); it != stack_mappings.end(); it++) {
122 if (thread_it->stack.first >= it->begin && thread_it->stack.first <= it->end) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700123 MEM_ALOGV("Stack %" PRIxPTR "-%" PRIxPTR " %s", thread_it->stack.first, it->end, it->name);
Colin Cross7add50d2016-01-14 15:35:40 -0800124 heap_walker_.Root(thread_it->stack.first, it->end);
125 }
126 }
127 heap_walker_.Root(thread_it->regs);
128 }
129
Colin Crossf572b912017-06-20 18:07:29 -0700130 heap_walker_.Root(refs);
131
Christopher Ferris47dea712017-05-03 17:34:29 -0700132 MEM_ALOGI("searching done");
Colin Cross7add50d2016-01-14 15:35:40 -0800133
134 return true;
135}
136
Colin Crossa83881e2017-06-22 10:50:05 -0700137bool MemUnreachable::GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit,
138 size_t* num_leaks, size_t* leak_bytes) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700139 MEM_ALOGI("sweeping process %d for unreachable memory", pid_);
Colin Cross7add50d2016-01-14 15:35:40 -0800140 leaks.clear();
141
Colin Cross8e8f34c2016-03-02 17:53:39 -0800142 if (!heap_walker_.DetectLeaks()) {
143 return false;
144 }
145
Colin Cross7a22e812016-03-04 16:36:12 -0800146 allocator::vector<Range> leaked1{allocator_};
147 heap_walker_.Leaked(leaked1, 0, num_leaks, leak_bytes);
148
Christopher Ferris47dea712017-05-03 17:34:29 -0700149 MEM_ALOGI("sweeping done");
Colin Cross7a22e812016-03-04 16:36:12 -0800150
Christopher Ferris47dea712017-05-03 17:34:29 -0700151 MEM_ALOGI("folding related leaks");
Colin Cross7a22e812016-03-04 16:36:12 -0800152
Colin Cross8e8f34c2016-03-02 17:53:39 -0800153 LeakFolding folding(allocator_, heap_walker_);
154 if (!folding.FoldLeaks()) {
155 return false;
156 }
157
158 allocator::vector<LeakFolding::Leak> leaked{allocator_};
159
Colin Cross7a22e812016-03-04 16:36:12 -0800160 if (!folding.Leaked(leaked, num_leaks, leak_bytes)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800161 return false;
162 }
163
Colin Cross7a22e812016-03-04 16:36:12 -0800164 allocator::unordered_map<Leak::Backtrace, Leak*> backtrace_map{allocator_};
165
166 // Prevent reallocations of backing memory so we can store pointers into it
167 // in backtrace_map.
168 leaks.reserve(leaked.size());
169
Colin Crossa83881e2017-06-22 10:50:05 -0700170 for (auto& it : leaked) {
Colin Cross7a22e812016-03-04 16:36:12 -0800171 leaks.emplace_back();
172 Leak* leak = &leaks.back();
173
Colin Crossa83881e2017-06-22 10:50:05 -0700174 ssize_t num_backtrace_frames = malloc_backtrace(
175 reinterpret_cast<void*>(it.range.begin), leak->backtrace.frames, leak->backtrace.max_frames);
Colin Cross7add50d2016-01-14 15:35:40 -0800176 if (num_backtrace_frames > 0) {
Colin Cross7a22e812016-03-04 16:36:12 -0800177 leak->backtrace.num_frames = num_backtrace_frames;
178
179 auto inserted = backtrace_map.emplace(leak->backtrace, leak);
180 if (!inserted.second) {
181 // Leak with same backtrace already exists, drop this one and
182 // increment similar counts on the existing one.
183 leaks.pop_back();
184 Leak* similar_leak = inserted.first->second;
185 similar_leak->similar_count++;
186 similar_leak->similar_size += it.range.size();
187 similar_leak->similar_referenced_count += it.referenced_count;
188 similar_leak->similar_referenced_size += it.referenced_size;
189 similar_leak->total_size += it.range.size();
190 similar_leak->total_size += it.referenced_size;
191 continue;
192 }
Colin Cross7add50d2016-01-14 15:35:40 -0800193 }
Colin Cross7a22e812016-03-04 16:36:12 -0800194
195 leak->begin = it.range.begin;
196 leak->size = it.range.size();
197 leak->referenced_count = it.referenced_count;
198 leak->referenced_size = it.referenced_size;
199 leak->total_size = leak->size + leak->referenced_size;
200 memcpy(leak->contents, reinterpret_cast<void*>(it.range.begin),
Colin Crossa83881e2017-06-22 10:50:05 -0700201 std::min(leak->size, Leak::contents_length));
Colin Cross7add50d2016-01-14 15:35:40 -0800202 }
203
Christopher Ferris47dea712017-05-03 17:34:29 -0700204 MEM_ALOGI("folding done");
Colin Cross7a22e812016-03-04 16:36:12 -0800205
Colin Crossa83881e2017-06-22 10:50:05 -0700206 std::sort(leaks.begin(), leaks.end(),
207 [](const Leak& a, const Leak& b) { return a.total_size > b.total_size; });
Colin Cross7a22e812016-03-04 16:36:12 -0800208
209 if (leaks.size() > limit) {
210 leaks.resize(limit);
211 }
Colin Cross7add50d2016-01-14 15:35:40 -0800212
213 return true;
214}
215
216static bool has_prefix(const allocator::string& s, const char* prefix) {
217 int ret = s.compare(0, strlen(prefix), prefix);
218 return ret == 0;
219}
220
Evgenii Stepanov3e1c6042019-03-19 17:17:47 -0700221static bool is_sanitizer_mapping(const allocator::string& s) {
222 return s == "[anon:low shadow]" || s == "[anon:high shadow]" || has_prefix(s, "[anon:hwasan");
223}
224
Colin Cross7add50d2016-01-14 15:35:40 -0800225bool MemUnreachable::ClassifyMappings(const allocator::vector<Mapping>& mappings,
Colin Crossa83881e2017-06-22 10:50:05 -0700226 allocator::vector<Mapping>& heap_mappings,
227 allocator::vector<Mapping>& anon_mappings,
228 allocator::vector<Mapping>& globals_mappings,
229 allocator::vector<Mapping>& stack_mappings) {
Colin Cross7add50d2016-01-14 15:35:40 -0800230 heap_mappings.clear();
231 anon_mappings.clear();
232 globals_mappings.clear();
233 stack_mappings.clear();
234
235 allocator::string current_lib{allocator_};
236
237 for (auto it = mappings.begin(); it != mappings.end(); it++) {
238 if (it->execute) {
239 current_lib = it->name;
240 continue;
241 }
242
243 if (!it->read) {
244 continue;
245 }
246
247 const allocator::string mapping_name{it->name, allocator_};
248 if (mapping_name == "[anon:.bss]") {
249 // named .bss section
250 globals_mappings.emplace_back(*it);
251 } else if (mapping_name == current_lib) {
252 // .rodata or .data section
253 globals_mappings.emplace_back(*it);
Christopher Ferris5db00922019-09-18 10:30:33 -0700254 } else if (mapping_name == "[anon:libc_malloc]" ||
255 android::base::StartsWith(mapping_name, "[anon:scudo:")) {
Colin Cross7add50d2016-01-14 15:35:40 -0800256 // named malloc mapping
257 heap_mappings.emplace_back(*it);
Joel Fernandesed59ff42018-08-24 11:57:57 -0700258 } else if (has_prefix(mapping_name, "[anon:dalvik-")) {
Colin Cross7add50d2016-01-14 15:35:40 -0800259 // named dalvik heap mapping
260 globals_mappings.emplace_back(*it);
261 } else if (has_prefix(mapping_name, "[stack")) {
262 // named stack mapping
263 stack_mappings.emplace_back(*it);
264 } else if (mapping_name.size() == 0) {
265 globals_mappings.emplace_back(*it);
Colin Crossa83881e2017-06-22 10:50:05 -0700266 } else if (has_prefix(mapping_name, "[anon:") &&
Evgenii Stepanov3e1c6042019-03-19 17:17:47 -0700267 mapping_name != "[anon:leak_detector_malloc]" &&
268 !is_sanitizer_mapping(mapping_name)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800269 // TODO(ccross): it would be nice to treat named anonymous mappings as
270 // possible leaks, but naming something in a .bss or .data section makes
271 // it impossible to distinguish them from mmaped and then named mappings.
272 globals_mappings.emplace_back(*it);
273 }
274 }
275
276 return true;
277}
278
Colin Crossa83881e2017-06-22 10:50:05 -0700279template <typename T>
Colin Cross7a22e812016-03-04 16:36:12 -0800280static inline const char* plural(T val) {
281 return (val == 1) ? "" : "s";
282}
283
Colin Cross7add50d2016-01-14 15:35:40 -0800284bool GetUnreachableMemory(UnreachableMemoryInfo& info, size_t limit) {
Colin Cross025ed8a2019-05-20 12:55:33 -0700285 if (info.version > 0) {
286 MEM_ALOGE("unsupported UnreachableMemoryInfo.version %zu in GetUnreachableMemory",
287 info.version);
288 return false;
289 }
290
Colin Cross7add50d2016-01-14 15:35:40 -0800291 int parent_pid = getpid();
292 int parent_tid = gettid();
293
294 Heap heap;
295
296 Semaphore continue_parent_sem;
297 LeakPipe pipe;
298
299 PtracerThread thread{[&]() -> int {
300 /////////////////////////////////////////////
301 // Collection thread
302 /////////////////////////////////////////////
Christopher Ferris47dea712017-05-03 17:34:29 -0700303 MEM_ALOGI("collecting thread info for process %d...", parent_pid);
Colin Cross7add50d2016-01-14 15:35:40 -0800304
305 ThreadCapture thread_capture(parent_pid, heap);
306 allocator::vector<ThreadInfo> thread_info(heap);
307 allocator::vector<Mapping> mappings(heap);
Colin Crossf572b912017-06-20 18:07:29 -0700308 allocator::vector<uintptr_t> refs(heap);
Colin Cross7add50d2016-01-14 15:35:40 -0800309
310 // ptrace all the threads
311 if (!thread_capture.CaptureThreads()) {
Colin Crossde42af02016-01-14 15:35:40 -0800312 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800313 return 1;
314 }
315
316 // collect register contents and stacks
317 if (!thread_capture.CapturedThreadInfo(thread_info)) {
Colin Crossde42af02016-01-14 15:35:40 -0800318 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800319 return 1;
320 }
321
322 // snapshot /proc/pid/maps
323 if (!ProcessMappings(parent_pid, mappings)) {
Colin Crossde42af02016-01-14 15:35:40 -0800324 continue_parent_sem.Post();
Colin Cross7add50d2016-01-14 15:35:40 -0800325 return 1;
326 }
327
Colin Crossf572b912017-06-20 18:07:29 -0700328 if (!BinderReferences(refs)) {
329 continue_parent_sem.Post();
330 return 1;
331 }
332
Colin Cross7add50d2016-01-14 15:35:40 -0800333 // malloc must be enabled to call fork, at_fork handlers take the same
334 // locks as ScopedDisableMalloc. All threads are paused in ptrace, so
335 // memory state is still consistent. Unfreeze the original thread so it
336 // can drop the malloc locks, it will block until the collection thread
337 // exits.
338 thread_capture.ReleaseThread(parent_tid);
339 continue_parent_sem.Post();
340
341 // fork a process to do the heap walking
342 int ret = fork();
343 if (ret < 0) {
344 return 1;
345 } else if (ret == 0) {
346 /////////////////////////////////////////////
347 // Heap walker process
348 /////////////////////////////////////////////
349 // Examine memory state in the child using the data collected above and
350 // the CoW snapshot of the process memory contents.
351
352 if (!pipe.OpenSender()) {
353 _exit(1);
354 }
355
356 MemUnreachable unreachable{parent_pid, heap};
357
Colin Crossf572b912017-06-20 18:07:29 -0700358 if (!unreachable.CollectAllocations(thread_info, mappings, refs)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800359 _exit(2);
360 }
361 size_t num_allocations = unreachable.Allocations();
362 size_t allocation_bytes = unreachable.AllocationBytes();
363
364 allocator::vector<Leak> leaks{heap};
365
366 size_t num_leaks = 0;
367 size_t leak_bytes = 0;
368 bool ok = unreachable.GetUnreachableMemory(leaks, limit, &num_leaks, &leak_bytes);
369
370 ok = ok && pipe.Sender().Send(num_allocations);
371 ok = ok && pipe.Sender().Send(allocation_bytes);
372 ok = ok && pipe.Sender().Send(num_leaks);
373 ok = ok && pipe.Sender().Send(leak_bytes);
374 ok = ok && pipe.Sender().SendVector(leaks);
375
376 if (!ok) {
377 _exit(3);
378 }
379
380 _exit(0);
381 } else {
382 // Nothing left to do in the collection thread, return immediately,
383 // releasing all the captured threads.
Christopher Ferris47dea712017-05-03 17:34:29 -0700384 MEM_ALOGI("collection thread done");
Colin Cross7add50d2016-01-14 15:35:40 -0800385 return 0;
386 }
387 }};
388
389 /////////////////////////////////////////////
390 // Original thread
391 /////////////////////////////////////////////
392
393 {
394 // Disable malloc to get a consistent view of memory
395 ScopedDisableMalloc disable_malloc;
396
397 // Start the collection thread
398 thread.Start();
399
400 // Wait for the collection thread to signal that it is ready to fork the
401 // heap walker process.
Colin Crossde42af02016-01-14 15:35:40 -0800402 continue_parent_sem.Wait(30s);
Colin Cross7add50d2016-01-14 15:35:40 -0800403
404 // Re-enable malloc so the collection thread can fork.
405 }
406
407 // Wait for the collection thread to exit
408 int ret = thread.Join();
409 if (ret != 0) {
410 return false;
411 }
412
413 // Get a pipe from the heap walker process. Transferring a new pipe fd
414 // ensures no other forked processes can have it open, so when the heap
415 // walker process dies the remote side of the pipe will close.
416 if (!pipe.OpenReceiver()) {
417 return false;
418 }
419
420 bool ok = true;
421 ok = ok && pipe.Receiver().Receive(&info.num_allocations);
422 ok = ok && pipe.Receiver().Receive(&info.allocation_bytes);
423 ok = ok && pipe.Receiver().Receive(&info.num_leaks);
424 ok = ok && pipe.Receiver().Receive(&info.leak_bytes);
425 ok = ok && pipe.Receiver().ReceiveVector(info.leaks);
426 if (!ok) {
427 return false;
428 }
429
Christopher Ferris47dea712017-05-03 17:34:29 -0700430 MEM_ALOGI("unreachable memory detection done");
431 MEM_ALOGE("%zu bytes in %zu allocation%s unreachable out of %zu bytes in %zu allocation%s",
432 info.leak_bytes, info.num_leaks, plural(info.num_leaks), info.allocation_bytes,
433 info.num_allocations, plural(info.num_allocations));
Colin Cross7add50d2016-01-14 15:35:40 -0800434 return true;
435}
436
437std::string Leak::ToString(bool log_contents) const {
Colin Cross7add50d2016-01-14 15:35:40 -0800438 std::ostringstream oss;
439
440 oss << " " << std::dec << size;
Colin Crossde42af02016-01-14 15:35:40 -0800441 oss << " bytes unreachable at ";
Colin Cross7add50d2016-01-14 15:35:40 -0800442 oss << std::hex << begin;
443 oss << std::endl;
Colin Cross7a22e812016-03-04 16:36:12 -0800444 if (referenced_count > 0) {
445 oss << std::dec;
446 oss << " referencing " << referenced_size << " unreachable bytes";
447 oss << " in " << referenced_count << " allocation" << plural(referenced_count);
448 oss << std::endl;
449 }
450 if (similar_count > 0) {
451 oss << std::dec;
452 oss << " and " << similar_size << " similar unreachable bytes";
453 oss << " in " << similar_count << " allocation" << plural(similar_count);
454 oss << std::endl;
455 if (similar_referenced_count > 0) {
456 oss << " referencing " << similar_referenced_size << " unreachable bytes";
457 oss << " in " << similar_referenced_count << " allocation" << plural(similar_referenced_count);
458 oss << std::endl;
459 }
460 }
Colin Cross7add50d2016-01-14 15:35:40 -0800461
462 if (log_contents) {
463 const int bytes_per_line = 16;
464 const size_t bytes = std::min(size, contents_length);
465
466 if (bytes == size) {
467 oss << " contents:" << std::endl;
468 } else {
Colin Cross7a22e812016-03-04 16:36:12 -0800469 oss << " first " << bytes << " bytes of contents:" << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800470 }
471
472 for (size_t i = 0; i < bytes; i += bytes_per_line) {
473 oss << " " << std::hex << begin + i << ": ";
474 size_t j;
475 oss << std::setfill('0');
476 for (j = i; j < bytes && j < i + bytes_per_line; j++) {
477 oss << std::setw(2) << static_cast<int>(contents[j]) << " ";
478 }
479 oss << std::setfill(' ');
480 for (; j < i + bytes_per_line; j++) {
481 oss << " ";
482 }
483 for (j = i; j < bytes && j < i + bytes_per_line; j++) {
484 char c = contents[j];
485 if (c < ' ' || c >= 0x7f) {
486 c = '.';
487 }
488 oss << c;
489 }
490 oss << std::endl;
491 }
492 }
Colin Cross7a22e812016-03-04 16:36:12 -0800493 if (backtrace.num_frames > 0) {
494 oss << backtrace_string(backtrace.frames, backtrace.num_frames);
Colin Cross7add50d2016-01-14 15:35:40 -0800495 }
496
497 return oss.str();
498}
499
500std::string UnreachableMemoryInfo::ToString(bool log_contents) const {
501 std::ostringstream oss;
502 oss << " " << leak_bytes << " bytes in ";
Colin Cross7a22e812016-03-04 16:36:12 -0800503 oss << num_leaks << " unreachable allocation" << plural(num_leaks);
Colin Cross7add50d2016-01-14 15:35:40 -0800504 oss << std::endl;
Colin Cross11185af2016-03-04 16:37:02 -0800505 oss << " ABI: '" ABI_STRING "'" << std::endl;
506 oss << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800507
508 for (auto it = leaks.begin(); it != leaks.end(); it++) {
Colin Crossa83881e2017-06-22 10:50:05 -0700509 oss << it->ToString(log_contents);
510 oss << std::endl;
Colin Cross7add50d2016-01-14 15:35:40 -0800511 }
512
513 return oss.str();
514}
515
Colin Crossca71f172018-05-14 14:55:39 -0700516UnreachableMemoryInfo::~UnreachableMemoryInfo() {
517 // Clear the memory that holds the leaks, otherwise the next attempt to
518 // detect leaks may find the old data (for example in the jemalloc tcache)
519 // and consider all the leaks to be referenced.
520 memset(leaks.data(), 0, leaks.capacity() * sizeof(Leak));
521
522 std::vector<Leak> tmp;
523 leaks.swap(tmp);
524
525 // Disable and re-enable malloc to flush the jemalloc tcache to make sure
526 // there are no copies of the leaked pointer addresses there.
527 malloc_disable();
528 malloc_enable();
529}
530
Colin Cross7add50d2016-01-14 15:35:40 -0800531std::string GetUnreachableMemoryString(bool log_contents, size_t limit) {
532 UnreachableMemoryInfo info;
533 if (!GetUnreachableMemory(info, limit)) {
Colin Cross72d38812017-06-13 16:41:58 -0700534 return "Failed to get unreachable memory\n"
535 "If you are trying to get unreachable memory from a system app\n"
536 "(like com.android.systemui), disable selinux first using\n"
537 "setenforce 0\n";
Colin Cross7add50d2016-01-14 15:35:40 -0800538 }
539
540 return info.ToString(log_contents);
541}
542
Colin Crossa9939e92017-06-21 13:13:00 -0700543} // namespace android
544
Colin Cross7add50d2016-01-14 15:35:40 -0800545bool LogUnreachableMemory(bool log_contents, size_t limit) {
Colin Crossa9939e92017-06-21 13:13:00 -0700546 android::UnreachableMemoryInfo info;
547 if (!android::GetUnreachableMemory(info, limit)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800548 return false;
549 }
550
551 for (auto it = info.leaks.begin(); it != info.leaks.end(); it++) {
Christopher Ferris47dea712017-05-03 17:34:29 -0700552 MEM_ALOGE("%s", it->ToString(log_contents).c_str());
Colin Cross7add50d2016-01-14 15:35:40 -0800553 }
554 return true;
555}
556
Colin Cross7add50d2016-01-14 15:35:40 -0800557bool NoLeaks() {
Colin Crossa9939e92017-06-21 13:13:00 -0700558 android::UnreachableMemoryInfo info;
559 if (!android::GetUnreachableMemory(info, 0)) {
Colin Cross7add50d2016-01-14 15:35:40 -0800560 return false;
561 }
562
563 return info.num_leaks == 0;
564}