1 //===-- dfsan.cc ----------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of DataFlowSanitizer.
12 // DataFlowSanitizer runtime. This file defines the public interface to
13 // DataFlowSanitizer as well as the definition of certain runtime functions
14 // called automatically by the compiler (specifically the instrumentation pass
15 // in llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp).
17 // The public interface is defined in include/sanitizer/dfsan_interface.h whose
18 // functions are prefixed dfsan_ while the compiler interface functions are
20 //===----------------------------------------------------------------------===//
22 #include "sanitizer_common/sanitizer_atomic.h"
23 #include "sanitizer_common/sanitizer_common.h"
24 #include "sanitizer_common/sanitizer_flags.h"
25 #include "sanitizer_common/sanitizer_flag_parser.h"
26 #include "sanitizer_common/sanitizer_libc.h"
28 #include "dfsan/dfsan.h"
30 using namespace __dfsan;
32 typedef atomic_uint16_t atomic_dfsan_label;
33 static const dfsan_label kInitializingLabel = -1;
35 static const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8);
37 static atomic_dfsan_label __dfsan_last_label;
38 static dfsan_label_info __dfsan_label_info[kNumLabels];
40 Flags __dfsan::flags_data;
42 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_retval_tls;
43 SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_arg_tls[64];
45 SANITIZER_INTERFACE_ATTRIBUTE uptr __dfsan_shadow_ptr_mask;
47 // On Linux/x86_64, memory is laid out as follows:
49 // +--------------------+ 0x800000000000 (top of memory)
50 // | application memory |
51 // +--------------------+ 0x700000008000 (kAppAddr)
55 // +--------------------+ 0x200200000000 (kUnusedAddr)
57 // +--------------------+ 0x200000000000 (kUnionTableAddr)
59 // +--------------------+ 0x000000010000 (kShadowAddr)
60 // | reserved by kernel |
61 // +--------------------+ 0x000000000000
63 // To derive a shadow memory address from an application memory address,
64 // bits 44-46 are cleared to bring the address into the range
65 // [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
66 // account for the double byte representation of shadow labels and move the
67 // address into the shadow memory range. See the function shadow_for below.
69 // On Linux/MIPS64, memory is laid out as follows:
71 // +--------------------+ 0x10000000000 (top of memory)
72 // | application memory |
73 // +--------------------+ 0xF000008000 (kAppAddr)
77 // +--------------------+ 0x2200000000 (kUnusedAddr)
79 // +--------------------+ 0x2000000000 (kUnionTableAddr)
81 // +--------------------+ 0x0000010000 (kShadowAddr)
82 // | reserved by kernel |
83 // +--------------------+ 0x0000000000
85 // On Linux/AArch64 (39-bit VMA), memory is laid out as follow:
87 // +--------------------+ 0x8000000000 (top of memory)
88 // | application memory |
89 // +--------------------+ 0x7000008000 (kAppAddr)
93 // +--------------------+ 0x1200000000 (kUnusedAddr)
95 // +--------------------+ 0x1000000000 (kUnionTableAddr)
97 // +--------------------+ 0x0000010000 (kShadowAddr)
98 // | reserved by kernel |
99 // +--------------------+ 0x0000000000
101 // On Linux/AArch64 (42-bit VMA), memory is laid out as follow:
103 // +--------------------+ 0x40000000000 (top of memory)
104 // | application memory |
105 // +--------------------+ 0x3ff00008000 (kAppAddr)
109 // +--------------------+ 0x1200000000 (kUnusedAddr)
111 // +--------------------+ 0x8000000000 (kUnionTableAddr)
113 // +--------------------+ 0x0000010000 (kShadowAddr)
114 // | reserved by kernel |
115 // +--------------------+ 0x0000000000
117 // On Linux/AArch64 (48-bit VMA), memory is laid out as follow:
119 // +--------------------+ 0x1000000000000 (top of memory)
120 // | application memory |
121 // +--------------------+ 0xffff00008000 (kAppAddr)
123 // +--------------------+ 0xaaaab0000000 (top of PIE address)
124 // | application PIE |
125 // +--------------------+ 0xaaaaa0000000 (top of PIE address)
129 // +--------------------+ 0x1200000000 (kUnusedAddr)
131 // +--------------------+ 0x8000000000 (kUnionTableAddr)
133 // +--------------------+ 0x0000010000 (kShadowAddr)
134 // | reserved by kernel |
135 // +--------------------+ 0x0000000000
137 typedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels];
139 #ifdef DFSAN_RUNTIME_VMA
140 // Runtime detected VMA size.
141 int __dfsan::vmaSize;
144 static uptr UnusedAddr() {
145 return MappingArchImpl<MAPPING_UNION_TABLE_ADDR>()
146 + sizeof(dfsan_union_table_t);
149 static atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) {
150 return &(*(dfsan_union_table_t *) UnionTableAddr())[l1][l2];
153 // Checks we do not run out of labels.
154 static void dfsan_check_label(dfsan_label label) {
155 if (label == kInitializingLabel) {
156 Report("FATAL: DataFlowSanitizer: out of labels\n");
161 // Resolves the union of two unequal labels. Nonequality is a precondition for
162 // this function (the instrumentation pass inlines the equality test).
163 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
164 dfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) {
175 atomic_dfsan_label *table_ent = union_table(l1, l2);
176 // We need to deal with the case where two threads concurrently request
177 // a union of the same pair of labels. If the table entry is uninitialized,
178 // (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel
179 // (i.e. -1) to mark that we are initializing it.
180 dfsan_label label = 0;
181 if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel,
182 memory_order_acquire)) {
183 // Check whether l2 subsumes l1. We don't need to check whether l1
184 // subsumes l2 because we are guaranteed here that l1 < l2, and (at least
185 // in the cases we are interested in) a label may only subsume labels
186 // created earlier (i.e. with a lower numerical value).
187 if (__dfsan_label_info[l2].l1 == l1 ||
188 __dfsan_label_info[l2].l2 == l1) {
192 atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;
193 dfsan_check_label(label);
194 __dfsan_label_info[label].l1 = l1;
195 __dfsan_label_info[label].l2 = l2;
197 atomic_store(table_ent, label, memory_order_release);
198 } else if (label == kInitializingLabel) {
199 // Another thread is initializing the entry. Wait until it is finished.
201 internal_sched_yield();
202 label = atomic_load(table_ent, memory_order_acquire);
203 } while (label == kInitializingLabel);
208 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
209 dfsan_label __dfsan_union_load(const dfsan_label *ls, uptr n) {
210 dfsan_label label = ls[0];
211 for (uptr i = 1; i != n; ++i) {
212 dfsan_label next_label = ls[i];
213 if (label != next_label)
214 label = __dfsan_union(label, next_label);
219 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
220 void __dfsan_unimplemented(char *fname) {
221 if (flags().warn_unimplemented)
222 Report("WARNING: DataFlowSanitizer: call to uninstrumented function %s\n",
226 // Use '-mllvm -dfsan-debug-nonzero-labels' and break on this function
227 // to try to figure out where labels are being introduced in a nominally
228 // label-free program.
229 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_nonzero_label() {
230 if (flags().warn_nonzero_labels)
231 Report("WARNING: DataFlowSanitizer: saw nonzero label\n");
234 // Indirect call to an uninstrumented vararg function. We don't have a way of
235 // handling these at the moment.
236 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
237 __dfsan_vararg_wrapper(const char *fname) {
238 Report("FATAL: DataFlowSanitizer: unsupported indirect call to vararg "
239 "function %s\n", fname);
243 // Like __dfsan_union, but for use from the client or custom functions. Hence
244 // the equality comparison is done here before calling __dfsan_union.
245 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
246 dfsan_union(dfsan_label l1, dfsan_label l2) {
249 return __dfsan_union(l1, l2);
252 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
253 dfsan_label dfsan_create_label(const char *desc, void *userdata) {
255 atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;
256 dfsan_check_label(label);
257 __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0;
258 __dfsan_label_info[label].desc = desc;
259 __dfsan_label_info[label].userdata = userdata;
263 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
264 void __dfsan_set_label(dfsan_label label, void *addr, uptr size) {
265 for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) {
266 // Don't write the label if it is already the value we need it to be.
267 // In a program where most addresses are not labeled, it is common that
268 // a page of shadow memory is entirely zeroed. The Linux copy-on-write
269 // implementation will share all of the zeroed pages, making a copy of a
270 // page when any value is written. The un-sharing will happen even if
271 // the value written does not change the value in memory. Avoiding the
272 // write when both |label| and |*labelp| are zero dramatically reduces
273 // the amount of real memory used by large programs.
274 if (label == *labelp)
281 SANITIZER_INTERFACE_ATTRIBUTE
282 void dfsan_set_label(dfsan_label label, void *addr, uptr size) {
283 __dfsan_set_label(label, addr, size);
286 SANITIZER_INTERFACE_ATTRIBUTE
287 void dfsan_add_label(dfsan_label label, void *addr, uptr size) {
288 for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)
289 if (*labelp != label)
290 *labelp = __dfsan_union(*labelp, label);
293 // Unlike the other dfsan interface functions the behavior of this function
294 // depends on the label of one of its arguments. Hence it is implemented as a
296 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
297 __dfsw_dfsan_get_label(long data, dfsan_label data_label,
298 dfsan_label *ret_label) {
303 SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
304 dfsan_read_label(const void *addr, uptr size) {
307 return __dfsan_union_load(shadow_for(addr), size);
310 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
311 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) {
312 return &__dfsan_label_info[label];
315 extern "C" SANITIZER_INTERFACE_ATTRIBUTE int
316 dfsan_has_label(dfsan_label label, dfsan_label elem) {
319 const dfsan_label_info *info = dfsan_get_label_info(label);
321 return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem);
327 extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label
328 dfsan_has_label_with_desc(dfsan_label label, const char *desc) {
329 const dfsan_label_info *info = dfsan_get_label_info(label);
331 return dfsan_has_label_with_desc(info->l1, desc) ||
332 dfsan_has_label_with_desc(info->l2, desc);
334 return internal_strcmp(desc, info->desc) == 0;
338 extern "C" SANITIZER_INTERFACE_ATTRIBUTE uptr
339 dfsan_get_label_count(void) {
340 dfsan_label max_label_allocated =
341 atomic_load(&__dfsan_last_label, memory_order_relaxed);
343 return static_cast<uptr>(max_label_allocated);
346 extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
347 dfsan_dump_labels(int fd) {
348 dfsan_label last_label =
349 atomic_load(&__dfsan_last_label, memory_order_relaxed);
351 for (uptr l = 1; l <= last_label; ++l) {
353 internal_snprintf(buf, sizeof(buf), "%u %u %u ", l,
354 __dfsan_label_info[l].l1, __dfsan_label_info[l].l2);
355 WriteToFile(fd, buf, internal_strlen(buf));
356 if (__dfsan_label_info[l].l1 == 0 && __dfsan_label_info[l].desc) {
357 WriteToFile(fd, __dfsan_label_info[l].desc,
358 internal_strlen(__dfsan_label_info[l].desc));
360 WriteToFile(fd, "\n", 1);
364 void Flags::SetDefaults() {
365 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) Name = DefaultValue;
366 #include "dfsan_flags.inc"
370 static void RegisterDfsanFlags(FlagParser *parser, Flags *f) {
371 #define DFSAN_FLAG(Type, Name, DefaultValue, Description) \
372 RegisterFlag(parser, #Name, Description, &f->Name);
373 #include "dfsan_flags.inc"
377 static void InitializeFlags() {
378 SetCommonFlagsDefaults();
379 flags().SetDefaults();
382 RegisterCommonFlags(&parser);
383 RegisterDfsanFlags(&parser, &flags());
384 parser.ParseString(GetEnv("DFSAN_OPTIONS"));
385 InitializeCommonFlags();
386 if (Verbosity()) ReportUnrecognizedFlags();
387 if (common_flags()->help) parser.PrintFlagDescriptions();
390 static void InitializePlatformEarly() {
391 AvoidCVE_2016_2143();
392 #ifdef DFSAN_RUNTIME_VMA
394 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
395 if (__dfsan::vmaSize == 39 || __dfsan::vmaSize == 42 ||
396 __dfsan::vmaSize == 48) {
397 __dfsan_shadow_ptr_mask = ShadowMask();
399 Printf("FATAL: DataFlowSanitizer: unsupported VMA range\n");
400 Printf("FATAL: Found %d - Supported 39, 42, and 48\n", __dfsan::vmaSize);
406 static void dfsan_fini() {
407 if (internal_strcmp(flags().dump_labels_at_exit, "") != 0) {
408 fd_t fd = OpenFile(flags().dump_labels_at_exit, WrOnly);
409 if (fd == kInvalidFd) {
410 Report("WARNING: DataFlowSanitizer: unable to open output file %s\n",
411 flags().dump_labels_at_exit);
415 Report("INFO: DataFlowSanitizer: dumping labels to %s\n",
416 flags().dump_labels_at_exit);
417 dfsan_dump_labels(fd);
422 static void dfsan_init(int argc, char **argv, char **envp) {
425 InitializePlatformEarly();
427 MmapFixedNoReserve(ShadowAddr(), UnusedAddr() - ShadowAddr());
429 // Protect the region of memory we don't use, to preserve the one-to-one
430 // mapping from application to shadow memory. But if ASLR is disabled, Linux
431 // will load our executable in the middle of our unused region. This mostly
432 // works so long as the program doesn't use too much memory. We support this
433 // case by disabling memory protection when ASLR is disabled.
434 uptr init_addr = (uptr)&dfsan_init;
435 if (!(init_addr >= UnusedAddr() && init_addr < AppAddr()))
436 MmapFixedNoAccess(UnusedAddr(), AppAddr() - UnusedAddr());
438 InitializeInterceptors();
440 // Register the fini callback to run when the program terminates successfully
441 // or it is killed by the runtime.
443 AddDieCallback(dfsan_fini);
445 __dfsan_label_info[kInitializingLabel].desc = "<init label>";
448 #if SANITIZER_CAN_USE_PREINIT_ARRAY
449 __attribute__((section(".preinit_array"), used))
450 static void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init;