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