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