1 /*
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>
33 #include <signal.h>
34 #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 <platform/bionic/reserved_signals.h>
44 #include <sys/system_properties.h>
45 
46 #include "private/bionic_fdtrack.h"
47 #include "private/bionic_globals.h"
48 #include "private/bionic_inline_raise.h"
49 #include "pthread_internal.h"
50 
51 extern "C" int __close(int fd);
52 pid_t __get_cached_pid();
53 
54 static constexpr const char* kFdsanPropertyName = "debug.fdsan";
55 
56 template<size_t inline_fds>
at(size_t idx)57 FdEntry* FdTableImpl<inline_fds>::at(size_t idx) {
58   if (idx < inline_fds) {
59     return &entries[idx];
60   }
61 
62   // Try to create the overflow table ourselves.
63   FdTableOverflow* local_overflow = atomic_load(&overflow);
64   if (__predict_false(!local_overflow)) {
65     struct rlimit rlim = { .rlim_max = 32768 };
66     getrlimit(RLIMIT_NOFILE, &rlim);
67     rlim_t max = rlim.rlim_max;
68 
69     if (max == RLIM_INFINITY) {
70       // This isn't actually possible (the kernel has a hard limit), but just
71       // in case...
72       max = 32768;
73     }
74 
75     if (idx > max) {
76       // This can happen if an fd is created and then the rlimit is lowered.
77       // In this case, just return nullptr and ignore the fd.
78       return nullptr;
79     }
80 
81     size_t required_count = max - inline_fds;
82     size_t required_size = sizeof(FdTableOverflow) + required_count * sizeof(FdEntry);
83     size_t aligned_size = __BIONIC_ALIGN(required_size, PAGE_SIZE);
84     size_t aligned_count = (aligned_size - sizeof(FdTableOverflow)) / sizeof(FdEntry);
85 
86     void* allocation =
87         mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
88     if (allocation == MAP_FAILED) {
89       async_safe_fatal("fdsan: mmap failed: %s", strerror(errno));
90     }
91 
92     FdTableOverflow* new_overflow = reinterpret_cast<FdTableOverflow*>(allocation);
93     new_overflow->len = aligned_count;
94 
95     if (atomic_compare_exchange_strong(&overflow, &local_overflow, new_overflow)) {
96       local_overflow = new_overflow;
97     } else {
98       // Someone beat us to it. Deallocate and use theirs.
99       munmap(allocation, aligned_size);
100     }
101   }
102 
103   size_t offset = idx - inline_fds;
104   if (local_overflow->len < offset) {
105     return nullptr;
106   }
107   return &local_overflow->entries[offset];
108 }
109 
__libc_init_fdsan()110 void __libc_init_fdsan() {
111   constexpr auto default_level = ANDROID_FDSAN_ERROR_LEVEL_FATAL;
112   android_fdsan_set_error_level_from_property(default_level);
113 }
114 
GetFdTable()115 static FdTable& GetFdTable() {
116   return __libc_shared_globals()->fd_table;
117 }
118 
119 // Exposed to the platform to allow crash_dump to print out the fd table.
android_fdsan_get_fd_table()120 extern "C" void* android_fdsan_get_fd_table() {
121   return &GetFdTable();
122 }
123 
GetFdEntry(int fd)124 static FdEntry* GetFdEntry(int fd) {
125   if (fd < 0) {
126     return nullptr;
127   }
128 
129   return GetFdTable().at(fd);
130 }
131 
fdsan_error(const char * fmt,...)132 __printflike(1, 0) static void fdsan_error(const char* fmt, ...) {
133   auto& fd_table = GetFdTable();
134 
135   auto error_level = atomic_load(&fd_table.error_level);
136   if (error_level == ANDROID_FDSAN_ERROR_LEVEL_DISABLED) {
137     return;
138   }
139 
140   struct {
141     size_t size;
142     char buf[512];
143   } abort_message;
144 
145   va_list va;
146   va_start(va, fmt);
147   if (error_level == ANDROID_FDSAN_ERROR_LEVEL_FATAL) {
148     async_safe_fatal_va_list("fdsan", fmt, va);
149   } else {
150     async_safe_format_log_va_list(ANDROID_LOG_ERROR, "fdsan", fmt, va);
151     va_end(va);
152     va_start(va, fmt);
153     size_t len =
154         async_safe_format_buffer_va_list(abort_message.buf, sizeof(abort_message.buf), fmt, va);
155     abort_message.size = len + sizeof(size_t);
156   }
157   va_end(va);
158 
159   switch (error_level) {
160     case ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE:
161       atomic_compare_exchange_strong(&fd_table.error_level, &error_level,
162                                      ANDROID_FDSAN_ERROR_LEVEL_DISABLED);
163       __BIONIC_FALLTHROUGH;
164     case ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS:
165       inline_raise(BIONIC_SIGNAL_DEBUGGER, &abort_message);
166       break;
167 
168     case ANDROID_FDSAN_ERROR_LEVEL_FATAL:
169       inline_raise(SIGABRT);
170       abort();
171 
172     case ANDROID_FDSAN_ERROR_LEVEL_DISABLED:
173       break;
174   }
175 }
176 
android_fdsan_create_owner_tag(android_fdsan_owner_type type,uint64_t tag)177 uint64_t android_fdsan_create_owner_tag(android_fdsan_owner_type type, uint64_t tag) {
178   if (tag == 0) {
179     return 0;
180   }
181 
182   if (__predict_false((type & 0xff) != type)) {
183     async_safe_fatal("invalid android_fdsan_owner_type value: %x", type);
184   }
185 
186   uint64_t result = static_cast<uint64_t>(type) << 56;
187   uint64_t mask = (static_cast<uint64_t>(1) << 56) - 1;
188   result |= tag & mask;
189   return result;
190 }
191 
android_fdsan_get_tag_type(uint64_t tag)192 const char* android_fdsan_get_tag_type(uint64_t tag) {
193   uint64_t type = tag >> 56;
194   switch (type) {
195     case ANDROID_FDSAN_OWNER_TYPE_FILE:
196       return "FILE*";
197     case ANDROID_FDSAN_OWNER_TYPE_DIR:
198       return "DIR*";
199     case ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD:
200       return "unique_fd";
201     case ANDROID_FDSAN_OWNER_TYPE_FILEINPUTSTREAM:
202       return "FileInputStream";
203     case ANDROID_FDSAN_OWNER_TYPE_FILEOUTPUTSTREAM:
204       return "FileOutputStream";
205     case ANDROID_FDSAN_OWNER_TYPE_RANDOMACCESSFILE:
206       return "RandomAccessFile";
207     case ANDROID_FDSAN_OWNER_TYPE_PARCELFILEDESCRIPTOR:
208       return "ParcelFileDescriptor";
209     case ANDROID_FDSAN_OWNER_TYPE_SQLITE:
210       return "sqlite";
211     case ANDROID_FDSAN_OWNER_TYPE_ART_FDFILE:
212       return "ART FdFile";
213     case ANDROID_FDSAN_OWNER_TYPE_DATAGRAMSOCKETIMPL:
214       return "DatagramSocketImpl";
215     case ANDROID_FDSAN_OWNER_TYPE_SOCKETIMPL:
216       return "SocketImpl";
217     case ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE:
218       return "ZipArchive";
219 
220     case ANDROID_FDSAN_OWNER_TYPE_GENERIC_00:
221     default:
222       return "native object of unknown type";
223 
224     case ANDROID_FDSAN_OWNER_TYPE_GENERIC_FF:
225       // If bits 48 to 56 are set, this is a sign-extended generic native pointer
226       uint64_t high_bits = tag >> 48;
227       if (high_bits == (1 << 16) - 1) {
228         return "native object of unknown type";
229       }
230 
231       return "Java object of unknown type";
232   }
233 }
234 
android_fdsan_get_tag_value(uint64_t tag)235 uint64_t android_fdsan_get_tag_value(uint64_t tag) {
236   // Lop off the most significant byte and sign extend.
237   return static_cast<uint64_t>(static_cast<int64_t>(tag << 8) >> 8);
238 }
239 
android_fdsan_close_with_tag(int fd,uint64_t expected_tag)240 int android_fdsan_close_with_tag(int fd, uint64_t expected_tag) {
241   if (__get_thread()->is_vforked()) {
242     return __close(fd);
243   }
244 
245   FDTRACK_CLOSE(fd);
246   FdEntry* fde = GetFdEntry(fd);
247   if (!fde) {
248     return __close(fd);
249   }
250 
251   uint64_t tag = expected_tag;
252   if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, 0)) {
253     const char* expected_type = android_fdsan_get_tag_type(expected_tag);
254     uint64_t expected_owner = android_fdsan_get_tag_value(expected_tag);
255     const char* actual_type = android_fdsan_get_tag_type(tag);
256     uint64_t actual_owner = android_fdsan_get_tag_value(tag);
257     if (expected_tag && tag) {
258       fdsan_error(
259           "attempted to close file descriptor %d, "
260           "expected to be owned by %s 0x%" PRIx64 ", actually owned by %s 0x%" PRIx64,
261           fd, expected_type, expected_owner, actual_type, actual_owner);
262     } else if (expected_tag && !tag) {
263       fdsan_error(
264           "attempted to close file descriptor %d, "
265           "expected to be owned by %s 0x%" PRIx64 ", actually unowned",
266           fd, expected_type, expected_owner);
267     } else if (!expected_tag && tag) {
268       fdsan_error(
269           "attempted to close file descriptor %d, "
270           "expected to be unowned, actually owned by %s 0x%" PRIx64,
271           fd, actual_type, actual_owner);
272     } else if (!expected_tag && !tag) {
273       // This should never happen: our CAS failed, but expected == actual?
274       async_safe_fatal("fdsan atomic_compare_exchange_strong failed unexpectedly while closing");
275     }
276   }
277 
278   int rc = __close(fd);
279   // If we were expecting to close with a tag, abort on EBADF.
280   if (expected_tag && rc == -1 && errno == EBADF) {
281     fdsan_error("double-close of file descriptor %d detected", fd);
282   }
283   return rc;
284 }
285 
android_fdsan_get_owner_tag(int fd)286 uint64_t android_fdsan_get_owner_tag(int fd) {
287   FdEntry* fde = GetFdEntry(fd);
288   if (!fde) {
289     return 0;
290   }
291   return fde->close_tag;
292 }
293 
android_fdsan_exchange_owner_tag(int fd,uint64_t expected_tag,uint64_t new_tag)294 void android_fdsan_exchange_owner_tag(int fd, uint64_t expected_tag, uint64_t new_tag) {
295   if (__get_thread()->is_vforked()) {
296     return;
297   }
298 
299   FdEntry* fde = GetFdEntry(fd);
300   if (!fde) {
301     return;
302   }
303 
304   uint64_t tag = expected_tag;
305   if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, new_tag)) {
306     if (expected_tag && tag) {
307       fdsan_error(
308           "failed to exchange ownership of file descriptor: fd %d is "
309           "owned by %s 0x%" PRIx64 ", was expected to be owned by %s 0x%" PRIx64,
310           fd, android_fdsan_get_tag_type(tag), android_fdsan_get_tag_value(tag),
311           android_fdsan_get_tag_type(expected_tag), android_fdsan_get_tag_value(expected_tag));
312     } else if (expected_tag && !tag) {
313       fdsan_error(
314           "failed to exchange ownership of file descriptor: fd %d is "
315           "unowned, was expected to be owned by %s 0x%" PRIx64,
316           fd, android_fdsan_get_tag_type(expected_tag), android_fdsan_get_tag_value(expected_tag));
317     } else if (!expected_tag && tag) {
318       fdsan_error(
319           "failed to exchange ownership of file descriptor: fd %d is "
320           "owned by %s 0x%" PRIx64 ", was expected to be unowned",
321           fd, android_fdsan_get_tag_type(tag), android_fdsan_get_tag_value(tag));
322     } else if (!expected_tag && !tag) {
323       // This should never happen: our CAS failed, but expected == actual?
324       async_safe_fatal(
325           "fdsan atomic_compare_exchange_strong failed unexpectedly while exchanging owner tag");
326     }
327   }
328 }
329 
android_fdsan_get_error_level()330 android_fdsan_error_level android_fdsan_get_error_level() {
331   return GetFdTable().error_level;
332 }
333 
android_fdsan_set_error_level(android_fdsan_error_level new_level)334 android_fdsan_error_level android_fdsan_set_error_level(android_fdsan_error_level new_level) {
335   if (__get_thread()->is_vforked()) {
336     return android_fdsan_get_error_level();
337   }
338 
339   return atomic_exchange(&GetFdTable().error_level, new_level);
340 }
341 
android_fdsan_set_error_level_from_property(android_fdsan_error_level default_level)342 android_fdsan_error_level android_fdsan_set_error_level_from_property(
343     android_fdsan_error_level default_level) {
344   const prop_info* pi = __system_property_find(kFdsanPropertyName);
345   if (!pi) {
346     return android_fdsan_set_error_level(default_level);
347   }
348 
349   struct callback_data {
350     android_fdsan_error_level default_value;
351     android_fdsan_error_level result;
352   };
353 
354   callback_data data;
355   data.default_value = default_level;
356 
357   __system_property_read_callback(
358       pi,
359       [](void* arg, const char*, const char* value, uint32_t) {
360         callback_data* data = static_cast<callback_data*>(arg);
361 
362         if (strcasecmp(value, "1") == 0 || strcasecmp(value, "fatal") == 0) {
363           data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_FATAL);
364         } else if (strcasecmp(value, "warn") == 0) {
365           data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS);
366         } else if (strcasecmp(value, "warn_once") == 0) {
367           data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
368         } else {
369           if (strlen(value) != 0 && strcasecmp(value, "0") != 0) {
370             async_safe_format_log(ANDROID_LOG_ERROR, "libc",
371                                   "debug.fdsan set to unknown value '%s', disabling", value);
372           }
373           data->result = android_fdsan_set_error_level(data->default_value);
374         }
375       },
376       &data);
377 
378   return data.result;
379 }
380 
close(int fd)381 int close(int fd) {
382   int rc = android_fdsan_close_with_tag(fd, 0);
383   if (rc == -1 && errno == EINTR) {
384     return 0;
385   }
386   return rc;
387 }
388