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