• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 <inttypes.h>
30 #include <stdint.h>
31 
32 #include <array>
33 #include <mutex>
34 #include <vector>
35 
36 #include <android/fdsan.h>
37 #include <bionic/fdtrack.h>
38 
39 #include <android-base/no_destructor.h>
40 #include <android-base/thread_annotations.h>
41 #include <async_safe/log.h>
42 #include <bionic/reserved_signals.h>
43 #include <unwindstack/LocalUnwinder.h>
44 
45 struct FdEntry {
46   std::mutex mutex;
47   std::vector<unwindstack::LocalFrameData> backtrace GUARDED_BY(mutex);
48 };
49 
50 extern "C" void fdtrack_dump();
51 
52 using fdtrack_callback_t = bool (*)(int fd, const char* const* function_names,
53                                     const uint64_t* function_offsets, size_t count, void* arg);
54 extern "C" void fdtrack_iterate(fdtrack_callback_t callback, void* arg);
55 
56 static void fd_hook(android_fdtrack_event* event);
57 
58 // Backtraces for the first 4k file descriptors ought to be enough to diagnose an fd leak.
59 static constexpr size_t kFdTableSize = 4096;
60 static constexpr size_t kStackDepth = 10;
61 
62 static bool installed = false;
63 static std::array<FdEntry, kFdTableSize> stack_traces [[clang::no_destroy]];
Unwinder()64 static unwindstack::LocalUnwinder& Unwinder() {
65   static android::base::NoDestructor<unwindstack::LocalUnwinder> unwinder;
66   return *unwinder.get();
67 }
68 
ctor()69 __attribute__((constructor)) static void ctor() {
70   for (auto& entry : stack_traces) {
71     entry.backtrace.reserve(kStackDepth);
72   }
73 
74   signal(BIONIC_SIGNAL_FDTRACK, [](int) { fdtrack_dump(); });
75   if (Unwinder().Init()) {
76     android_fdtrack_hook_t expected = nullptr;
77     installed = android_fdtrack_compare_exchange_hook(&expected, &fd_hook);
78   }
79 }
80 
dtor()81 __attribute__((destructor)) static void dtor() {
82   if (installed) {
83     android_fdtrack_hook_t expected = &fd_hook;
84     android_fdtrack_compare_exchange_hook(&expected, nullptr);
85   }
86 }
87 
GetFdEntry(int fd)88 FdEntry* GetFdEntry(int fd) {
89   if (fd >= 0 && fd < static_cast<int>(kFdTableSize)) {
90     return &stack_traces[fd];
91   }
92   return nullptr;
93 }
94 
fd_hook(android_fdtrack_event * event)95 static void fd_hook(android_fdtrack_event* event) {
96   if (event->type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
97     if (FdEntry* entry = GetFdEntry(event->fd); entry) {
98       std::lock_guard<std::mutex> lock(entry->mutex);
99       entry->backtrace.clear();
100       Unwinder().Unwind(&entry->backtrace, kStackDepth);
101     }
102   } else if (event->type == ANDROID_FDTRACK_EVENT_TYPE_CLOSE) {
103     if (FdEntry* entry = GetFdEntry(event->fd); entry) {
104       std::lock_guard<std::mutex> lock(entry->mutex);
105       entry->backtrace.clear();
106     }
107   }
108 }
109 
fdtrack_iterate(fdtrack_callback_t callback,void * arg)110 void fdtrack_iterate(fdtrack_callback_t callback, void* arg) {
111   bool prev = android_fdtrack_set_enabled(false);
112 
113   for (int fd = 0; fd < static_cast<int>(stack_traces.size()); ++fd) {
114     const char* function_names[kStackDepth];
115     uint64_t function_offsets[kStackDepth];
116     FdEntry* entry = GetFdEntry(fd);
117     if (!entry) {
118       continue;
119     }
120 
121     if (!entry->mutex.try_lock()) {
122       async_safe_format_log(ANDROID_LOG_WARN, "fdtrack", "fd %d locked, skipping", fd);
123       continue;
124     }
125 
126     if (entry->backtrace.empty()) {
127       entry->mutex.unlock();
128       continue;
129     } else if (entry->backtrace.size() < 2) {
130       async_safe_format_log(ANDROID_LOG_WARN, "fdtrack", "fd %d missing frames: size = %zu", fd,
131                             entry->backtrace.size());
132 
133       entry->mutex.unlock();
134       continue;
135     }
136 
137     constexpr size_t frame_skip = 2;
138     for (size_t i = frame_skip; i < entry->backtrace.size(); ++i) {
139       size_t j = i - frame_skip;
140       function_names[j] = entry->backtrace[i].function_name.c_str();
141       function_offsets[j] = entry->backtrace[i].function_offset;
142     }
143 
144     bool should_continue =
145         callback(fd, function_names, function_offsets, entry->backtrace.size() - frame_skip, arg);
146 
147     entry->mutex.unlock();
148 
149     if (!should_continue) {
150       break;
151     }
152   }
153 
154   android_fdtrack_set_enabled(prev);
155 }
156 
fdtrack_dump()157 void fdtrack_dump() {
158   if (!installed) {
159     async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack not installed");
160   } else {
161     async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack dumping...");
162   }
163 
164   fdtrack_iterate(
165       [](int fd, const char* const* function_names, const uint64_t* function_offsets, size_t count,
166          void*) {
167         uint64_t fdsan_owner = android_fdsan_get_owner_tag(fd);
168         if (fdsan_owner != 0) {
169           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (owner = 0x%" PRIx64 ")", fd,
170                                 fdsan_owner);
171         } else {
172           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (unowned)", fd);
173         }
174 
175         for (size_t i = 0; i < count; ++i) {
176           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "  %zu: %s+%" PRIu64, i,
177                                 function_names[i], function_offsets[i]);
178         }
179 
180         return true;
181       },
182       nullptr);
183 }
184