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_chained_origin_depot.h"
24 #include "dfsan/dfsan_flags.h"
25 #include "dfsan/dfsan_origin.h"
26 #include "dfsan/dfsan_thread.h"
27 #include "sanitizer_common/sanitizer_atomic.h"
28 #include "sanitizer_common/sanitizer_common.h"
29 #include "sanitizer_common/sanitizer_file.h"
30 #include "sanitizer_common/sanitizer_flag_parser.h"
31 #include "sanitizer_common/sanitizer_flags.h"
32 #include "sanitizer_common/sanitizer_internal_defs.h"
33 #include "sanitizer_common/sanitizer_libc.h"
34 #include "sanitizer_common/sanitizer_report_decorator.h"
35 #include "sanitizer_common/sanitizer_stacktrace.h"
36 
37 using namespace __dfsan;
38 
39 typedef atomic_uint16_t atomic_dfsan_label;
40 static const dfsan_label kInitializingLabel = -1;
41 
42 static const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8);
43 
44 static atomic_dfsan_label __dfsan_last_label;
45 static dfsan_label_info __dfsan_label_info[kNumLabels];
46 
47 Flags __dfsan::flags_data;
48 
49 // The size of TLS variables. These constants must be kept in sync with the ones
50 // in DataFlowSanitizer.cpp.
51 static const int kDFsanArgTlsSize = 800;
52 static const int kDFsanRetvalTlsSize = 800;
53 static const int kDFsanArgOriginTlsSize = 800;
54 
55 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64
56     __dfsan_retval_tls[kDFsanRetvalTlsSize / sizeof(u64)];
57 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u32 __dfsan_retval_origin_tls;
58 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u64
59     __dfsan_arg_tls[kDFsanArgTlsSize / sizeof(u64)];
60 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL u32
61     __dfsan_arg_origin_tls[kDFsanArgOriginTlsSize / sizeof(u32)];
62 
63 SANITIZER_INTERFACE_ATTRIBUTE uptr __dfsan_shadow_ptr_mask;
64 
65 // Instrumented code may set this value in terms of -dfsan-track-origins.
66 // * undefined or 0: do not track origins.
67 // * 1: track origins at memory store operations.
68 // * 2: TODO: track origins at memory store operations and callsites.
69 extern "C" SANITIZER_WEAK_ATTRIBUTE const int __dfsan_track_origins;
70 
71 int __dfsan_get_track_origins() {
72   return &__dfsan_track_origins ? __dfsan_track_origins : 0;
73 }
74 
75 // On Linux/x86_64, memory is laid out as follows:
76 //
77 // +--------------------+ 0x800000000000 (top of memory)
78 // | application memory |
79 // +--------------------+ 0x700000008000 (kAppAddr)
80 // |                    |
81 // |       unused       |
82 // |                    |
83 // +--------------------+ 0x300200000000 (kUnusedAddr)
84 // |    union table     |
85 // +--------------------+ 0x300000000000 (kUnionTableAddr)
86 // |       origin       |
87 // +--------------------+ 0x200000000000 (kOriginAddr)
88 // |   shadow memory    |
89 // +--------------------+ 0x000000010000 (kShadowAddr)
90 // | reserved by kernel |
91 // +--------------------+ 0x000000000000
92 //
93 // To derive a shadow memory address from an application memory address,
94 // bits 44-46 are cleared to bring the address into the range
95 // [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
96 // account for the double byte representation of shadow labels and move the
97 // address into the shadow memory range.  See the function shadow_for below.
98 
99 // On Linux/MIPS64, memory is laid out as follows:
100 //
101 // +--------------------+ 0x10000000000 (top of memory)
102 // | application memory |
103 // +--------------------+ 0xF000008000 (kAppAddr)
104 // |                    |
105 // |       unused       |
106 // |                    |
107 // +--------------------+ 0x2200000000 (kUnusedAddr)
108 // |    union table     |
109 // +--------------------+ 0x2000000000 (kUnionTableAddr)
110 // |   shadow memory    |
111 // +--------------------+ 0x0000010000 (kShadowAddr)
112 // | reserved by kernel |
113 // +--------------------+ 0x0000000000
114 
115 // On Linux/AArch64 (39-bit VMA), memory is laid out as follow:
116 //
117 // +--------------------+ 0x8000000000 (top of memory)
118 // | application memory |
119 // +--------------------+ 0x7000008000 (kAppAddr)
120 // |                    |
121 // |       unused       |
122 // |                    |
123 // +--------------------+ 0x1200000000 (kUnusedAddr)
124 // |    union table     |
125 // +--------------------+ 0x1000000000 (kUnionTableAddr)
126 // |   shadow memory    |
127 // +--------------------+ 0x0000010000 (kShadowAddr)
128 // | reserved by kernel |
129 // +--------------------+ 0x0000000000
130 
131 // On Linux/AArch64 (42-bit VMA), memory is laid out as follow:
132 //
133 // +--------------------+ 0x40000000000 (top of memory)
134 // | application memory |
135 // +--------------------+ 0x3ff00008000 (kAppAddr)
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 // On Linux/AArch64 (48-bit VMA), memory is laid out as follow:
148 //
149 // +--------------------+ 0x1000000000000 (top of memory)
150 // | application memory |
151 // +--------------------+ 0xffff00008000 (kAppAddr)
152 // |       unused       |
153 // +--------------------+ 0xaaaab0000000 (top of PIE address)
154 // | application PIE    |
155 // +--------------------+ 0xaaaaa0000000 (top of PIE address)
156 // |                    |
157 // |       unused       |
158 // |                    |
159 // +--------------------+ 0x1200000000 (kUnusedAddr)
160 // |    union table     |
161 // +--------------------+ 0x8000000000 (kUnionTableAddr)
162 // |   shadow memory    |
163 // +--------------------+ 0x0000010000 (kShadowAddr)
164 // | reserved by kernel |
165 // +--------------------+ 0x0000000000
166 
167 typedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels];
168 
169 #ifdef DFSAN_RUNTIME_VMA
170 // Runtime detected VMA size.
171 int __dfsan::vmaSize;
172 #endif
173 
174 static uptr UnusedAddr() {
175   return UnionTableAddr() + sizeof(dfsan_union_table_t);
176 }
177 
178 static atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) {
179   return &(*(dfsan_union_table_t *) UnionTableAddr())[l1][l2];
180 }
181 
182 // Checks we do not run out of labels.
183 static void dfsan_check_label(dfsan_label label) {
184   if (label == kInitializingLabel) {
185     Report("FATAL: DataFlowSanitizer: out of labels\n");
186     Die();
187   }
188 }
189 
190 // Resolves the union of two unequal labels.  Nonequality is a precondition for
191 // this function (the instrumentation pass inlines the equality test).
192 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
193 dfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) {
194   DCHECK_NE(l1, l2);
195 
196   if (l1 == 0)
197     return l2;
198   if (l2 == 0)
199     return l1;
200 
201   // If no labels have been created, yet l1 and l2 are non-zero, we are using
202   // fast16labels mode.
203   if (atomic_load(&__dfsan_last_label, memory_order_relaxed) == 0)
204     return l1 | l2;
205 
206   if (l1 > l2)
207     Swap(l1, l2);
208 
209   atomic_dfsan_label *table_ent = union_table(l1, l2);
210   // We need to deal with the case where two threads concurrently request
211   // a union of the same pair of labels.  If the table entry is uninitialized,
212   // (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel
213   // (i.e. -1) to mark that we are initializing it.
214   dfsan_label label = 0;
215   if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel,
216                                      memory_order_acquire)) {
217     // Check whether l2 subsumes l1.  We don't need to check whether l1
218     // subsumes l2 because we are guaranteed here that l1 < l2, and (at least
219     // in the cases we are interested in) a label may only subsume labels
220     // created earlier (i.e. with a lower numerical value).
221     if (__dfsan_label_info[l2].l1 == l1 ||
222         __dfsan_label_info[l2].l2 == l1) {
223       label = l2;
224     } else {
225       label =
226         atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;
227       dfsan_check_label(label);
228       __dfsan_label_info[label].l1 = l1;
229       __dfsan_label_info[label].l2 = l2;
230     }
231     atomic_store(table_ent, label, memory_order_release);
232   } else if (label == kInitializingLabel) {
233     // Another thread is initializing the entry.  Wait until it is finished.
234     do {
235       internal_sched_yield();
236       label = atomic_load(table_ent, memory_order_acquire);
237     } while (label == kInitializingLabel);
238   }
239   return label;
240 }
241 
242 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
243 dfsan_label __dfsan_union_load(const dfsan_label *ls, uptr n) {
244   dfsan_label label = ls[0];
245   for (uptr i = 1; i != n; ++i) {
246     dfsan_label next_label = ls[i];
247     if (label != next_label)
248       label = __dfsan_union(label, next_label);
249   }
250   return label;
251 }
252 
253 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
254 dfsan_label __dfsan_union_load_fast16labels(const dfsan_label *ls, uptr n) {
255   dfsan_label label = ls[0];
256   for (uptr i = 1; i != n; ++i)
257     label |= ls[i];
258   return label;
259 }
260 
261 // Return the union of all the n labels from addr at the high 32 bit, and the
262 // origin of the first taint byte at the low 32 bit.
263 extern "C" SANITIZER_INTERFACE_ATTRIBUTE u64
264 __dfsan_load_label_and_origin(const void *addr, uptr n) {
265   dfsan_label label = 0;
266   u64 ret = 0;
267   uptr p = (uptr)addr;
268   dfsan_label *s = shadow_for((void *)p);
269   for (uptr i = 0; i < n; ++i) {
270     dfsan_label l = s[i];
271     if (!l)
272       continue;
273     label |= l;
274     if (!ret)
275       ret = *(dfsan_origin *)origin_for((void *)(p + i));
276   }
277   return ret | (u64)label << 32;
278 }
279 
280 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
281 void __dfsan_unimplemented(char *fname) {
282   if (flags().warn_unimplemented)
283     Report("WARNING: DataFlowSanitizer: call to uninstrumented function %s\n",
284            fname);
285 }
286 
287 // Use '-mllvm -dfsan-debug-nonzero-labels' and break on this function
288 // to try to figure out where labels are being introduced in a nominally
289 // label-free program.
290 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_nonzero_label() {
291   if (flags().warn_nonzero_labels)
292     Report("WARNING: DataFlowSanitizer: saw nonzero label\n");
293 }
294 
295 // Indirect call to an uninstrumented vararg function. We don't have a way of
296 // handling these at the moment.
297 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
298 __dfsan_vararg_wrapper(const char *fname) {
299   Report("FATAL: DataFlowSanitizer: unsupported indirect call to vararg "
300          "function %s\n", fname);
301   Die();
302 }
303 
304 // Like __dfsan_union, but for use from the client or custom functions.  Hence
305 // the equality comparison is done here before calling __dfsan_union.
306 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
307 dfsan_union(dfsan_label l1, dfsan_label l2) {
308   if (l1 == l2)
309     return l1;
310   return __dfsan_union(l1, l2);
311 }
312 
313 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
314 dfsan_label dfsan_create_label(const char *desc, void *userdata) {
315   dfsan_label label =
316       atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;
317   dfsan_check_label(label);
318   __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0;
319   __dfsan_label_info[label].desc = desc;
320   __dfsan_label_info[label].userdata = userdata;
321   return label;
322 }
323 
324 // Return the origin of the first taint byte in the size bytes from the address
325 // addr.
326 static dfsan_origin GetOriginIfTainted(uptr addr, uptr size) {
327   for (uptr i = 0; i < size; ++i, ++addr) {
328     dfsan_label *s = shadow_for((void *)addr);
329     if (!is_shadow_addr_valid((uptr)s)) {
330       // The current DFSan memory layout is not always correct. For example,
331       // addresses (0, 0x10000) are mapped to (0, 0x10000). Before fixing the
332       // issue, we ignore such addresses.
333       continue;
334     }
335     if (*s)
336       return *(dfsan_origin *)origin_for((void *)addr);
337   }
338   return 0;
339 }
340 
341 // For platforms which support slow unwinder only, we need to restrict the store
342 // context size to 1, basically only storing the current pc, because the slow
343 // unwinder which is based on libunwind is not async signal safe and causes
344 // random freezes in forking applications as well as in signal handlers.
345 // DFSan supports only Linux. So we do not restrict the store context size.
346 #define GET_STORE_STACK_TRACE_PC_BP(pc, bp) \
347   BufferedStackTrace stack;                 \
348   stack.Unwind(pc, bp, nullptr, true, flags().store_context_size);
349 
350 #define PRINT_CALLER_STACK_TRACE        \
351   {                                     \
352     GET_CALLER_PC_BP_SP;                \
353     (void)sp;                           \
354     GET_STORE_STACK_TRACE_PC_BP(pc, bp) \
355     stack.Print();                      \
356   }
357 
358 // Return a chain with the previous ID id and the current stack.
359 // from_init = true if this is the first chain of an origin tracking path.
360 static u32 ChainOrigin(u32 id, StackTrace *stack, bool from_init = false) {
361   // StackDepot is not async signal safe. Do not create new chains in a signal
362   // handler.
363   DFsanThread *t = GetCurrentThread();
364   if (t && t->InSignalHandler())
365     return id;
366 
367   // As an optimization the origin of an application byte is updated only when
368   // its shadow is non-zero. Because we are only interested in the origins of
369   // taint labels, it does not matter what origin a zero label has. This reduces
370   // memory write cost. MSan does similar optimization. The following invariant
371   // may not hold because of some bugs. We check the invariant to help debug.
372   if (!from_init && id == 0 && flags().check_origin_invariant) {
373     Printf("  DFSan found invalid origin invariant\n");
374     PRINT_CALLER_STACK_TRACE
375   }
376 
377   Origin o = Origin::FromRawId(id);
378   stack->tag = StackTrace::TAG_UNKNOWN;
379   Origin chained = Origin::CreateChainedOrigin(o, stack);
380   return chained.raw_id();
381 }
382 
383 static const uptr kOriginAlign = sizeof(dfsan_origin);
384 static const uptr kOriginAlignMask = ~(kOriginAlign - 1UL);
385 
386 static uptr AlignUp(uptr u) {
387   return (u + kOriginAlign - 1) & kOriginAlignMask;
388 }
389 
390 static uptr AlignDown(uptr u) { return u & kOriginAlignMask; }
391 
392 static void ChainAndWriteOriginIfTainted(uptr src, uptr size, uptr dst,
393                                          StackTrace *stack) {
394   dfsan_origin o = GetOriginIfTainted(src, size);
395   if (o) {
396     o = ChainOrigin(o, stack);
397     *(dfsan_origin *)origin_for((void *)dst) = o;
398   }
399 }
400 
401 // Copy the origins of the size bytes from src to dst. The source and target
402 // memory ranges cannot be overlapped. This is used by memcpy. stack records the
403 // stack trace of the memcpy. When dst and src are not 4-byte aligned properly,
404 // origins at the unaligned address boundaries may be overwritten because four
405 // contiguous bytes share the same origin.
406 static void CopyOrigin(const void *dst, const void *src, uptr size,
407                        StackTrace *stack) {
408   uptr d = (uptr)dst;
409   uptr beg = AlignDown(d);
410   // Copy left unaligned origin if that memory is tainted.
411   if (beg < d) {
412     ChainAndWriteOriginIfTainted((uptr)src, beg + kOriginAlign - d, beg, stack);
413     beg += kOriginAlign;
414   }
415 
416   uptr end = AlignDown(d + size);
417   // If both ends fall into the same 4-byte slot, we are done.
418   if (end < beg)
419     return;
420 
421   // Copy right unaligned origin if that memory is tainted.
422   if (end < d + size)
423     ChainAndWriteOriginIfTainted((uptr)src + (end - d), (d + size) - end, end,
424                                  stack);
425 
426   if (beg >= end)
427     return;
428 
429   // Align src up.
430   uptr s = AlignUp((uptr)src);
431   dfsan_origin *src_o = (dfsan_origin *)origin_for((void *)s);
432   u64 *src_s = (u64 *)shadow_for((void *)s);
433   dfsan_origin *src_end = (dfsan_origin *)origin_for((void *)(s + (end - beg)));
434   dfsan_origin *dst_o = (dfsan_origin *)origin_for((void *)beg);
435   dfsan_origin last_src_o = 0;
436   dfsan_origin last_dst_o = 0;
437   for (; src_o < src_end; ++src_o, ++src_s, ++dst_o) {
438     if (!*src_s)
439       continue;
440     if (*src_o != last_src_o) {
441       last_src_o = *src_o;
442       last_dst_o = ChainOrigin(last_src_o, stack);
443     }
444     *dst_o = last_dst_o;
445   }
446 }
447 
448 // Copy the origins of the size bytes from src to dst. The source and target
449 // memory ranges may be overlapped. So the copy is done in a reverse order.
450 // This is used by memmove. stack records the stack trace of the memmove.
451 static void ReverseCopyOrigin(const void *dst, const void *src, uptr size,
452                               StackTrace *stack) {
453   uptr d = (uptr)dst;
454   uptr end = AlignDown(d + size);
455 
456   // Copy right unaligned origin if that memory is tainted.
457   if (end < d + size)
458     ChainAndWriteOriginIfTainted((uptr)src + (end - d), (d + size) - end, end,
459                                  stack);
460 
461   uptr beg = AlignDown(d);
462 
463   if (beg + kOriginAlign < end) {
464     // Align src up.
465     uptr s = AlignUp((uptr)src);
466     dfsan_origin *src =
467         (dfsan_origin *)origin_for((void *)(s + end - beg - kOriginAlign));
468     u64 *src_s = (u64 *)shadow_for((void *)(s + end - beg - kOriginAlign));
469     dfsan_origin *src_begin = (dfsan_origin *)origin_for((void *)s);
470     dfsan_origin *dst =
471         (dfsan_origin *)origin_for((void *)(end - kOriginAlign));
472     dfsan_origin src_o = 0;
473     dfsan_origin dst_o = 0;
474     for (; src >= src_begin; --src, --src_s, --dst) {
475       if (!*src_s)
476         continue;
477       if (*src != src_o) {
478         src_o = *src;
479         dst_o = ChainOrigin(src_o, stack);
480       }
481       *dst = dst_o;
482     }
483   }
484 
485   // Copy left unaligned origin if that memory is tainted.
486   if (beg < d)
487     ChainAndWriteOriginIfTainted((uptr)src, beg + kOriginAlign - d, beg, stack);
488 }
489 
490 // Copy or move the origins of the len bytes from src to dst. The source and
491 // target memory ranges may or may not be overlapped. This is used by memory
492 // transfer operations. stack records the stack trace of the memory transfer
493 // operation.
494 static void MoveOrigin(const void *dst, const void *src, uptr size,
495                        StackTrace *stack) {
496   if (!has_valid_shadow_addr(dst) ||
497       !has_valid_shadow_addr((void *)((uptr)dst + size)) ||
498       !has_valid_shadow_addr(src) ||
499       !has_valid_shadow_addr((void *)((uptr)src + size))) {
500     return;
501   }
502   // If destination origin range overlaps with source origin range, move
503   // origins by copying origins in a reverse order; otherwise, copy origins in
504   // a normal order. The orders of origin transfer are consistent with the
505   // orders of how memcpy and memmove transfer user data.
506   uptr src_aligned_beg = reinterpret_cast<uptr>(src) & ~3UL;
507   uptr src_aligned_end = (reinterpret_cast<uptr>(src) + size) & ~3UL;
508   uptr dst_aligned_beg = reinterpret_cast<uptr>(dst) & ~3UL;
509   if (dst_aligned_beg < src_aligned_end && dst_aligned_beg >= src_aligned_beg)
510     return ReverseCopyOrigin(dst, src, size, stack);
511   return CopyOrigin(dst, src, size, stack);
512 }
513 
514 // Set the size bytes from the addres dst to be the origin value.
515 static void SetOrigin(const void *dst, uptr size, u32 origin) {
516   if (size == 0)
517     return;
518 
519   // Origin mapping is 4 bytes per 4 bytes of application memory.
520   // Here we extend the range such that its left and right bounds are both
521   // 4 byte aligned.
522   uptr x = unaligned_origin_for((uptr)dst);
523   uptr beg = AlignDown(x);
524   uptr end = AlignUp(x + size);  // align up.
525   u64 origin64 = ((u64)origin << 32) | origin;
526   // This is like memset, but the value is 32-bit. We unroll by 2 to write
527   // 64 bits at once. May want to unroll further to get 128-bit stores.
528   if (beg & 7ULL) {
529     if (*(u32 *)beg != origin)
530       *(u32 *)beg = origin;
531     beg += 4;
532   }
533   for (uptr addr = beg; addr < (end & ~7UL); addr += 8) {
534     if (*(u64 *)addr == origin64)
535       continue;
536     *(u64 *)addr = origin64;
537   }
538   if (end & 7ULL)
539     if (*(u32 *)(end - kOriginAlign) != origin)
540       *(u32 *)(end - kOriginAlign) = origin;
541 }
542 
543 static void WriteShadowInRange(dfsan_label label, uptr beg_shadow_addr,
544                                uptr end_shadow_addr) {
545   // TODO: After changing dfsan_label to 8bit, use internal_memset when label
546   // is not 0.
547   dfsan_label *labelp = (dfsan_label *)beg_shadow_addr;
548   if (label) {
549     for (; (uptr)labelp < end_shadow_addr; ++labelp) *labelp = label;
550     return;
551   }
552 
553   for (; (uptr)labelp < end_shadow_addr; ++labelp) {
554     // Don't write the label if it is already the value we need it to be.
555     // In a program where most addresses are not labeled, it is common that
556     // a page of shadow memory is entirely zeroed.  The Linux copy-on-write
557     // implementation will share all of the zeroed pages, making a copy of a
558     // page when any value is written.  The un-sharing will happen even if
559     // the value written does not change the value in memory.  Avoiding the
560     // write when both |label| and |*labelp| are zero dramatically reduces
561     // the amount of real memory used by large programs.
562     if (!*labelp)
563       continue;
564 
565     *labelp = 0;
566   }
567 }
568 
569 static void WriteShadowWithSize(dfsan_label label, uptr shadow_addr,
570                                 uptr size) {
571   WriteShadowInRange(label, shadow_addr, shadow_addr + size * sizeof(label));
572 }
573 
574 #define RET_CHAIN_ORIGIN(id)           \
575   GET_CALLER_PC_BP_SP;                 \
576   (void)sp;                            \
577   GET_STORE_STACK_TRACE_PC_BP(pc, bp); \
578   return ChainOrigin(id, &stack);
579 
580 // Return a new origin chain with the previous ID id and the current stack
581 // trace.
582 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin
583 __dfsan_chain_origin(dfsan_origin id) {
584   RET_CHAIN_ORIGIN(id)
585 }
586 
587 // Return a new origin chain with the previous ID id and the current stack
588 // trace if the label is tainted.
589 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin
590 __dfsan_chain_origin_if_tainted(dfsan_label label, dfsan_origin id) {
591   if (!label)
592     return id;
593   RET_CHAIN_ORIGIN(id)
594 }
595 
596 // Copy or move the origins of the len bytes from src to dst.
597 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_mem_origin_transfer(
598     const void *dst, const void *src, uptr len) {
599   if (src == dst)
600     return;
601   GET_CALLER_PC_BP;
602   GET_STORE_STACK_TRACE_PC_BP(pc, bp);
603   MoveOrigin(dst, src, len, &stack);
604 }
605 
606 SANITIZER_INTERFACE_ATTRIBUTE void dfsan_mem_origin_transfer(const void *dst,
607                                                              const void *src,
608                                                              uptr len) {
609   __dfsan_mem_origin_transfer(dst, src, len);
610 }
611 
612 namespace __dfsan {
613 
614 bool dfsan_inited = false;
615 bool dfsan_init_is_running = false;
616 
617 void dfsan_copy_memory(void *dst, const void *src, uptr size) {
618   internal_memcpy(dst, src, size);
619   internal_memcpy((void *)shadow_for(dst), (const void *)shadow_for(src),
620                   size * sizeof(dfsan_label));
621   if (__dfsan_get_track_origins())
622     dfsan_mem_origin_transfer(dst, src, size);
623 }
624 
625 }  // namespace __dfsan
626 
627 // If the label s is tainted, set the size bytes from the address p to be a new
628 // origin chain with the previous ID o and the current stack trace. This is
629 // used by instrumentation to reduce code size when too much code is inserted.
630 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_maybe_store_origin(
631     u16 s, void *p, uptr size, dfsan_origin o) {
632   if (UNLIKELY(s)) {
633     GET_CALLER_PC_BP_SP;
634     (void)sp;
635     GET_STORE_STACK_TRACE_PC_BP(pc, bp);
636     SetOrigin(p, size, ChainOrigin(o, &stack));
637   }
638 }
639 
640 // Releases the pages within the origin address range.
641 static void ReleaseOrigins(void *addr, uptr size) {
642   const uptr beg_origin_addr = (uptr)__dfsan::origin_for(addr);
643   const void *end_addr = (void *)((uptr)addr + size);
644   const uptr end_origin_addr = (uptr)__dfsan::origin_for(end_addr);
645 
646   if (end_origin_addr - beg_origin_addr <
647       common_flags()->clear_shadow_mmap_threshold)
648     return;
649 
650   const uptr page_size = GetPageSizeCached();
651   const uptr beg_aligned = RoundUpTo(beg_origin_addr, page_size);
652   const uptr end_aligned = RoundDownTo(end_origin_addr, page_size);
653 
654   if (!MmapFixedSuperNoReserve(beg_aligned, end_aligned - beg_aligned))
655     Die();
656 }
657 
658 // Releases the pages within the shadow address range, and sets
659 // the shadow addresses not on the pages to be 0.
660 static void ReleaseOrClearShadows(void *addr, uptr size) {
661   const uptr beg_shadow_addr = (uptr)__dfsan::shadow_for(addr);
662   const void *end_addr = (void *)((uptr)addr + size);
663   const uptr end_shadow_addr = (uptr)__dfsan::shadow_for(end_addr);
664 
665   if (end_shadow_addr - beg_shadow_addr <
666       common_flags()->clear_shadow_mmap_threshold)
667     return WriteShadowWithSize(0, beg_shadow_addr, size);
668 
669   const uptr page_size = GetPageSizeCached();
670   const uptr beg_aligned = RoundUpTo(beg_shadow_addr, page_size);
671   const uptr end_aligned = RoundDownTo(end_shadow_addr, page_size);
672 
673   if (beg_aligned >= end_aligned) {
674     WriteShadowWithSize(0, beg_shadow_addr, size);
675   } else {
676     if (beg_aligned != beg_shadow_addr)
677       WriteShadowInRange(0, beg_shadow_addr, beg_aligned);
678     if (end_aligned != end_shadow_addr)
679       WriteShadowInRange(0, end_aligned, end_shadow_addr);
680     if (!MmapFixedSuperNoReserve(beg_aligned, end_aligned - beg_aligned))
681       Die();
682   }
683 }
684 
685 void SetShadow(dfsan_label label, void *addr, uptr size, dfsan_origin origin) {
686   if (0 != label) {
687     const uptr beg_shadow_addr = (uptr)__dfsan::shadow_for(addr);
688     WriteShadowWithSize(label, beg_shadow_addr, size);
689     if (__dfsan_get_track_origins())
690       SetOrigin(addr, size, origin);
691     return;
692   }
693 
694   if (__dfsan_get_track_origins())
695     ReleaseOrigins(addr, size);
696 
697   ReleaseOrClearShadows(addr, size);
698 }
699 
700 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_set_label(
701     dfsan_label label, dfsan_origin origin, void *addr, uptr size) {
702   SetShadow(label, addr, size, origin);
703 }
704 
705 SANITIZER_INTERFACE_ATTRIBUTE
706 void dfsan_set_label(dfsan_label label, void *addr, uptr size) {
707   dfsan_origin init_origin = 0;
708   if (label && __dfsan_get_track_origins()) {
709     GET_CALLER_PC_BP;
710     GET_STORE_STACK_TRACE_PC_BP(pc, bp);
711     init_origin = ChainOrigin(0, &stack, true);
712   }
713   SetShadow(label, addr, size, init_origin);
714 }
715 
716 SANITIZER_INTERFACE_ATTRIBUTE
717 void dfsan_add_label(dfsan_label label, void *addr, uptr size) {
718   if (0 == label)
719     return;
720 
721   if (__dfsan_get_track_origins()) {
722     GET_CALLER_PC_BP;
723     GET_STORE_STACK_TRACE_PC_BP(pc, bp);
724     dfsan_origin init_origin = ChainOrigin(0, &stack, true);
725     SetOrigin(addr, size, init_origin);
726   }
727 
728   for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)
729     if (*labelp != label)
730       *labelp = __dfsan_union(*labelp, label);
731 }
732 
733 // Unlike the other dfsan interface functions the behavior of this function
734 // depends on the label of one of its arguments.  Hence it is implemented as a
735 // custom function.
736 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
737 __dfsw_dfsan_get_label(long data, dfsan_label data_label,
738                        dfsan_label *ret_label) {
739   *ret_label = 0;
740   return data_label;
741 }
742 
743 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfso_dfsan_get_label(
744     long data, dfsan_label data_label, dfsan_label *ret_label,
745     dfsan_origin data_origin, dfsan_origin *ret_origin) {
746   *ret_label = 0;
747   *ret_origin = 0;
748   return data_label;
749 }
750 
751 // This function is used if dfsan_get_origin is called when origin tracking is
752 // off.
753 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin __dfsw_dfsan_get_origin(
754     long data, dfsan_label data_label, dfsan_label *ret_label) {
755   *ret_label = 0;
756   return 0;
757 }
758 
759 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin __dfso_dfsan_get_origin(
760     long data, dfsan_label data_label, dfsan_label *ret_label,
761     dfsan_origin data_origin, dfsan_origin *ret_origin) {
762   *ret_label = 0;
763   *ret_origin = 0;
764   return data_origin;
765 }
766 
767 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
768 dfsan_read_label(const void *addr, uptr size) {
769   if (size == 0)
770     return 0;
771   return __dfsan_union_load(shadow_for(addr), size);
772 }
773 
774 SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin
775 dfsan_read_origin_of_first_taint(const void *addr, uptr size) {
776   return GetOriginIfTainted((uptr)addr, size);
777 }
778 
779 SANITIZER_INTERFACE_ATTRIBUTE void dfsan_set_label_origin(dfsan_label label,
780                                                           dfsan_origin origin,
781                                                           void *addr,
782                                                           uptr size) {
783   __dfsan_set_label(label, origin, addr, size);
784 }
785 
786 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
787 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) {
788   return &__dfsan_label_info[label];
789 }
790 
791 extern "C" SANITIZER_INTERFACE_ATTRIBUTE int
792 dfsan_has_label(dfsan_label label, dfsan_label elem) {
793   if (label == elem)
794     return true;
795   const dfsan_label_info *info = dfsan_get_label_info(label);
796   if (info->l1 != 0) {
797     return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem);
798   } else {
799     return false;
800   }
801 }
802 
803 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
804 dfsan_has_label_with_desc(dfsan_label label, const char *desc) {
805   const dfsan_label_info *info = dfsan_get_label_info(label);
806   if (info->l1 != 0) {
807     return dfsan_has_label_with_desc(info->l1, desc) ||
808            dfsan_has_label_with_desc(info->l2, desc);
809   } else {
810     return internal_strcmp(desc, info->desc) == 0;
811   }
812 }
813 
814 extern "C" SANITIZER_INTERFACE_ATTRIBUTE uptr
815 dfsan_get_label_count(void) {
816   dfsan_label max_label_allocated =
817       atomic_load(&__dfsan_last_label, memory_order_relaxed);
818 
819   return static_cast<uptr>(max_label_allocated);
820 }
821 
822 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
823 dfsan_dump_labels(int fd) {
824   dfsan_label last_label =
825       atomic_load(&__dfsan_last_label, memory_order_relaxed);
826   for (uptr l = 1; l <= last_label; ++l) {
827     char buf[64];
828     internal_snprintf(buf, sizeof(buf), "%u %u %u ", l,
829                       __dfsan_label_info[l].l1, __dfsan_label_info[l].l2);
830     WriteToFile(fd, buf, internal_strlen(buf));
831     if (__dfsan_label_info[l].l1 == 0 && __dfsan_label_info[l].desc) {
832       WriteToFile(fd, __dfsan_label_info[l].desc,
833                   internal_strlen(__dfsan_label_info[l].desc));
834     }
835     WriteToFile(fd, "\n", 1);
836   }
837 }
838 
839 class Decorator : public __sanitizer::SanitizerCommonDecorator {
840  public:
841   Decorator() : SanitizerCommonDecorator() {}
842   const char *Origin() const { return Magenta(); }
843 };
844 
845 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void dfsan_print_origin_trace(
846     const void *addr, const char *description) {
847   Decorator d;
848 
849   if (!__dfsan_get_track_origins()) {
850     Printf(
851         "  %sDFSan: origin tracking is not enabled. Did you specify the "
852         "-dfsan-track-origins=1 option?%s\n",
853         d.Warning(), d.Default());
854     return;
855   }
856 
857   const dfsan_label label = *__dfsan::shadow_for(addr);
858   if (!label) {
859     Printf("  %sDFSan: no tainted value at %x%s\n", d.Warning(), addr,
860            d.Default());
861     return;
862   }
863 
864   const dfsan_origin origin = *__dfsan::origin_for(addr);
865 
866   Printf("  %sTaint value 0x%x (at %p) origin tracking (%s)%s\n", d.Origin(),
867          label, addr, description ? description : "", d.Default());
868   Origin o = Origin::FromRawId(origin);
869   bool found = false;
870   while (o.isChainedOrigin()) {
871     StackTrace stack;
872     dfsan_origin origin_id = o.raw_id();
873     o = o.getNextChainedOrigin(&stack);
874     if (o.isChainedOrigin())
875       Printf("  %sOrigin value: 0x%x, Taint value was stored to memory at%s\n",
876              d.Origin(), origin_id, d.Default());
877     else
878       Printf("  %sOrigin value: 0x%x, Taint value was created at%s\n",
879              d.Origin(), origin_id, d.Default());
880     stack.Print();
881     found = true;
882   }
883   if (!found)
884     Printf(
885         "  %sTaint value 0x%x (at %p) has invalid origin tracking. This can "
886         "be a DFSan bug.%s\n",
887         d.Warning(), label, addr, d.Default());
888 }
889 
890 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_origin
891 dfsan_get_init_origin(const void *addr) {
892   if (!__dfsan_get_track_origins())
893     return 0;
894 
895   const dfsan_label label = *__dfsan::shadow_for(addr);
896   if (!label)
897     return 0;
898 
899   const dfsan_origin origin = *__dfsan::origin_for(addr);
900 
901   Origin o = Origin::FromRawId(origin);
902   dfsan_origin origin_id = o.raw_id();
903   while (o.isChainedOrigin()) {
904     StackTrace stack;
905     origin_id = o.raw_id();
906     o = o.getNextChainedOrigin(&stack);
907   }
908   return origin_id;
909 }
910 
911 #define GET_FATAL_STACK_TRACE_PC_BP(pc, bp) \
912   BufferedStackTrace stack;                 \
913   stack.Unwind(pc, bp, nullptr, common_flags()->fast_unwind_on_fatal);
914 
915 void __sanitizer::BufferedStackTrace::UnwindImpl(uptr pc, uptr bp,
916                                                  void *context,
917                                                  bool request_fast,
918                                                  u32 max_depth) {
919   using namespace __dfsan;
920   DFsanThread *t = GetCurrentThread();
921   if (!t || !StackTrace::WillUseFastUnwind(request_fast)) {
922     return Unwind(max_depth, pc, bp, context, 0, 0, false);
923   }
924   Unwind(max_depth, pc, bp, nullptr, t->stack_top(), t->stack_bottom(), true);
925 }
926 
927 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_print_stack_trace() {
928   GET_FATAL_STACK_TRACE_PC_BP(StackTrace::GetCurrentPc(), GET_CURRENT_FRAME());
929   stack.Print();
930 }
931 
932 void Flags::SetDefaults() {
933 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
934 #include "dfsan_flags.inc"
935 #undef DFSAN_FLAG
936 }
937 
938 static void RegisterDfsanFlags(FlagParser *parser, Flags *f) {
939 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) \
940   RegisterFlag(parser, #Name, Description, &f->Name);
941 #include "dfsan_flags.inc"
942 #undef DFSAN_FLAG
943 }
944 
945 static void InitializeFlags() {
946   SetCommonFlagsDefaults();
947   {
948     CommonFlags cf;
949     cf.CopyFrom(*common_flags());
950     cf.intercept_tls_get_addr = true;
951     OverrideCommonFlags(cf);
952   }
953   flags().SetDefaults();
954 
955   FlagParser parser;
956   RegisterCommonFlags(&parser);
957   RegisterDfsanFlags(&parser, &flags());
958   parser.ParseStringFromEnv("DFSAN_OPTIONS");
959   InitializeCommonFlags();
960   if (Verbosity()) ReportUnrecognizedFlags();
961   if (common_flags()->help) parser.PrintFlagDescriptions();
962 }
963 
964 SANITIZER_INTERFACE_ATTRIBUTE
965 void dfsan_clear_arg_tls(uptr offset, uptr size) {
966   internal_memset((void *)((uptr)__dfsan_arg_tls + offset), 0, size);
967 }
968 
969 SANITIZER_INTERFACE_ATTRIBUTE
970 void dfsan_clear_thread_local_state() {
971   internal_memset(__dfsan_arg_tls, 0, sizeof(__dfsan_arg_tls));
972   internal_memset(__dfsan_retval_tls, 0, sizeof(__dfsan_retval_tls));
973 
974   if (__dfsan_get_track_origins()) {
975     internal_memset(__dfsan_arg_origin_tls, 0, sizeof(__dfsan_arg_origin_tls));
976     internal_memset(&__dfsan_retval_origin_tls, 0,
977                     sizeof(__dfsan_retval_origin_tls));
978   }
979 }
980 
981 static void InitializePlatformEarly() {
982   AvoidCVE_2016_2143();
983 #ifdef DFSAN_RUNTIME_VMA
984   __dfsan::vmaSize =
985     (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
986   if (__dfsan::vmaSize == 39 || __dfsan::vmaSize == 42 ||
987       __dfsan::vmaSize == 48) {
988     __dfsan_shadow_ptr_mask = ShadowMask();
989   } else {
990     Printf("FATAL: DataFlowSanitizer: unsupported VMA range\n");
991     Printf("FATAL: Found %d - Supported 39, 42, and 48\n", __dfsan::vmaSize);
992     Die();
993   }
994 #endif
995 }
996 
997 static void dfsan_fini() {
998   if (internal_strcmp(flags().dump_labels_at_exit, "") != 0) {
999     fd_t fd = OpenFile(flags().dump_labels_at_exit, WrOnly);
1000     if (fd == kInvalidFd) {
1001       Report("WARNING: DataFlowSanitizer: unable to open output file %s\n",
1002              flags().dump_labels_at_exit);
1003       return;
1004     }
1005 
1006     Report("INFO: DataFlowSanitizer: dumping labels to %s\n",
1007            flags().dump_labels_at_exit);
1008     dfsan_dump_labels(fd);
1009     CloseFile(fd);
1010   }
1011 }
1012 
1013 extern "C" void dfsan_flush() {
1014   if (!MmapFixedSuperNoReserve(ShadowAddr(), UnusedAddr() - ShadowAddr()))
1015     Die();
1016 }
1017 
1018 static void DFsanInit(int argc, char **argv, char **envp) {
1019   CHECK(!dfsan_init_is_running);
1020   if (dfsan_inited)
1021     return;
1022   dfsan_init_is_running = true;
1023   SanitizerToolName = "DataflowSanitizer";
1024 
1025   InitializeFlags();
1026 
1027   ::InitializePlatformEarly();
1028 
1029   dfsan_flush();
1030   if (common_flags()->use_madv_dontdump)
1031     DontDumpShadowMemory(ShadowAddr(), UnusedAddr() - ShadowAddr());
1032 
1033   // Protect the region of memory we don't use, to preserve the one-to-one
1034   // mapping from application to shadow memory. But if ASLR is disabled, Linux
1035   // will load our executable in the middle of our unused region. This mostly
1036   // works so long as the program doesn't use too much memory. We support this
1037   // case by disabling memory protection when ASLR is disabled.
1038   uptr init_addr = (uptr)&DFsanInit;
1039   if (!(init_addr >= UnusedAddr() && init_addr < AppAddr()))
1040     MmapFixedNoAccess(UnusedAddr(), AppAddr() - UnusedAddr());
1041 
1042   InitializeInterceptors();
1043 
1044   // Register the fini callback to run when the program terminates successfully
1045   // or it is killed by the runtime.
1046   Atexit(dfsan_fini);
1047   AddDieCallback(dfsan_fini);
1048 
1049   // Set up threads
1050   DFsanTSDInit(DFsanTSDDtor);
1051 
1052   dfsan_allocator_init();
1053 
1054   DFsanThread *main_thread = DFsanThread::Create(nullptr, nullptr, nullptr);
1055   SetCurrentThread(main_thread);
1056   main_thread->ThreadStart();
1057 
1058   __dfsan_label_info[kInitializingLabel].desc = "<init label>";
1059 
1060   dfsan_init_is_running = false;
1061   dfsan_inited = true;
1062 }
1063 
1064 namespace __dfsan {
1065 
1066 void dfsan_init() { DFsanInit(0, nullptr, nullptr); }
1067 
1068 }  // namespace __dfsan
1069 
1070 #if SANITIZER_CAN_USE_PREINIT_ARRAY
1071 __attribute__((section(".preinit_array"),
1072                used)) static void (*dfsan_init_ptr)(int, char **,
1073                                                     char **) = DFsanInit;
1074 #endif
1075