blob: 67b3a625c14a8d244db86d30fd2deda9e3ad53f8 [file] [log] [blame]
Josh Gaof6e5b582018-06-01 15:30:54 -07001/*
2 * Copyright (C) 2018 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 <android/fdsan.h>
30
31#include <errno.h>
32#include <inttypes.h>
Josh Gaofe380882018-07-23 18:36:16 -070033#include <signal.h>
Josh Gaof6e5b582018-06-01 15:30:54 -070034#include <stdarg.h>
35#include <stdatomic.h>
36#include <string.h>
37#include <sys/cdefs.h>
38#include <sys/mman.h>
39#include <sys/syscall.h>
40#include <unistd.h>
41
42#include <async_safe/log.h>
43#include <sys/system_properties.h>
44
45#include "private/bionic_globals.h"
46#include "pthread_internal.h"
47
48extern "C" int ___close(int fd);
49pid_t __get_cached_pid();
50
51static constexpr const char* kFdsanPropertyName = "debug.fdsan";
52
Josh Gaoe6dab7b2018-08-06 18:47:29 -070053template<size_t inline_fds>
54FdEntry* FdTableImpl<inline_fds>::at(size_t idx) {
55 if (idx < inline_fds) {
56 return &entries[idx];
57 }
58
59 // Try to create the overflow table ourselves.
60 FdTableOverflow* local_overflow = atomic_load(&overflow);
61 if (__predict_false(!local_overflow)) {
62 struct rlimit rlim = { .rlim_max = 32768 };
63 getrlimit(RLIMIT_NOFILE, &rlim);
64 rlim_t max = rlim.rlim_max;
65
66 if (max == RLIM_INFINITY) {
67 // This isn't actually possible (the kernel has a hard limit), but just
68 // in case...
69 max = 32768;
70 }
71
72 if (idx > max) {
73 // This can happen if an fd is created and then the rlimit is lowered.
74 // In this case, just return nullptr and ignore the fd.
75 return nullptr;
76 }
77
78 size_t required_count = max - inline_fds;
79 size_t required_size = sizeof(FdTableOverflow) + required_count * sizeof(FdEntry);
80 size_t aligned_size = __BIONIC_ALIGN(required_size, PAGE_SIZE);
81 size_t aligned_count = (aligned_size - sizeof(FdTableOverflow)) / sizeof(FdEntry);
82
83 void* allocation =
84 mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
85 if (allocation == MAP_FAILED) {
86 async_safe_fatal("fdsan: mmap failed: %s", strerror(errno));
87 }
88
89 FdTableOverflow* new_overflow = reinterpret_cast<FdTableOverflow*>(allocation);
90 new_overflow->len = aligned_count;
91
92 if (atomic_compare_exchange_strong(&overflow, &local_overflow, new_overflow)) {
93 local_overflow = new_overflow;
94 } else {
95 // Someone beat us to it. Deallocate and use theirs.
96 munmap(allocation, aligned_size);
97 }
98 }
99
100 size_t offset = idx - inline_fds;
101 if (local_overflow->len < offset) {
102 return nullptr;
103 }
104 return &local_overflow->entries[offset];
105}
106
Josh Gaof6e5b582018-06-01 15:30:54 -0700107void __libc_init_fdsan() {
Josh Gao4b7c1cc2018-08-06 14:57:30 -0700108 constexpr auto default_level = ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE;
Josh Gaof6e5b582018-06-01 15:30:54 -0700109 const prop_info* pi = __system_property_find(kFdsanPropertyName);
110 if (!pi) {
Josh Gao4b7c1cc2018-08-06 14:57:30 -0700111 android_fdsan_set_error_level(default_level);
Josh Gaof6e5b582018-06-01 15:30:54 -0700112 return;
113 }
114 __system_property_read_callback(
115 pi,
116 [](void*, const char*, const char* value, uint32_t) {
117 if (strcasecmp(value, "1") == 0 || strcasecmp(value, "fatal") == 0) {
118 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_FATAL);
119 } else if (strcasecmp(value, "warn") == 0) {
120 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS);
121 } else if (strcasecmp(value, "warn_once") == 0) {
122 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
123 } else {
124 if (strlen(value) != 0 && strcasecmp(value, "0") != 0) {
125 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
126 "debug.fdsan set to unknown value '%s', disabling", value);
127 }
Josh Gao4b7c1cc2018-08-06 14:57:30 -0700128 android_fdsan_set_error_level(default_level);
Josh Gaof6e5b582018-06-01 15:30:54 -0700129 }
130 },
131 nullptr);
132}
133
Josh Gaoe6dab7b2018-08-06 18:47:29 -0700134static FdTable* GetFdTable() {
Josh Gaof6e5b582018-06-01 15:30:54 -0700135 if (!__libc_shared_globals) {
136 return nullptr;
137 }
138
139 return &__libc_shared_globals->fd_table;
140}
141
Josh Gaoe16082f2018-08-06 18:48:52 -0700142// Exposed to the platform to allow crash_dump to print out the fd table.
143extern "C" void* android_fdsan_get_fd_table() {
144 return GetFdTable();
145}
146
Josh Gaof6e5b582018-06-01 15:30:54 -0700147static FdEntry* GetFdEntry(int fd) {
148 if (fd < 0) {
149 return nullptr;
150 }
151
152 auto* fd_table = GetFdTable();
153 if (!fd_table) {
154 return nullptr;
155 }
156
157 return fd_table->at(fd);
158}
159
160__printflike(1, 0) static void fdsan_error(const char* fmt, ...) {
161 auto* fd_table = GetFdTable();
162 if (!fd_table) {
163 return;
164 }
165
166 auto error_level = atomic_load(&fd_table->error_level);
167 if (error_level == ANDROID_FDSAN_ERROR_LEVEL_DISABLED) {
168 return;
169 }
170
171 // Lots of code will (sensibly) fork, blindly call close on all of their fds,
172 // and then exec. Compare our cached pid value against the real one to detect
173 // this scenario and permit it.
174 pid_t cached_pid = __get_cached_pid();
175 if (cached_pid == 0 || cached_pid != syscall(__NR_getpid)) {
176 return;
177 }
178
179 va_list va;
180 va_start(va, fmt);
Josh Gaofe380882018-07-23 18:36:16 -0700181 if (error_level == ANDROID_FDSAN_ERROR_LEVEL_FATAL) {
182 async_safe_fatal_va_list("fdsan", fmt, va);
183 } else {
184 async_safe_format_log_va_list(ANDROID_LOG_ERROR, "fdsan", fmt, va);
185 }
Josh Gaof6e5b582018-06-01 15:30:54 -0700186 va_end(va);
187
188 switch (error_level) {
189 case ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE:
190 atomic_compare_exchange_strong(&fd_table->error_level, &error_level,
191 ANDROID_FDSAN_ERROR_LEVEL_DISABLED);
George Burgess IVfa5410f2018-08-13 17:44:06 -0700192 __BIONIC_FALLTHROUGH;
Josh Gaofe380882018-07-23 18:36:16 -0700193 case ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS:
194 // DEBUGGER_SIGNAL
195 raise(__SIGRTMIN + 3);
Josh Gaof6e5b582018-06-01 15:30:54 -0700196 break;
197
198 case ANDROID_FDSAN_ERROR_LEVEL_FATAL:
199 abort();
200
201 case ANDROID_FDSAN_ERROR_LEVEL_DISABLED:
Josh Gaof6e5b582018-06-01 15:30:54 -0700202 break;
203 }
204}
205
206uint64_t android_fdsan_create_owner_tag(android_fdsan_owner_type type, uint64_t tag) {
207 if (tag == 0) {
208 return 0;
209 }
210
211 if (__predict_false((type & 0xff) != type)) {
212 async_safe_fatal("invalid android_fdsan_owner_type value: %x", type);
213 }
214
215 uint64_t result = static_cast<uint64_t>(type) << 56;
216 uint64_t mask = (static_cast<uint64_t>(1) << 56) - 1;
217 result |= tag & mask;
218 return result;
219}
220
221static const char* __tag_to_type(uint64_t tag) {
222 uint64_t type = tag >> 56;
223 switch (type) {
224 case ANDROID_FDSAN_OWNER_TYPE_FILE:
225 return "FILE*";
226 case ANDROID_FDSAN_OWNER_TYPE_DIR:
227 return "DIR*";
228 case ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD:
229 return "unique_fd";
230 case ANDROID_FDSAN_OWNER_TYPE_FILEINPUTSTREAM:
231 return "FileInputStream";
232 case ANDROID_FDSAN_OWNER_TYPE_FILEOUTPUTSTREAM:
233 return "FileOutputStream";
234 case ANDROID_FDSAN_OWNER_TYPE_RANDOMACCESSFILE:
235 return "RandomAccessFile";
236 case ANDROID_FDSAN_OWNER_TYPE_PARCELFILEDESCRIPTOR:
237 return "ParcelFileDescriptor";
Josh Gao27cc4bc2018-08-22 12:40:08 -0700238 case ANDROID_FDSAN_OWNER_TYPE_SQLITE:
239 return "sqlite";
Josh Gaof6e5b582018-06-01 15:30:54 -0700240
241 case ANDROID_FDSAN_OWNER_TYPE_GENERIC_00:
242 default:
243 return "native object of unknown type";
244
245 case ANDROID_FDSAN_OWNER_TYPE_GENERIC_FF:
246 // If bits 48 to 56 are set, this is a sign-extended generic native pointer
247 uint64_t high_bits = tag >> 48;
248 if (high_bits == (1 << 16) - 1) {
249 return "native object of unknown type";
250 }
251
252 return "Java object of unknown type";
253 }
254}
255
256static uint64_t __tag_to_owner(uint64_t tag) {
Josh Gao08b7a402018-08-03 14:31:37 -0700257 // Lop off the most significant byte and sign extend.
258 return static_cast<uint64_t>(static_cast<int64_t>(tag << 8) >> 8);
Josh Gaof6e5b582018-06-01 15:30:54 -0700259}
260
261int android_fdsan_close_with_tag(int fd, uint64_t expected_tag) {
262 FdEntry* fde = GetFdEntry(fd);
263 if (!fde) {
264 return ___close(fd);
265 }
266
267 uint64_t tag = expected_tag;
268 if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, 0)) {
269 const char* expected_type = __tag_to_type(expected_tag);
270 uint64_t expected_owner = __tag_to_owner(expected_tag);
271 const char* actual_type = __tag_to_type(tag);
272 uint64_t actual_owner = __tag_to_owner(tag);
273 if (expected_tag && tag) {
Josh Gao08b7a402018-08-03 14:31:37 -0700274 fdsan_error(
275 "attempted to close file descriptor %d, "
276 "expected to be owned by %s 0x%" PRIx64 ", actually owned by %s 0x%" PRIx64,
277 fd, expected_type, expected_owner, actual_type, actual_owner);
Josh Gaof6e5b582018-06-01 15:30:54 -0700278 } else if (expected_tag && !tag) {
Josh Gao08b7a402018-08-03 14:31:37 -0700279 fdsan_error(
280 "attempted to close file descriptor %d, "
281 "expected to be owned by %s 0x%" PRIx64 ", actually unowned",
282 fd, expected_type, expected_owner);
Josh Gaof6e5b582018-06-01 15:30:54 -0700283 } else if (!expected_tag && tag) {
284 fdsan_error(
Josh Gao08b7a402018-08-03 14:31:37 -0700285 "attempted to close file descriptor %d, "
286 "expected to be unowned, actually owned by %s 0x%" PRIx64,
Josh Gaof6e5b582018-06-01 15:30:54 -0700287 fd, actual_type, actual_owner);
288 } else if (!expected_tag && !tag) {
289 // This should never happen: our CAS failed, but expected == actual?
Josh Gao08b7a402018-08-03 14:31:37 -0700290 async_safe_fatal("fdsan atomic_compare_exchange_strong failed unexpectedly while closing");
Josh Gaof6e5b582018-06-01 15:30:54 -0700291 }
292 }
293
294 int rc = ___close(fd);
295 // If we were expecting to close with a tag, abort on EBADF.
296 if (expected_tag && rc == -1 && errno == EBADF) {
297 fdsan_error("double-close of file descriptor %d detected", fd);
298 }
299 return rc;
300}
301
302void android_fdsan_exchange_owner_tag(int fd, uint64_t expected_tag, uint64_t new_tag) {
303 FdEntry* fde = GetFdEntry(fd);
304 if (!fde) {
305 return;
306 }
307
308 uint64_t tag = expected_tag;
309 if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, new_tag)) {
Josh Gao08b7a402018-08-03 14:31:37 -0700310 if (expected_tag && tag) {
Josh Gaof6e5b582018-06-01 15:30:54 -0700311 fdsan_error(
Josh Gao08b7a402018-08-03 14:31:37 -0700312 "failed to exchange ownership of file descriptor: fd %d is "
313 "owned by %s 0x%" PRIx64 ", was expected to be owned by %s 0x%" PRIx64,
314 fd, __tag_to_type(tag), __tag_to_owner(tag), __tag_to_type(expected_tag),
315 __tag_to_owner(expected_tag));
316 } else if (expected_tag && !tag) {
Josh Gaof6e5b582018-06-01 15:30:54 -0700317 fdsan_error(
Josh Gao08b7a402018-08-03 14:31:37 -0700318 "failed to exchange ownership of file descriptor: fd %d is "
319 "unowned, was expected to be owned by %s 0x%" PRIx64,
Josh Gaof6e5b582018-06-01 15:30:54 -0700320 fd, __tag_to_type(expected_tag), __tag_to_owner(expected_tag));
Josh Gao08b7a402018-08-03 14:31:37 -0700321 } else if (!expected_tag && tag) {
322 fdsan_error(
323 "failed to exchange ownership of file descriptor: fd %d is "
324 "owned by %s 0x%" PRIx64 ", was expected to be unowned",
325 fd, __tag_to_type(tag), __tag_to_owner(tag));
326 } else if (!expected_tag && !tag) {
327 // This should never happen: our CAS failed, but expected == actual?
328 async_safe_fatal(
329 "fdsan atomic_compare_exchange_strong failed unexpectedly while exchanging owner tag");
Josh Gaof6e5b582018-06-01 15:30:54 -0700330 }
331 }
332}
333
334android_fdsan_error_level android_fdsan_get_error_level() {
335 auto* fd_table = GetFdTable();
336 if (!fd_table) {
337 async_safe_fatal("attempted to get fdsan error level before libc initialization?");
338 }
339
340 return fd_table->error_level;
341}
342
343android_fdsan_error_level android_fdsan_set_error_level(android_fdsan_error_level new_level) {
344 auto* fd_table = GetFdTable();
345 if (!fd_table) {
346 async_safe_fatal("attempted to get fdsan error level before libc initialization?");
347 }
348
349 return atomic_exchange(&fd_table->error_level, new_level);
350}
351
352int close(int fd) {
353 int rc = android_fdsan_close_with_tag(fd, 0);
354 if (rc == -1 && errno == EINTR) {
355 return 0;
356 }
357 return rc;
358}