blob: 2d114f23ebaba736b5159de09d5b9f57a3b21baf [file] [log] [blame]
Josh Gao97271922019-11-06 13:15:00 -08001/*
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>
Josh Gaoad8f02d2020-01-28 13:54:00 -080030#include <stdint.h>
Josh Gao97271922019-11-06 13:15:00 -080031
32#include <array>
33#include <mutex>
Christopher Ferris459eecb2022-01-07 13:38:10 -080034#include <string>
35#include <string_view>
Josh Gao1cb36812021-03-11 21:11:37 -080036#include <thread>
37#include <utility>
Josh Gao97271922019-11-06 13:15:00 -080038#include <vector>
39
Josh Gao6f088662020-01-28 15:13:47 -080040#include <android/fdsan.h>
Josh Gao1cb36812021-03-11 21:11:37 -080041#include <android/set_abort_message.h>
Josh Gao75962502020-01-28 13:24:33 -080042#include <bionic/fdtrack.h>
Josh Gao97271922019-11-06 13:15:00 -080043
44#include <android-base/no_destructor.h>
45#include <android-base/thread_annotations.h>
46#include <async_safe/log.h>
47#include <bionic/reserved_signals.h>
Christopher Ferris459eecb2022-01-07 13:38:10 -080048#include <unwindstack/Maps.h>
49#include <unwindstack/Regs.h>
50#include <unwindstack/RegsGetLocal.h>
51#include <unwindstack/Unwinder.h>
Josh Gao97271922019-11-06 13:15:00 -080052
53struct FdEntry {
54 std::mutex mutex;
Christopher Ferris459eecb2022-01-07 13:38:10 -080055 std::vector<unwindstack::FrameData> backtrace GUARDED_BY(mutex);
Josh Gao97271922019-11-06 13:15:00 -080056};
57
58extern "C" void fdtrack_dump();
Josh Gao1cb36812021-03-11 21:11:37 -080059extern "C" void fdtrack_dump_fatal();
Josh Gaoad8f02d2020-01-28 13:54:00 -080060
61using fdtrack_callback_t = bool (*)(int fd, const char* const* function_names,
62 const uint64_t* function_offsets, size_t count, void* arg);
63extern "C" void fdtrack_iterate(fdtrack_callback_t callback, void* arg);
64
Josh Gao97271922019-11-06 13:15:00 -080065static void fd_hook(android_fdtrack_event* event);
66
67// Backtraces for the first 4k file descriptors ought to be enough to diagnose an fd leak.
68static constexpr size_t kFdTableSize = 4096;
Josh Gao55b91af2020-06-02 15:54:32 -070069
Christopher Ferris459eecb2022-01-07 13:38:10 -080070// Only unwind up to 32 frames outside of libfdtrack.so.
71static constexpr size_t kStackDepth = 32;
72
73// Skip any initial frames from libfdtrack.so.
74static std::vector<std::string> kSkipFdtrackLib [[clang::no_destroy]] = {"libfdtrack.so"};
Josh Gao97271922019-11-06 13:15:00 -080075
76static bool installed = false;
Josh Gao38d00b82020-04-21 17:05:32 -070077static std::array<FdEntry, kFdTableSize> stack_traces [[clang::no_destroy]];
Christopher Ferris459eecb2022-01-07 13:38:10 -080078static unwindstack::LocalUpdatableMaps& Maps() {
79 static android::base::NoDestructor<unwindstack::LocalUpdatableMaps> maps;
80 return *maps.get();
81}
82static std::shared_ptr<unwindstack::Memory>& ProcessMemory() {
83 static android::base::NoDestructor<std::shared_ptr<unwindstack::Memory>> process_memory;
84 return *process_memory.get();
Josh Gao97271922019-11-06 13:15:00 -080085}
86
87__attribute__((constructor)) static void ctor() {
Josh Gaoad8f02d2020-01-28 13:54:00 -080088 for (auto& entry : stack_traces) {
89 entry.backtrace.reserve(kStackDepth);
90 }
91
Josh Gao1cb36812021-03-11 21:11:37 -080092 struct sigaction sa = {};
93 sa.sa_sigaction = [](int, siginfo_t* siginfo, void*) {
94 if (siginfo->si_code == SI_QUEUE && siginfo->si_int == 1) {
95 fdtrack_dump_fatal();
96 } else {
97 fdtrack_dump();
98 }
99 };
100 sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
101 sigaction(BIONIC_SIGNAL_FDTRACK, &sa, nullptr);
102
Christopher Ferris459eecb2022-01-07 13:38:10 -0800103 if (Maps().Parse()) {
104 ProcessMemory() = unwindstack::Memory::CreateProcessMemoryThreadCached(getpid());
Josh Gao97271922019-11-06 13:15:00 -0800105 android_fdtrack_hook_t expected = nullptr;
106 installed = android_fdtrack_compare_exchange_hook(&expected, &fd_hook);
107 }
Josh Gaodcc97c02020-12-09 14:01:13 -0800108
109 android_fdtrack_set_globally_enabled(true);
Josh Gao97271922019-11-06 13:15:00 -0800110}
111
112__attribute__((destructor)) static void dtor() {
113 if (installed) {
114 android_fdtrack_hook_t expected = &fd_hook;
115 android_fdtrack_compare_exchange_hook(&expected, nullptr);
116 }
117}
118
119FdEntry* GetFdEntry(int fd) {
120 if (fd >= 0 && fd < static_cast<int>(kFdTableSize)) {
121 return &stack_traces[fd];
122 }
123 return nullptr;
124}
125
126static void fd_hook(android_fdtrack_event* event) {
127 if (event->type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
128 if (FdEntry* entry = GetFdEntry(event->fd); entry) {
129 std::lock_guard<std::mutex> lock(entry->mutex);
130 entry->backtrace.clear();
Christopher Ferris459eecb2022-01-07 13:38:10 -0800131
132 std::unique_ptr<unwindstack::Regs> regs(unwindstack::Regs::CreateFromLocal());
133 unwindstack::RegsGetLocal(regs.get());
134 unwindstack::Unwinder unwinder(kStackDepth, &Maps(), regs.get(), ProcessMemory());
135 unwinder.Unwind(&kSkipFdtrackLib);
136 entry->backtrace = unwinder.ConsumeFrames();
Josh Gao97271922019-11-06 13:15:00 -0800137 }
138 } else if (event->type == ANDROID_FDTRACK_EVENT_TYPE_CLOSE) {
139 if (FdEntry* entry = GetFdEntry(event->fd); entry) {
140 std::lock_guard<std::mutex> lock(entry->mutex);
141 entry->backtrace.clear();
142 }
143 }
144}
145
Josh Gaoad8f02d2020-01-28 13:54:00 -0800146void fdtrack_iterate(fdtrack_callback_t callback, void* arg) {
Josh Gao97271922019-11-06 13:15:00 -0800147 bool prev = android_fdtrack_set_enabled(false);
Josh Gaoad8f02d2020-01-28 13:54:00 -0800148
Josh Gao97271922019-11-06 13:15:00 -0800149 for (int fd = 0; fd < static_cast<int>(stack_traces.size()); ++fd) {
Josh Gaoad8f02d2020-01-28 13:54:00 -0800150 const char* function_names[kStackDepth];
151 uint64_t function_offsets[kStackDepth];
Josh Gao97271922019-11-06 13:15:00 -0800152 FdEntry* entry = GetFdEntry(fd);
153 if (!entry) {
154 continue;
155 }
156
Josh Gao50955c42020-01-28 14:10:19 -0800157 if (!entry->mutex.try_lock()) {
158 async_safe_format_log(ANDROID_LOG_WARN, "fdtrack", "fd %d locked, skipping", fd);
159 continue;
160 }
161
Josh Gao97271922019-11-06 13:15:00 -0800162 if (entry->backtrace.empty()) {
Josh Gaoad8f02d2020-01-28 13:54:00 -0800163 entry->mutex.unlock();
164 continue;
165 } else if (entry->backtrace.size() < 2) {
166 async_safe_format_log(ANDROID_LOG_WARN, "fdtrack", "fd %d missing frames: size = %zu", fd,
167 entry->backtrace.size());
168
169 entry->mutex.unlock();
Josh Gao97271922019-11-06 13:15:00 -0800170 continue;
171 }
172
Christopher Ferris459eecb2022-01-07 13:38:10 -0800173 for (size_t i = 0; i < entry->backtrace.size(); ++i) {
174 function_names[i] = entry->backtrace[i].function_name.c_str();
175 function_offsets[i] = entry->backtrace[i].function_offset;
Josh Gao97271922019-11-06 13:15:00 -0800176 }
Josh Gao50955c42020-01-28 14:10:19 -0800177
Christopher Ferris459eecb2022-01-07 13:38:10 -0800178 bool should_continue =
179 callback(fd, function_names, function_offsets, entry->backtrace.size(), arg);
Josh Gaoad8f02d2020-01-28 13:54:00 -0800180
Josh Gao50955c42020-01-28 14:10:19 -0800181 entry->mutex.unlock();
Josh Gaoad8f02d2020-01-28 13:54:00 -0800182
183 if (!should_continue) {
184 break;
185 }
Josh Gao97271922019-11-06 13:15:00 -0800186 }
Josh Gaoad8f02d2020-01-28 13:54:00 -0800187
Josh Gao97271922019-11-06 13:15:00 -0800188 android_fdtrack_set_enabled(prev);
189}
Josh Gaoad8f02d2020-01-28 13:54:00 -0800190
Josh Gao1cb36812021-03-11 21:11:37 -0800191static size_t hash_stack(const char* const* function_names, const uint64_t* function_offsets,
192 size_t stack_depth) {
193 size_t hash = 0;
194 for (size_t i = 0; i < stack_depth; ++i) {
195 // To future maintainers: if a libc++ update ever makes this invalid, replace this with +.
196 hash = std::__hash_combine(hash, std::hash<std::string_view>()(function_names[i]));
197 hash = std::__hash_combine(hash, std::hash<uint64_t>()(function_offsets[i]));
198 }
199 return hash;
200}
201
202static void fdtrack_dump_impl(bool fatal) {
Josh Gaoad8f02d2020-01-28 13:54:00 -0800203 if (!installed) {
204 async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack not installed");
205 } else {
206 async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack dumping...");
207 }
208
Josh Gao1cb36812021-03-11 21:11:37 -0800209 // If we're aborting, identify the most common stack in the hopes that it's the culprit,
210 // and emit that in the abort message so crash reporting can separate different fd leaks out.
211 // This is horrible and quadratic, but we need to avoid allocation since this can happen in
212 // response to a signal generated asynchronously. We're only going to dump 1k fds by default,
213 // and we're about to blow up the entire system, so this isn't too expensive.
214 struct StackInfo {
215 size_t hash = 0;
216 size_t count = 0;
217
218 size_t stack_depth = 0;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800219 const char* function_names[kStackDepth];
220 uint64_t function_offsets[kStackDepth];
Josh Gao1cb36812021-03-11 21:11:37 -0800221 };
222 struct StackList {
223 size_t count = 0;
224 std::array<StackInfo, 128> data;
225 };
226 static StackList stacks;
227
Josh Gaoad8f02d2020-01-28 13:54:00 -0800228 fdtrack_iterate(
Josh Gao1cb36812021-03-11 21:11:37 -0800229 [](int fd, const char* const* function_names, const uint64_t* function_offsets,
230 size_t stack_depth, void* stacks_ptr) {
231 auto stacks = static_cast<StackList*>(stacks_ptr);
Josh Gaoad8f02d2020-01-28 13:54:00 -0800232 uint64_t fdsan_owner = android_fdsan_get_owner_tag(fd);
233 if (fdsan_owner != 0) {
Yuxian Xu3a5ddd72020-04-09 10:35:37 +0800234 async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (owner = 0x%" PRIx64 ")", fd,
Josh Gaoad8f02d2020-01-28 13:54:00 -0800235 fdsan_owner);
236 } else {
237 async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (unowned)", fd);
238 }
239
Josh Gao1cb36812021-03-11 21:11:37 -0800240 for (size_t i = 0; i < stack_depth; ++i) {
Josh Gaoad8f02d2020-01-28 13:54:00 -0800241 async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", " %zu: %s+%" PRIu64, i,
242 function_names[i], function_offsets[i]);
243 }
244
Josh Gao1cb36812021-03-11 21:11:37 -0800245 if (stacks) {
246 size_t hash = hash_stack(function_names, function_offsets, stack_depth);
247 bool found_stack = false;
248 for (size_t i = 0; i < stacks->count; ++i) {
249 if (stacks->data[i].hash == hash) {
250 ++stacks->data[i].count;
251 found_stack = true;
252 break;
253 }
254 }
255
256 if (!found_stack) {
257 if (stacks->count < stacks->data.size()) {
258 auto& stack = stacks->data[stacks->count++];
259 stack.hash = hash;
260 stack.count = 1;
261 stack.stack_depth = stack_depth;
262 for (size_t i = 0; i < stack_depth; ++i) {
263 stack.function_names[i] = function_names[i];
264 stack.function_offsets[i] = function_offsets[i];
265 }
266 }
267 }
268 }
269
Josh Gaoad8f02d2020-01-28 13:54:00 -0800270 return true;
271 },
Josh Gao1cb36812021-03-11 21:11:37 -0800272 fatal ? &stacks : nullptr);
273
274 if (fatal) {
275 // Find the most common stack.
276 size_t max = 0;
277 StackInfo* stack = nullptr;
278 for (size_t i = 0; i < stacks.count; ++i) {
279 if (stacks.data[i].count > max) {
280 stack = &stacks.data[i];
281 max = stack->count;
282 }
283 }
284
285 static char buf[1024];
286
287 if (!stack) {
288 async_safe_format_buffer(buf, sizeof(buf),
289 "aborting due to fd leak: failed to find most common stack");
290 } else {
291 char* p = buf;
292 p += async_safe_format_buffer(buf, sizeof(buf),
293 "aborting due to fd leak: most common stack =\n");
294
295 for (size_t i = 0; i < stack->stack_depth; ++i) {
296 ssize_t bytes_left = buf + sizeof(buf) - p;
297 if (bytes_left > 0) {
298 p += async_safe_format_buffer(p, buf + sizeof(buf) - p, " %zu: %s+%" PRIu64 "\n", i,
299 stack->function_names[i], stack->function_offsets[i]);
300 }
301 }
302 }
303
304 android_set_abort_message(buf);
305
306 // Abort on a different thread to avoid ART dumping runtime stacks.
307 std::thread([]() { abort(); }).join();
308 }
309}
310
311void fdtrack_dump() {
312 fdtrack_dump_impl(false);
313}
314
315void fdtrack_dump_fatal() {
316 fdtrack_dump_impl(true);
Josh Gaoad8f02d2020-01-28 13:54:00 -0800317}