• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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>
18 #include <string.h>
19 
20 #include <functional>
21 #include <iomanip>
22 #include <mutex>
23 #include <sstream>
24 #include <string>
25 #include <unordered_map>
26 
27 #include <android-base/macros.h>
28 #include <backtrace.h>
29 
30 #include "Allocator.h"
31 #include "Binder.h"
32 #include "HeapWalker.h"
33 #include "Leak.h"
34 #include "LeakFolding.h"
35 #include "LeakPipe.h"
36 #include "ProcessMappings.h"
37 #include "PtracerThread.h"
38 #include "ScopedDisableMalloc.h"
39 #include "Semaphore.h"
40 #include "ThreadCapture.h"
41 
42 #include "bionic.h"
43 #include "log.h"
44 #include "memunreachable/memunreachable.h"
45 
46 using namespace std::chrono_literals;
47 
48 namespace android {
49 
50 const size_t Leak::contents_length;
51 
52 class MemUnreachable {
53  public:
MemUnreachable(pid_t pid,Allocator<void> allocator)54   MemUnreachable(pid_t pid, Allocator<void> allocator)
55       : pid_(pid), allocator_(allocator), heap_walker_(allocator_) {}
56   bool CollectAllocations(const allocator::vector<ThreadInfo>& threads,
57                           const allocator::vector<Mapping>& mappings,
58                           const allocator::vector<uintptr_t>& refs);
59   bool GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit, size_t* num_leaks,
60                             size_t* leak_bytes);
Allocations()61   size_t Allocations() { return heap_walker_.Allocations(); }
AllocationBytes()62   size_t AllocationBytes() { return heap_walker_.AllocationBytes(); }
63 
64  private:
65   bool ClassifyMappings(const allocator::vector<Mapping>& mappings,
66                         allocator::vector<Mapping>& heap_mappings,
67                         allocator::vector<Mapping>& anon_mappings,
68                         allocator::vector<Mapping>& globals_mappings,
69                         allocator::vector<Mapping>& stack_mappings);
70   DISALLOW_COPY_AND_ASSIGN(MemUnreachable);
71   pid_t pid_;
72   Allocator<void> allocator_;
73   HeapWalker heap_walker_;
74 };
75 
HeapIterate(const Mapping & heap_mapping,const std::function<void (uintptr_t,size_t)> & func)76 static void HeapIterate(const Mapping& heap_mapping,
77                         const std::function<void(uintptr_t, size_t)>& func) {
78   malloc_iterate(heap_mapping.begin, heap_mapping.end - heap_mapping.begin,
79                  [](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)));
84 }
85 
CollectAllocations(const allocator::vector<ThreadInfo> & threads,const allocator::vector<Mapping> & mappings,const allocator::vector<uintptr_t> & refs)86 bool MemUnreachable::CollectAllocations(const allocator::vector<ThreadInfo>& threads,
87                                         const allocator::vector<Mapping>& mappings,
88                                         const allocator::vector<uintptr_t>& refs) {
89   MEM_ALOGI("searching process %d for allocations", pid_);
90 
91   for (auto it = mappings.begin(); it != mappings.end(); it++) {
92     heap_walker_.Mapping(it->begin, it->end);
93   }
94 
95   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};
99   if (!ClassifyMappings(mappings, heap_mappings, anon_mappings, globals_mappings, stack_mappings)) {
100     return false;
101   }
102 
103   for (auto it = heap_mappings.begin(); it != heap_mappings.end(); it++) {
104     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); });
107   }
108 
109   for (auto it = anon_mappings.begin(); it != anon_mappings.end(); it++) {
110     MEM_ALOGV("Anon mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
111     heap_walker_.Allocation(it->begin, it->end);
112   }
113 
114   for (auto it = globals_mappings.begin(); it != globals_mappings.end(); it++) {
115     MEM_ALOGV("Globals mapping %" PRIxPTR "-%" PRIxPTR " %s", it->begin, it->end, it->name);
116     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) {
122         MEM_ALOGV("Stack %" PRIxPTR "-%" PRIxPTR " %s", thread_it->stack.first, it->end, it->name);
123         heap_walker_.Root(thread_it->stack.first, it->end);
124       }
125     }
126     heap_walker_.Root(thread_it->regs);
127   }
128 
129   heap_walker_.Root(refs);
130 
131   MEM_ALOGI("searching done");
132 
133   return true;
134 }
135 
GetUnreachableMemory(allocator::vector<Leak> & leaks,size_t limit,size_t * num_leaks,size_t * leak_bytes)136 bool MemUnreachable::GetUnreachableMemory(allocator::vector<Leak>& leaks, size_t limit,
137                                           size_t* num_leaks, size_t* leak_bytes) {
138   MEM_ALOGI("sweeping process %d for unreachable memory", pid_);
139   leaks.clear();
140 
141   if (!heap_walker_.DetectLeaks()) {
142     return false;
143   }
144 
145   allocator::vector<Range> leaked1{allocator_};
146   heap_walker_.Leaked(leaked1, 0, num_leaks, leak_bytes);
147 
148   MEM_ALOGI("sweeping done");
149 
150   MEM_ALOGI("folding related leaks");
151 
152   LeakFolding folding(allocator_, heap_walker_);
153   if (!folding.FoldLeaks()) {
154     return false;
155   }
156 
157   allocator::vector<LeakFolding::Leak> leaked{allocator_};
158 
159   if (!folding.Leaked(leaked, num_leaks, leak_bytes)) {
160     return false;
161   }
162 
163   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 
169   for (auto& it : leaked) {
170     leaks.emplace_back();
171     Leak* leak = &leaks.back();
172 
173     ssize_t num_backtrace_frames = malloc_backtrace(
174         reinterpret_cast<void*>(it.range.begin), leak->backtrace.frames, leak->backtrace.max_frames);
175     if (num_backtrace_frames > 0) {
176       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       }
192     }
193 
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),
200            std::min(leak->size, Leak::contents_length));
201   }
202 
203   MEM_ALOGI("folding done");
204 
205   std::sort(leaks.begin(), leaks.end(),
206             [](const Leak& a, const Leak& b) { return a.total_size > b.total_size; });
207 
208   if (leaks.size() > limit) {
209     leaks.resize(limit);
210   }
211 
212   return true;
213 }
214 
has_prefix(const allocator::string & s,const char * prefix)215 static 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 
is_sanitizer_mapping(const allocator::string & s)220 static 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 
ClassifyMappings(const allocator::vector<Mapping> & mappings,allocator::vector<Mapping> & heap_mappings,allocator::vector<Mapping> & anon_mappings,allocator::vector<Mapping> & globals_mappings,allocator::vector<Mapping> & stack_mappings)224 bool MemUnreachable::ClassifyMappings(const allocator::vector<Mapping>& mappings,
225                                       allocator::vector<Mapping>& heap_mappings,
226                                       allocator::vector<Mapping>& anon_mappings,
227                                       allocator::vector<Mapping>& globals_mappings,
228                                       allocator::vector<Mapping>& stack_mappings) {
229   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);
256     } else if (has_prefix(mapping_name, "[anon:dalvik-")) {
257       // 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);
264     } else if (has_prefix(mapping_name, "[anon:") &&
265                mapping_name != "[anon:leak_detector_malloc]" &&
266                !is_sanitizer_mapping(mapping_name)) {
267       // 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 
277 template <typename T>
plural(T val)278 static inline const char* plural(T val) {
279   return (val == 1) ? "" : "s";
280 }
281 
GetUnreachableMemory(UnreachableMemoryInfo & info,size_t limit)282 bool GetUnreachableMemory(UnreachableMemoryInfo& info, size_t limit) {
283   int parent_pid = getpid();
284   int parent_tid = gettid();
285 
286   Heap heap;
287 
288   Semaphore continue_parent_sem;
289   LeakPipe pipe;
290 
291   PtracerThread thread{[&]() -> int {
292     /////////////////////////////////////////////
293     // Collection thread
294     /////////////////////////////////////////////
295     MEM_ALOGI("collecting thread info for process %d...", parent_pid);
296 
297     ThreadCapture thread_capture(parent_pid, heap);
298     allocator::vector<ThreadInfo> thread_info(heap);
299     allocator::vector<Mapping> mappings(heap);
300     allocator::vector<uintptr_t> refs(heap);
301 
302     // ptrace all the threads
303     if (!thread_capture.CaptureThreads()) {
304       continue_parent_sem.Post();
305       return 1;
306     }
307 
308     // collect register contents and stacks
309     if (!thread_capture.CapturedThreadInfo(thread_info)) {
310       continue_parent_sem.Post();
311       return 1;
312     }
313 
314     // snapshot /proc/pid/maps
315     if (!ProcessMappings(parent_pid, mappings)) {
316       continue_parent_sem.Post();
317       return 1;
318     }
319 
320     if (!BinderReferences(refs)) {
321       continue_parent_sem.Post();
322       return 1;
323     }
324 
325     // malloc must be enabled to call fork, at_fork handlers take the same
326     // locks as ScopedDisableMalloc.  All threads are paused in ptrace, so
327     // memory state is still consistent.  Unfreeze the original thread so it
328     // can drop the malloc locks, it will block until the collection thread
329     // exits.
330     thread_capture.ReleaseThread(parent_tid);
331     continue_parent_sem.Post();
332 
333     // fork a process to do the heap walking
334     int ret = fork();
335     if (ret < 0) {
336       return 1;
337     } else if (ret == 0) {
338       /////////////////////////////////////////////
339       // Heap walker process
340       /////////////////////////////////////////////
341       // Examine memory state in the child using the data collected above and
342       // the CoW snapshot of the process memory contents.
343 
344       if (!pipe.OpenSender()) {
345         _exit(1);
346       }
347 
348       MemUnreachable unreachable{parent_pid, heap};
349 
350       if (!unreachable.CollectAllocations(thread_info, mappings, refs)) {
351         _exit(2);
352       }
353       size_t num_allocations = unreachable.Allocations();
354       size_t allocation_bytes = unreachable.AllocationBytes();
355 
356       allocator::vector<Leak> leaks{heap};
357 
358       size_t num_leaks = 0;
359       size_t leak_bytes = 0;
360       bool ok = unreachable.GetUnreachableMemory(leaks, limit, &num_leaks, &leak_bytes);
361 
362       ok = ok && pipe.Sender().Send(num_allocations);
363       ok = ok && pipe.Sender().Send(allocation_bytes);
364       ok = ok && pipe.Sender().Send(num_leaks);
365       ok = ok && pipe.Sender().Send(leak_bytes);
366       ok = ok && pipe.Sender().SendVector(leaks);
367 
368       if (!ok) {
369         _exit(3);
370       }
371 
372       _exit(0);
373     } else {
374       // Nothing left to do in the collection thread, return immediately,
375       // releasing all the captured threads.
376       MEM_ALOGI("collection thread done");
377       return 0;
378     }
379   }};
380 
381   /////////////////////////////////////////////
382   // Original thread
383   /////////////////////////////////////////////
384 
385   {
386     // Disable malloc to get a consistent view of memory
387     ScopedDisableMalloc disable_malloc;
388 
389     // Start the collection thread
390     thread.Start();
391 
392     // Wait for the collection thread to signal that it is ready to fork the
393     // heap walker process.
394     continue_parent_sem.Wait(30s);
395 
396     // Re-enable malloc so the collection thread can fork.
397   }
398 
399   // Wait for the collection thread to exit
400   int ret = thread.Join();
401   if (ret != 0) {
402     return false;
403   }
404 
405   // Get a pipe from the heap walker process.  Transferring a new pipe fd
406   // ensures no other forked processes can have it open, so when the heap
407   // walker process dies the remote side of the pipe will close.
408   if (!pipe.OpenReceiver()) {
409     return false;
410   }
411 
412   bool ok = true;
413   ok = ok && pipe.Receiver().Receive(&info.num_allocations);
414   ok = ok && pipe.Receiver().Receive(&info.allocation_bytes);
415   ok = ok && pipe.Receiver().Receive(&info.num_leaks);
416   ok = ok && pipe.Receiver().Receive(&info.leak_bytes);
417   ok = ok && pipe.Receiver().ReceiveVector(info.leaks);
418   if (!ok) {
419     return false;
420   }
421 
422   MEM_ALOGI("unreachable memory detection done");
423   MEM_ALOGE("%zu bytes in %zu allocation%s unreachable out of %zu bytes in %zu allocation%s",
424             info.leak_bytes, info.num_leaks, plural(info.num_leaks), info.allocation_bytes,
425             info.num_allocations, plural(info.num_allocations));
426   return true;
427 }
428 
ToString(bool log_contents) const429 std::string Leak::ToString(bool log_contents) const {
430   std::ostringstream oss;
431 
432   oss << "  " << std::dec << size;
433   oss << " bytes unreachable at ";
434   oss << std::hex << begin;
435   oss << std::endl;
436   if (referenced_count > 0) {
437     oss << std::dec;
438     oss << "   referencing " << referenced_size << " unreachable bytes";
439     oss << " in " << referenced_count << " allocation" << plural(referenced_count);
440     oss << std::endl;
441   }
442   if (similar_count > 0) {
443     oss << std::dec;
444     oss << "   and " << similar_size << " similar unreachable bytes";
445     oss << " in " << similar_count << " allocation" << plural(similar_count);
446     oss << std::endl;
447     if (similar_referenced_count > 0) {
448       oss << "   referencing " << similar_referenced_size << " unreachable bytes";
449       oss << " in " << similar_referenced_count << " allocation" << plural(similar_referenced_count);
450       oss << std::endl;
451     }
452   }
453 
454   if (log_contents) {
455     const int bytes_per_line = 16;
456     const size_t bytes = std::min(size, contents_length);
457 
458     if (bytes == size) {
459       oss << "   contents:" << std::endl;
460     } else {
461       oss << "   first " << bytes << " bytes of contents:" << std::endl;
462     }
463 
464     for (size_t i = 0; i < bytes; i += bytes_per_line) {
465       oss << "   " << std::hex << begin + i << ": ";
466       size_t j;
467       oss << std::setfill('0');
468       for (j = i; j < bytes && j < i + bytes_per_line; j++) {
469         oss << std::setw(2) << static_cast<int>(contents[j]) << " ";
470       }
471       oss << std::setfill(' ');
472       for (; j < i + bytes_per_line; j++) {
473         oss << "   ";
474       }
475       for (j = i; j < bytes && j < i + bytes_per_line; j++) {
476         char c = contents[j];
477         if (c < ' ' || c >= 0x7f) {
478           c = '.';
479         }
480         oss << c;
481       }
482       oss << std::endl;
483     }
484   }
485   if (backtrace.num_frames > 0) {
486     oss << backtrace_string(backtrace.frames, backtrace.num_frames);
487   }
488 
489   return oss.str();
490 }
491 
ToString(bool log_contents) const492 std::string UnreachableMemoryInfo::ToString(bool log_contents) const {
493   std::ostringstream oss;
494   oss << "  " << leak_bytes << " bytes in ";
495   oss << num_leaks << " unreachable allocation" << plural(num_leaks);
496   oss << std::endl;
497   oss << "  ABI: '" ABI_STRING "'" << std::endl;
498   oss << std::endl;
499 
500   for (auto it = leaks.begin(); it != leaks.end(); it++) {
501     oss << it->ToString(log_contents);
502     oss << std::endl;
503   }
504 
505   return oss.str();
506 }
507 
~UnreachableMemoryInfo()508 UnreachableMemoryInfo::~UnreachableMemoryInfo() {
509   // Clear the memory that holds the leaks, otherwise the next attempt to
510   // detect leaks may find the old data (for example in the jemalloc tcache)
511   // and consider all the leaks to be referenced.
512   memset(leaks.data(), 0, leaks.capacity() * sizeof(Leak));
513 
514   std::vector<Leak> tmp;
515   leaks.swap(tmp);
516 
517   // Disable and re-enable malloc to flush the jemalloc tcache to make sure
518   // there are no copies of the leaked pointer addresses there.
519   malloc_disable();
520   malloc_enable();
521 }
522 
GetUnreachableMemoryString(bool log_contents,size_t limit)523 std::string GetUnreachableMemoryString(bool log_contents, size_t limit) {
524   UnreachableMemoryInfo info;
525   if (!GetUnreachableMemory(info, limit)) {
526     return "Failed to get unreachable memory\n"
527            "If you are trying to get unreachable memory from a system app\n"
528            "(like com.android.systemui), disable selinux first using\n"
529            "setenforce 0\n";
530   }
531 
532   return info.ToString(log_contents);
533 }
534 
535 }  // namespace android
536 
LogUnreachableMemory(bool log_contents,size_t limit)537 bool LogUnreachableMemory(bool log_contents, size_t limit) {
538   android::UnreachableMemoryInfo info;
539   if (!android::GetUnreachableMemory(info, limit)) {
540     return false;
541   }
542 
543   for (auto it = info.leaks.begin(); it != info.leaks.end(); it++) {
544     MEM_ALOGE("%s", it->ToString(log_contents).c_str());
545   }
546   return true;
547 }
548 
NoLeaks()549 bool NoLeaks() {
550   android::UnreachableMemoryInfo info;
551   if (!android::GetUnreachableMemory(info, 0)) {
552     return false;
553   }
554 
555   return info.num_leaks == 0;
556 }
557