1 //===-- dfsan.cpp ---------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file is a part of DataFlowSanitizer. 10 // 11 // DataFlowSanitizer runtime. This file defines the public interface to 12 // DataFlowSanitizer as well as the definition of certain runtime functions 13 // called automatically by the compiler (specifically the instrumentation pass 14 // in llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp). 15 // 16 // The public interface is defined in include/sanitizer/dfsan_interface.h whose 17 // functions are prefixed dfsan_ while the compiler interface functions are 18 // prefixed __dfsan_. 19 //===----------------------------------------------------------------------===// 20 21 #include "dfsan/dfsan.h" 22 23 #include "dfsan/dfsan_thread.h" 24 #include "sanitizer_common/sanitizer_atomic.h" 25 #include "sanitizer_common/sanitizer_common.h" 26 #include "sanitizer_common/sanitizer_file.h" 27 #include "sanitizer_common/sanitizer_flag_parser.h" 28 #include "sanitizer_common/sanitizer_flags.h" 29 #include "sanitizer_common/sanitizer_internal_defs.h" 30 #include "sanitizer_common/sanitizer_libc.h" 31 #include "sanitizer_common/sanitizer_stacktrace.h" 32 33 using namespace __dfsan; 34 35 typedef atomic_uint16_t atomic_dfsan_label; 36 static const dfsan_label kInitializingLabel = -1; 37 38 static const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8); 39 40 static atomic_dfsan_label __dfsan_last_label; 41 static dfsan_label_info __dfsan_label_info[kNumLabels]; 42 43 Flags __dfsan::flags_data; 44 45 // The size of TLS variables. These constants must be kept in sync with the ones 46 // in DataFlowSanitizer.cpp. 47 static const int kDFsanArgTlsSize = 800; 48 static const int kDFsanRetvalTlsSize = 800; 49 50 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64 51 __dfsan_retval_tls[kDFsanRetvalTlsSize / sizeof(u64)]; 52 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64 53 __dfsan_arg_tls[kDFsanArgTlsSize / sizeof(u64)]; 54 55 SANITIZER_INTERFACE_ATTRIBUTE uptr __dfsan_shadow_ptr_mask; 56 57 // On Linux/x86_64, memory is laid out as follows: 58 // 59 // +--------------------+ 0x800000000000 (top of memory) 60 // | application memory | 61 // +--------------------+ 0x700000008000 (kAppAddr) 62 // | | 63 // | unused | 64 // | | 65 // +--------------------+ 0x200200000000 (kUnusedAddr) 66 // | union table | 67 // +--------------------+ 0x200000000000 (kUnionTableAddr) 68 // | shadow memory | 69 // +--------------------+ 0x000000010000 (kShadowAddr) 70 // | reserved by kernel | 71 // +--------------------+ 0x000000000000 72 // 73 // To derive a shadow memory address from an application memory address, 74 // bits 44-46 are cleared to bring the address into the range 75 // [0x000000008000,0x100000000000). Then the address is shifted left by 1 to 76 // account for the double byte representation of shadow labels and move the 77 // address into the shadow memory range. See the function shadow_for below. 78 79 // On Linux/MIPS64, memory is laid out as follows: 80 // 81 // +--------------------+ 0x10000000000 (top of memory) 82 // | application memory | 83 // +--------------------+ 0xF000008000 (kAppAddr) 84 // | | 85 // | unused | 86 // | | 87 // +--------------------+ 0x2200000000 (kUnusedAddr) 88 // | union table | 89 // +--------------------+ 0x2000000000 (kUnionTableAddr) 90 // | shadow memory | 91 // +--------------------+ 0x0000010000 (kShadowAddr) 92 // | reserved by kernel | 93 // +--------------------+ 0x0000000000 94 95 // On Linux/AArch64 (39-bit VMA), memory is laid out as follow: 96 // 97 // +--------------------+ 0x8000000000 (top of memory) 98 // | application memory | 99 // +--------------------+ 0x7000008000 (kAppAddr) 100 // | | 101 // | unused | 102 // | | 103 // +--------------------+ 0x1200000000 (kUnusedAddr) 104 // | union table | 105 // +--------------------+ 0x1000000000 (kUnionTableAddr) 106 // | shadow memory | 107 // +--------------------+ 0x0000010000 (kShadowAddr) 108 // | reserved by kernel | 109 // +--------------------+ 0x0000000000 110 111 // On Linux/AArch64 (42-bit VMA), memory is laid out as follow: 112 // 113 // +--------------------+ 0x40000000000 (top of memory) 114 // | application memory | 115 // +--------------------+ 0x3ff00008000 (kAppAddr) 116 // | | 117 // | unused | 118 // | | 119 // +--------------------+ 0x1200000000 (kUnusedAddr) 120 // | union table | 121 // +--------------------+ 0x8000000000 (kUnionTableAddr) 122 // | shadow memory | 123 // +--------------------+ 0x0000010000 (kShadowAddr) 124 // | reserved by kernel | 125 // +--------------------+ 0x0000000000 126 127 // On Linux/AArch64 (48-bit VMA), memory is laid out as follow: 128 // 129 // +--------------------+ 0x1000000000000 (top of memory) 130 // | application memory | 131 // +--------------------+ 0xffff00008000 (kAppAddr) 132 // | unused | 133 // +--------------------+ 0xaaaab0000000 (top of PIE address) 134 // | application PIE | 135 // +--------------------+ 0xaaaaa0000000 (top of PIE address) 136 // | | 137 // | unused | 138 // | | 139 // +--------------------+ 0x1200000000 (kUnusedAddr) 140 // | union table | 141 // +--------------------+ 0x8000000000 (kUnionTableAddr) 142 // | shadow memory | 143 // +--------------------+ 0x0000010000 (kShadowAddr) 144 // | reserved by kernel | 145 // +--------------------+ 0x0000000000 146 147 typedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels]; 148 149 #ifdef DFSAN_RUNTIME_VMA 150 // Runtime detected VMA size. 151 int __dfsan::vmaSize; 152 #endif 153 154 static uptr UnusedAddr() { 155 return UnionTableAddr() + sizeof(dfsan_union_table_t); 156 } 157 158 static atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) { 159 return &(*(dfsan_union_table_t *) UnionTableAddr())[l1][l2]; 160 } 161 162 // Checks we do not run out of labels. 163 static void dfsan_check_label(dfsan_label label) { 164 if (label == kInitializingLabel) { 165 Report("FATAL: DataFlowSanitizer: out of labels\n"); 166 Die(); 167 } 168 } 169 170 // Resolves the union of two unequal labels. Nonequality is a precondition for 171 // this function (the instrumentation pass inlines the equality test). 172 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 173 dfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) { 174 DCHECK_NE(l1, l2); 175 176 if (l1 == 0) 177 return l2; 178 if (l2 == 0) 179 return l1; 180 181 // If no labels have been created, yet l1 and l2 are non-zero, we are using 182 // fast16labels mode. 183 if (atomic_load(&__dfsan_last_label, memory_order_relaxed) == 0) 184 return l1 | l2; 185 186 if (l1 > l2) 187 Swap(l1, l2); 188 189 atomic_dfsan_label *table_ent = union_table(l1, l2); 190 // We need to deal with the case where two threads concurrently request 191 // a union of the same pair of labels. If the table entry is uninitialized, 192 // (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel 193 // (i.e. -1) to mark that we are initializing it. 194 dfsan_label label = 0; 195 if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel, 196 memory_order_acquire)) { 197 // Check whether l2 subsumes l1. We don't need to check whether l1 198 // subsumes l2 because we are guaranteed here that l1 < l2, and (at least 199 // in the cases we are interested in) a label may only subsume labels 200 // created earlier (i.e. with a lower numerical value). 201 if (__dfsan_label_info[l2].l1 == l1 || 202 __dfsan_label_info[l2].l2 == l1) { 203 label = l2; 204 } else { 205 label = 206 atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; 207 dfsan_check_label(label); 208 __dfsan_label_info[label].l1 = l1; 209 __dfsan_label_info[label].l2 = l2; 210 } 211 atomic_store(table_ent, label, memory_order_release); 212 } else if (label == kInitializingLabel) { 213 // Another thread is initializing the entry. Wait until it is finished. 214 do { 215 internal_sched_yield(); 216 label = atomic_load(table_ent, memory_order_acquire); 217 } while (label == kInitializingLabel); 218 } 219 return label; 220 } 221 222 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 223 dfsan_label __dfsan_union_load(const dfsan_label *ls, uptr n) { 224 dfsan_label label = ls[0]; 225 for (uptr i = 1; i != n; ++i) { 226 dfsan_label next_label = ls[i]; 227 if (label != next_label) 228 label = __dfsan_union(label, next_label); 229 } 230 return label; 231 } 232 233 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 234 dfsan_label __dfsan_union_load_fast16labels(const dfsan_label *ls, uptr n) { 235 dfsan_label label = ls[0]; 236 for (uptr i = 1; i != n; ++i) 237 label |= ls[i]; 238 return label; 239 } 240 241 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 242 void __dfsan_unimplemented(char *fname) { 243 if (flags().warn_unimplemented) 244 Report("WARNING: DataFlowSanitizer: call to uninstrumented function %s\n", 245 fname); 246 } 247 248 // Use '-mllvm -dfsan-debug-nonzero-labels' and break on this function 249 // to try to figure out where labels are being introduced in a nominally 250 // label-free program. 251 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_nonzero_label() { 252 if (flags().warn_nonzero_labels) 253 Report("WARNING: DataFlowSanitizer: saw nonzero label\n"); 254 } 255 256 // Indirect call to an uninstrumented vararg function. We don't have a way of 257 // handling these at the moment. 258 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void 259 __dfsan_vararg_wrapper(const char *fname) { 260 Report("FATAL: DataFlowSanitizer: unsupported indirect call to vararg " 261 "function %s\n", fname); 262 Die(); 263 } 264 265 // Like __dfsan_union, but for use from the client or custom functions. Hence 266 // the equality comparison is done here before calling __dfsan_union. 267 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label 268 dfsan_union(dfsan_label l1, dfsan_label l2) { 269 if (l1 == l2) 270 return l1; 271 return __dfsan_union(l1, l2); 272 } 273 274 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 275 dfsan_label dfsan_create_label(const char *desc, void *userdata) { 276 dfsan_label label = 277 atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; 278 dfsan_check_label(label); 279 __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0; 280 __dfsan_label_info[label].desc = desc; 281 __dfsan_label_info[label].userdata = userdata; 282 return label; 283 } 284 285 static void WriteShadowIfDifferent(dfsan_label label, uptr shadow_addr, 286 uptr size) { 287 dfsan_label *labelp = (dfsan_label *)shadow_addr; 288 for (; size != 0; --size, ++labelp) { 289 // Don't write the label if it is already the value we need it to be. 290 // In a program where most addresses are not labeled, it is common that 291 // a page of shadow memory is entirely zeroed. The Linux copy-on-write 292 // implementation will share all of the zeroed pages, making a copy of a 293 // page when any value is written. The un-sharing will happen even if 294 // the value written does not change the value in memory. Avoiding the 295 // write when both |label| and |*labelp| are zero dramatically reduces 296 // the amount of real memory used by large programs. 297 if (label == *labelp) 298 continue; 299 300 *labelp = label; 301 } 302 } 303 304 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_set_label( 305 dfsan_label label, void *addr, uptr size) { 306 const uptr beg_shadow_addr = (uptr)__dfsan::shadow_for(addr); 307 308 if (0 != label) { 309 WriteShadowIfDifferent(label, beg_shadow_addr, size); 310 return; 311 } 312 313 // If label is 0, releases the pages within the shadow address range, and sets 314 // the shadow addresses not on the pages to be 0. 315 const void *end_addr = (void *)((uptr)addr + size); 316 const uptr end_shadow_addr = (uptr)__dfsan::shadow_for(end_addr); 317 const uptr page_size = GetPageSizeCached(); 318 const uptr beg_aligned = RoundUpTo(beg_shadow_addr, page_size); 319 const uptr end_aligned = RoundDownTo(end_shadow_addr, page_size); 320 321 // dfsan_set_label can be called from the following cases 322 // 1) mapped ranges by new/delete and malloc/free. This case has shadow memory 323 // size > 100k, and happens less frequently. 324 // 2) zero-filling internal data structures by utility libraries. This case 325 // has shadow memory size < 32k, and happens more often. 326 // Set kNumPagesThreshold to be 8 to avoid releasing small pages. 327 const int kNumPagesThreshold = 8; 328 if (beg_aligned + kNumPagesThreshold * page_size >= end_aligned) 329 return WriteShadowIfDifferent(label, beg_shadow_addr, size); 330 331 WriteShadowIfDifferent(label, beg_shadow_addr, beg_aligned - beg_shadow_addr); 332 ReleaseMemoryPagesToOS(beg_aligned, end_aligned); 333 WriteShadowIfDifferent(label, end_aligned, end_shadow_addr - end_aligned); 334 } 335 336 SANITIZER_INTERFACE_ATTRIBUTE 337 void dfsan_set_label(dfsan_label label, void *addr, uptr size) { 338 __dfsan_set_label(label, addr, size); 339 } 340 341 SANITIZER_INTERFACE_ATTRIBUTE 342 void dfsan_add_label(dfsan_label label, void *addr, uptr size) { 343 for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) 344 if (*labelp != label) 345 *labelp = __dfsan_union(*labelp, label); 346 } 347 348 // Unlike the other dfsan interface functions the behavior of this function 349 // depends on the label of one of its arguments. Hence it is implemented as a 350 // custom function. 351 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label 352 __dfsw_dfsan_get_label(long data, dfsan_label data_label, 353 dfsan_label *ret_label) { 354 *ret_label = 0; 355 return data_label; 356 } 357 358 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label 359 dfsan_read_label(const void *addr, uptr size) { 360 if (size == 0) 361 return 0; 362 return __dfsan_union_load(shadow_for(addr), size); 363 } 364 365 extern "C" SANITIZER_INTERFACE_ATTRIBUTE 366 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) { 367 return &__dfsan_label_info[label]; 368 } 369 370 extern "C" SANITIZER_INTERFACE_ATTRIBUTE int 371 dfsan_has_label(dfsan_label label, dfsan_label elem) { 372 if (label == elem) 373 return true; 374 const dfsan_label_info *info = dfsan_get_label_info(label); 375 if (info->l1 != 0) { 376 return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem); 377 } else { 378 return false; 379 } 380 } 381 382 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label 383 dfsan_has_label_with_desc(dfsan_label label, const char *desc) { 384 const dfsan_label_info *info = dfsan_get_label_info(label); 385 if (info->l1 != 0) { 386 return dfsan_has_label_with_desc(info->l1, desc) || 387 dfsan_has_label_with_desc(info->l2, desc); 388 } else { 389 return internal_strcmp(desc, info->desc) == 0; 390 } 391 } 392 393 extern "C" SANITIZER_INTERFACE_ATTRIBUTE uptr 394 dfsan_get_label_count(void) { 395 dfsan_label max_label_allocated = 396 atomic_load(&__dfsan_last_label, memory_order_relaxed); 397 398 return static_cast<uptr>(max_label_allocated); 399 } 400 401 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void 402 dfsan_dump_labels(int fd) { 403 dfsan_label last_label = 404 atomic_load(&__dfsan_last_label, memory_order_relaxed); 405 for (uptr l = 1; l <= last_label; ++l) { 406 char buf[64]; 407 internal_snprintf(buf, sizeof(buf), "%u %u %u ", l, 408 __dfsan_label_info[l].l1, __dfsan_label_info[l].l2); 409 WriteToFile(fd, buf, internal_strlen(buf)); 410 if (__dfsan_label_info[l].l1 == 0 && __dfsan_label_info[l].desc) { 411 WriteToFile(fd, __dfsan_label_info[l].desc, 412 internal_strlen(__dfsan_label_info[l].desc)); 413 } 414 WriteToFile(fd, "\n", 1); 415 } 416 } 417 418 #define GET_FATAL_STACK_TRACE_PC_BP(pc, bp) \ 419 BufferedStackTrace stack; \ 420 stack.Unwind(pc, bp, nullptr, common_flags()->fast_unwind_on_fatal); 421 422 void __sanitizer::BufferedStackTrace::UnwindImpl(uptr pc, uptr bp, 423 void *context, 424 bool request_fast, 425 u32 max_depth) { 426 using namespace __dfsan; 427 DFsanThread *t = GetCurrentThread(); 428 if (!t || !StackTrace::WillUseFastUnwind(request_fast)) { 429 return Unwind(max_depth, pc, bp, context, 0, 0, false); 430 } 431 Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true); 432 } 433 434 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_print_stack_trace() { 435 GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME()); 436 stack.Print(); 437 } 438 439 void Flags::SetDefaults() { 440 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue; 441 #include "dfsan_flags.inc" 442 #undef DFSAN_FLAG 443 } 444 445 static void RegisterDfsanFlags(FlagParser *parser, Flags *f) { 446 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) \ 447 RegisterFlag(parser, #Name, Description, &f->Name); 448 #include "dfsan_flags.inc" 449 #undef DFSAN_FLAG 450 } 451 452 static void InitializeFlags() { 453 SetCommonFlagsDefaults(); 454 flags().SetDefaults(); 455 456 FlagParser parser; 457 RegisterCommonFlags(&parser); 458 RegisterDfsanFlags(&parser, &flags()); 459 parser.ParseStringFromEnv("DFSAN_OPTIONS"); 460 InitializeCommonFlags(); 461 if (Verbosity()) ReportUnrecognizedFlags(); 462 if (common_flags()->help) parser.PrintFlagDescriptions(); 463 } 464 465 SANITIZER_INTERFACE_ATTRIBUTE 466 void dfsan_clear_arg_tls(uptr offset, uptr size) { 467 internal_memset((void *)((uptr)__dfsan_arg_tls + offset), 0, size); 468 } 469 470 SANITIZER_INTERFACE_ATTRIBUTE 471 void dfsan_clear_thread_local_state() { 472 internal_memset(__dfsan_arg_tls, 0, sizeof(__dfsan_arg_tls)); 473 internal_memset(__dfsan_retval_tls, 0, sizeof(__dfsan_retval_tls)); 474 } 475 476 static void InitializePlatformEarly() { 477 AvoidCVE_2016_2143(); 478 #ifdef DFSAN_RUNTIME_VMA 479 __dfsan::vmaSize = 480 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1); 481 if (__dfsan::vmaSize == 39 || __dfsan::vmaSize == 42 || 482 __dfsan::vmaSize == 48) { 483 __dfsan_shadow_ptr_mask = ShadowMask(); 484 } else { 485 Printf("FATAL: DataFlowSanitizer: unsupported VMA range\n"); 486 Printf("FATAL: Found %d - Supported 39, 42, and 48\n", __dfsan::vmaSize); 487 Die(); 488 } 489 #endif 490 } 491 492 static void dfsan_fini() { 493 if (internal_strcmp(flags().dump_labels_at_exit, "") != 0) { 494 fd_t fd = OpenFile(flags().dump_labels_at_exit, WrOnly); 495 if (fd == kInvalidFd) { 496 Report("WARNING: DataFlowSanitizer: unable to open output file %s\n", 497 flags().dump_labels_at_exit); 498 return; 499 } 500 501 Report("INFO: DataFlowSanitizer: dumping labels to %s\n", 502 flags().dump_labels_at_exit); 503 dfsan_dump_labels(fd); 504 CloseFile(fd); 505 } 506 } 507 508 extern "C" void dfsan_flush() { 509 if (!MmapFixedNoReserve(ShadowAddr(), UnusedAddr() - ShadowAddr())) 510 Die(); 511 } 512 513 static void dfsan_init(int argc, char **argv, char **envp) { 514 InitializeFlags(); 515 516 ::InitializePlatformEarly(); 517 518 if (!MmapFixedSuperNoReserve(ShadowAddr(), UnusedAddr() - ShadowAddr())) 519 Die(); 520 if (common_flags()->use_madv_dontdump) 521 DontDumpShadowMemory(ShadowAddr(), UnusedAddr() - ShadowAddr()); 522 523 // Protect the region of memory we don't use, to preserve the one-to-one 524 // mapping from application to shadow memory. But if ASLR is disabled, Linux 525 // will load our executable in the middle of our unused region. This mostly 526 // works so long as the program doesn't use too much memory. We support this 527 // case by disabling memory protection when ASLR is disabled. 528 uptr init_addr = (uptr)&dfsan_init; 529 if (!(init_addr >= UnusedAddr() && init_addr < AppAddr())) 530 MmapFixedNoAccess(UnusedAddr(), AppAddr() - UnusedAddr()); 531 532 InitializeInterceptors(); 533 534 // Register the fini callback to run when the program terminates successfully 535 // or it is killed by the runtime. 536 Atexit(dfsan_fini); 537 AddDieCallback(dfsan_fini); 538 539 // Set up threads 540 DFsanTSDInit(DFsanTSDDtor); 541 DFsanThread *main_thread = DFsanThread::Create(nullptr, nullptr, nullptr); 542 SetCurrentThread(main_thread); 543 main_thread->ThreadStart(); 544 545 __dfsan_label_info[kInitializingLabel].desc = "<init label>"; 546 } 547 548 #if SANITIZER_CAN_USE_PREINIT_ARRAY 549 __attribute__((section(".preinit_array"), used)) 550 static void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init; 551 #endif 552