]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep.cc
Merge lldb trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_coverage_libcdep.cc
1 //===-- sanitizer_coverage.cc ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Sanitizer Coverage.
11 // This file implements run-time support for a poor man's coverage tool.
12 //
13 // Compiler instrumentation:
14 // For every interesting basic block the compiler injects the following code:
15 // if (Guard < 0) {
16 //    __sanitizer_cov(&Guard);
17 // }
18 // At the module start up time __sanitizer_cov_module_init sets the guards
19 // to consecutive negative numbers (-1, -2, -3, ...).
20 // It's fine to call __sanitizer_cov more than once for a given block.
21 //
22 // Run-time:
23 //  - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
24 //    and atomically set Guard to -Guard.
25 //  - __sanitizer_cov_dump: dump the coverage data to disk.
26 //  For every module of the current process that has coverage data
27 //  this will create a file module_name.PID.sancov.
28 //
29 // The file format is simple: the first 8 bytes is the magic,
30 // one of 0xC0BFFFFFFFFFFF64 and 0xC0BFFFFFFFFFFF32. The last byte of the
31 // magic defines the size of the following offsets.
32 // The rest of the data is the offsets in the module.
33 //
34 // Eventually, this coverage implementation should be obsoleted by a more
35 // powerful general purpose Clang/LLVM coverage instrumentation.
36 // Consider this implementation as prototype.
37 //
38 // FIXME: support (or at least test with) dlclose.
39 //===----------------------------------------------------------------------===//
40
41 #include "sanitizer_allocator_internal.h"
42 #include "sanitizer_common.h"
43 #include "sanitizer_libc.h"
44 #include "sanitizer_mutex.h"
45 #include "sanitizer_procmaps.h"
46 #include "sanitizer_stacktrace.h"
47 #include "sanitizer_symbolizer.h"
48 #include "sanitizer_flags.h"
49
50 using namespace __sanitizer;
51
52 static const u64 kMagic64 = 0xC0BFFFFFFFFFFF64ULL;
53 static const u64 kMagic32 = 0xC0BFFFFFFFFFFF32ULL;
54 static const uptr kNumWordsForMagic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
55 static const u64 kMagic = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
56
57 static atomic_uint32_t dump_once_guard;  // Ensure that CovDump runs only once.
58
59 static atomic_uintptr_t coverage_counter;
60 static atomic_uintptr_t caller_callee_counter;
61
62 static void ResetGlobalCounters() {
63   return atomic_store(&coverage_counter, 0, memory_order_relaxed);
64   return atomic_store(&caller_callee_counter, 0, memory_order_relaxed);
65 }
66
67 // pc_array is the array containing the covered PCs.
68 // To make the pc_array thread- and async-signal-safe it has to be large enough.
69 // 128M counters "ought to be enough for anybody" (4M on 32-bit).
70
71 // With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
72 // In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
73 // dump current memory layout to another file.
74
75 static bool cov_sandboxed = false;
76 static fd_t cov_fd = kInvalidFd;
77 static unsigned int cov_max_block_size = 0;
78 static bool coverage_enabled = false;
79 static const char *coverage_dir;
80
81 namespace __sanitizer {
82
83 class CoverageData {
84  public:
85   void Init();
86   void Enable();
87   void Disable();
88   void ReInit();
89   void BeforeFork();
90   void AfterFork(int child_pid);
91   void Extend(uptr npcs);
92   void Add(uptr pc, u32 *guard);
93   void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
94                  uptr cache_size);
95   void DumpCallerCalleePairs();
96   void DumpTrace();
97   void DumpAsBitSet();
98   void DumpCounters();
99   void DumpOffsets();
100   void DumpAll();
101
102   ALWAYS_INLINE
103   void TraceBasicBlock(u32 *id);
104
105   void InitializeGuardArray(s32 *guards);
106   void InitializeGuards(s32 *guards, uptr n, const char *module_name,
107                         uptr caller_pc);
108   void InitializeCounters(u8 *counters, uptr n);
109   void ReinitializeGuards();
110   uptr GetNumberOf8bitCounters();
111   uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
112
113   uptr *data();
114   uptr size() const;
115
116  private:
117   struct NamedPcRange {
118     const char *copied_module_name;
119     uptr beg, end; // elements [beg,end) in pc_array.
120   };
121
122   void DirectOpen();
123   void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
124   void GetRangeOffsets(const NamedPcRange& r, Symbolizer* s,
125       InternalMmapVector<uptr>* offsets) const;
126
127   // Maximal size pc array may ever grow.
128   // We MmapNoReserve this space to ensure that the array is contiguous.
129   static const uptr kPcArrayMaxSize =
130       FIRST_32_SECOND_64(1 << (SANITIZER_ANDROID ? 24 : 26), 1 << 27);
131   // The amount file mapping for the pc array is grown by.
132   static const uptr kPcArrayMmapSize = 64 * 1024;
133
134   // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
135   // much RAM as it really needs.
136   uptr *pc_array;
137   // Index of the first available pc_array slot.
138   atomic_uintptr_t pc_array_index;
139   // Array size.
140   atomic_uintptr_t pc_array_size;
141   // Current file mapped size of the pc array.
142   uptr pc_array_mapped_size;
143   // Descriptor of the file mapped pc array.
144   fd_t pc_fd;
145
146   // Vector of coverage guard arrays, protected by mu.
147   InternalMmapVectorNoCtor<s32*> guard_array_vec;
148
149   // Vector of module and compilation unit pc ranges.
150   InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
151   InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
152
153   struct CounterAndSize {
154     u8 *counters;
155     uptr n;
156   };
157
158   InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
159   uptr num_8bit_counters;
160
161   // Caller-Callee (cc) array, size and current index.
162   static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
163   uptr **cc_array;
164   atomic_uintptr_t cc_array_index;
165   atomic_uintptr_t cc_array_size;
166
167   // Tracing event array, size and current pointer.
168   // We record all events (basic block entries) in a global buffer of u32
169   // values. Each such value is the index in pc_array.
170   // So far the tracing is highly experimental:
171   //   - not thread-safe;
172   //   - does not support long traces;
173   //   - not tuned for performance.
174   static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
175   u32 *tr_event_array;
176   uptr tr_event_array_size;
177   u32 *tr_event_pointer;
178   static const uptr kTrPcArrayMaxSize    = FIRST_32_SECOND_64(1 << 22, 1 << 27);
179
180   StaticSpinMutex mu;
181 };
182
183 static CoverageData coverage_data;
184
185 void CovUpdateMapping(const char *path, uptr caller_pc = 0);
186
187 void CoverageData::DirectOpen() {
188   InternalScopedString path(kMaxPathLength);
189   internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
190                     coverage_dir, internal_getpid());
191   pc_fd = OpenFile(path.data(), RdWr);
192   if (pc_fd == kInvalidFd) {
193     Report("Coverage: failed to open %s for reading/writing\n", path.data());
194     Die();
195   }
196
197   pc_array_mapped_size = 0;
198   CovUpdateMapping(coverage_dir);
199 }
200
201 void CoverageData::Init() {
202   pc_fd = kInvalidFd;
203 }
204
205 void CoverageData::Enable() {
206   if (pc_array)
207     return;
208   pc_array = reinterpret_cast<uptr *>(
209       MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
210   atomic_store(&pc_array_index, 0, memory_order_relaxed);
211   if (common_flags()->coverage_direct) {
212     atomic_store(&pc_array_size, 0, memory_order_relaxed);
213   } else {
214     atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
215   }
216
217   cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
218       sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
219   atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
220   atomic_store(&cc_array_index, 0, memory_order_relaxed);
221
222   // Allocate tr_event_array with a guard page at the end.
223   tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
224       sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
225       "CovInit::tr_event_array"));
226   MprotectNoAccess(
227       reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
228       GetMmapGranularity());
229   tr_event_array_size = kTrEventArrayMaxSize;
230   tr_event_pointer = tr_event_array;
231
232   num_8bit_counters = 0;
233 }
234
235 void CoverageData::InitializeGuardArray(s32 *guards) {
236   Enable();  // Make sure coverage is enabled at this point.
237   s32 n = guards[0];
238   for (s32 j = 1; j <= n; j++) {
239     uptr idx = atomic_load_relaxed(&pc_array_index);
240     atomic_store_relaxed(&pc_array_index, idx + 1);
241     guards[j] = -static_cast<s32>(idx + 1);
242   }
243 }
244
245 void CoverageData::Disable() {
246   if (pc_array) {
247     UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
248     pc_array = nullptr;
249   }
250   if (cc_array) {
251     UnmapOrDie(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
252     cc_array = nullptr;
253   }
254   if (tr_event_array) {
255     UnmapOrDie(tr_event_array,
256                sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
257                    GetMmapGranularity());
258     tr_event_array = nullptr;
259     tr_event_pointer = nullptr;
260   }
261   if (pc_fd != kInvalidFd) {
262     CloseFile(pc_fd);
263     pc_fd = kInvalidFd;
264   }
265 }
266
267 void CoverageData::ReinitializeGuards() {
268   // Assuming single thread.
269   atomic_store(&pc_array_index, 0, memory_order_relaxed);
270   for (uptr i = 0; i < guard_array_vec.size(); i++)
271     InitializeGuardArray(guard_array_vec[i]);
272 }
273
274 void CoverageData::ReInit() {
275   Disable();
276   if (coverage_enabled) {
277     if (common_flags()->coverage_direct) {
278       // In memory-mapped mode we must extend the new file to the known array
279       // size.
280       uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
281       uptr npcs = size / sizeof(uptr);
282       Enable();
283       if (size) Extend(npcs);
284       if (coverage_enabled) CovUpdateMapping(coverage_dir);
285     } else {
286       Enable();
287     }
288   }
289   // Re-initialize the guards.
290   // We are single-threaded now, no need to grab any lock.
291   CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
292   ReinitializeGuards();
293 }
294
295 void CoverageData::BeforeFork() {
296   mu.Lock();
297 }
298
299 void CoverageData::AfterFork(int child_pid) {
300   // We are single-threaded so it's OK to release the lock early.
301   mu.Unlock();
302   if (child_pid == 0) ReInit();
303 }
304
305 // Extend coverage PC array to fit additional npcs elements.
306 void CoverageData::Extend(uptr npcs) {
307   if (!common_flags()->coverage_direct) return;
308   SpinMutexLock l(&mu);
309
310   uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
311   size += npcs * sizeof(uptr);
312
313   if (coverage_enabled && size > pc_array_mapped_size) {
314     if (pc_fd == kInvalidFd) DirectOpen();
315     CHECK_NE(pc_fd, kInvalidFd);
316
317     uptr new_mapped_size = pc_array_mapped_size;
318     while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
319     CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
320
321     // Extend the file and map the new space at the end of pc_array.
322     uptr res = internal_ftruncate(pc_fd, new_mapped_size);
323     int err;
324     if (internal_iserror(res, &err)) {
325       Printf("failed to extend raw coverage file: %d\n", err);
326       Die();
327     }
328
329     uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
330     void *p = MapWritableFileToMemory((void *)next_map_base,
331                                       new_mapped_size - pc_array_mapped_size,
332                                       pc_fd, pc_array_mapped_size);
333     CHECK_EQ((uptr)p, next_map_base);
334     pc_array_mapped_size = new_mapped_size;
335   }
336
337   atomic_store(&pc_array_size, size, memory_order_release);
338 }
339
340 void CoverageData::InitializeCounters(u8 *counters, uptr n) {
341   if (!counters) return;
342   CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
343   n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
344   SpinMutexLock l(&mu);
345   counters_vec.push_back({counters, n});
346   num_8bit_counters += n;
347 }
348
349 void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
350                                        uptr range_end) {
351   auto sym = Symbolizer::GetOrInit();
352   if (!sym)
353     return;
354   const char *module_name = sym->GetModuleNameForPc(caller_pc);
355   if (!module_name) return;
356   if (module_name_vec.empty() ||
357       module_name_vec.back().copied_module_name != module_name)
358     module_name_vec.push_back({module_name, range_beg, range_end});
359   else
360     module_name_vec.back().end = range_end;
361 }
362
363 void CoverageData::InitializeGuards(s32 *guards, uptr n,
364                                     const char *comp_unit_name,
365                                     uptr caller_pc) {
366   // The array 'guards' has n+1 elements, we use the element zero
367   // to store 'n'.
368   CHECK_LT(n, 1 << 30);
369   guards[0] = static_cast<s32>(n);
370   InitializeGuardArray(guards);
371   SpinMutexLock l(&mu);
372   uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
373   uptr range_beg = range_end - n;
374   comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
375   guard_array_vec.push_back(guards);
376   UpdateModuleNameVec(caller_pc, range_beg, range_end);
377 }
378
379 static const uptr kBundleCounterBits = 16;
380
381 // When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
382 // we insert the global counter into the first 16 bits of the PC.
383 uptr BundlePcAndCounter(uptr pc, uptr counter) {
384   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
385     return pc;
386   static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
387   if (counter > kMaxCounter)
388     counter = kMaxCounter;
389   CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
390   return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
391 }
392
393 uptr UnbundlePc(uptr bundle) {
394   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
395     return bundle;
396   return (bundle << kBundleCounterBits) >> kBundleCounterBits;
397 }
398
399 uptr UnbundleCounter(uptr bundle) {
400   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
401     return 0;
402   return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
403 }
404
405 // If guard is negative, atomically set it to -guard and store the PC in
406 // pc_array.
407 void CoverageData::Add(uptr pc, u32 *guard) {
408   atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
409   s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
410   if (guard_value >= 0) return;
411
412   atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
413   if (!pc_array) return;
414
415   uptr idx = -guard_value - 1;
416   if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
417     return;  // May happen after fork when pc_array_index becomes 0.
418   CHECK_LT(idx * sizeof(uptr),
419            atomic_load(&pc_array_size, memory_order_acquire));
420   uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
421   pc_array[idx] = BundlePcAndCounter(pc, counter);
422 }
423
424 // Registers a pair caller=>callee.
425 // When a given caller is seen for the first time, the callee_cache is added
426 // to the global array cc_array, callee_cache[0] is set to caller and
427 // callee_cache[1] is set to cache_size.
428 // Then we are trying to add callee to callee_cache [2,cache_size) if it is
429 // not there yet.
430 // If the cache is full we drop the callee (may want to fix this later).
431 void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
432                              uptr cache_size) {
433   if (!cc_array) return;
434   atomic_uintptr_t *atomic_callee_cache =
435       reinterpret_cast<atomic_uintptr_t *>(callee_cache);
436   uptr zero = 0;
437   if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
438                                      memory_order_seq_cst)) {
439     uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
440     CHECK_LT(idx * sizeof(uptr),
441              atomic_load(&cc_array_size, memory_order_acquire));
442     callee_cache[1] = cache_size;
443     cc_array[idx] = callee_cache;
444   }
445   CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
446   for (uptr i = 2; i < cache_size; i++) {
447     uptr was = 0;
448     if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
449                                        memory_order_seq_cst)) {
450       atomic_fetch_add(&caller_callee_counter, 1, memory_order_relaxed);
451       return;
452     }
453     if (was == callee)  // Already have this callee.
454       return;
455   }
456 }
457
458 uptr CoverageData::GetNumberOf8bitCounters() {
459   return num_8bit_counters;
460 }
461
462 // Map every 8bit counter to a 8-bit bitset and clear the counter.
463 uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
464   uptr num_new_bits = 0;
465   uptr cur = 0;
466   // For better speed we map 8 counters to 8 bytes of bitset at once.
467   static const uptr kBatchSize = 8;
468   CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
469   for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
470     u8 *c = counters_vec[i].counters;
471     uptr n = counters_vec[i].n;
472     CHECK_EQ(n % 16, 0);
473     CHECK_EQ(cur % kBatchSize, 0);
474     CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
475     if (!bitset) {
476       internal_bzero_aligned16(c, n);
477       cur += n;
478       continue;
479     }
480     for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
481       CHECK_LT(cur, num_8bit_counters);
482       u64 *pc64 = reinterpret_cast<u64*>(c + j);
483       u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
484       u64 c64 = *pc64;
485       u64 old_bits_64 = *pb64;
486       u64 new_bits_64 = old_bits_64;
487       if (c64) {
488         *pc64 = 0;
489         for (uptr k = 0; k < kBatchSize; k++) {
490           u64 x = (c64 >> (8 * k)) & 0xff;
491           if (x) {
492             u64 bit = 0;
493             /**/ if (x >= 128) bit = 128;
494             else if (x >= 32) bit = 64;
495             else if (x >= 16) bit = 32;
496             else if (x >= 8) bit = 16;
497             else if (x >= 4) bit = 8;
498             else if (x >= 3) bit = 4;
499             else if (x >= 2) bit = 2;
500             else if (x >= 1) bit = 1;
501             u64 mask = bit << (8 * k);
502             if (!(new_bits_64 & mask)) {
503               num_new_bits++;
504               new_bits_64 |= mask;
505             }
506           }
507         }
508         *pb64 = new_bits_64;
509       }
510     }
511   }
512   CHECK_EQ(cur, num_8bit_counters);
513   return num_new_bits;
514 }
515
516 uptr *CoverageData::data() {
517   return pc_array;
518 }
519
520 uptr CoverageData::size() const {
521   return atomic_load(&pc_array_index, memory_order_relaxed);
522 }
523
524 // Block layout for packed file format: header, followed by module name (no
525 // trailing zero), followed by data blob.
526 struct CovHeader {
527   int pid;
528   unsigned int module_name_length;
529   unsigned int data_length;
530 };
531
532 static void CovWritePacked(int pid, const char *module, const void *blob,
533                            unsigned int blob_size) {
534   if (cov_fd == kInvalidFd) return;
535   unsigned module_name_length = internal_strlen(module);
536   CovHeader header = {pid, module_name_length, blob_size};
537
538   if (cov_max_block_size == 0) {
539     // Writing to a file. Just go ahead.
540     WriteToFile(cov_fd, &header, sizeof(header));
541     WriteToFile(cov_fd, module, module_name_length);
542     WriteToFile(cov_fd, blob, blob_size);
543   } else {
544     // Writing to a socket. We want to split the data into appropriately sized
545     // blocks.
546     InternalScopedBuffer<char> block(cov_max_block_size);
547     CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
548     uptr header_size_with_module = sizeof(header) + module_name_length;
549     CHECK_LT(header_size_with_module, cov_max_block_size);
550     unsigned int max_payload_size =
551         cov_max_block_size - header_size_with_module;
552     char *block_pos = block.data();
553     internal_memcpy(block_pos, &header, sizeof(header));
554     block_pos += sizeof(header);
555     internal_memcpy(block_pos, module, module_name_length);
556     block_pos += module_name_length;
557     char *block_data_begin = block_pos;
558     const char *blob_pos = (const char *)blob;
559     while (blob_size > 0) {
560       unsigned int payload_size = Min(blob_size, max_payload_size);
561       blob_size -= payload_size;
562       internal_memcpy(block_data_begin, blob_pos, payload_size);
563       blob_pos += payload_size;
564       ((CovHeader *)block.data())->data_length = payload_size;
565       WriteToFile(cov_fd, block.data(), header_size_with_module + payload_size);
566     }
567   }
568 }
569
570 // If packed = false: <name>.<pid>.<sancov> (name = module name).
571 // If packed = true and name == 0: <pid>.<sancov>.<packed>.
572 // If packed = true and name != 0: <name>.<sancov>.<packed> (name is
573 // user-supplied).
574 static fd_t CovOpenFile(InternalScopedString *path, bool packed,
575                        const char *name, const char *extension = "sancov") {
576   path->clear();
577   if (!packed) {
578     CHECK(name);
579     path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
580                 extension);
581   } else {
582     if (!name)
583       path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
584                   extension);
585     else
586       path->append("%s/%s.%s.packed", coverage_dir, name, extension);
587   }
588   error_t err;
589   fd_t fd = OpenFile(path->data(), WrOnly, &err);
590   if (fd == kInvalidFd)
591     Report("SanitizerCoverage: failed to open %s for writing (reason: %d)\n",
592            path->data(), err);
593   return fd;
594 }
595
596 // Dump trace PCs and trace events into two separate files.
597 void CoverageData::DumpTrace() {
598   uptr max_idx = tr_event_pointer - tr_event_array;
599   if (!max_idx) return;
600   auto sym = Symbolizer::GetOrInit();
601   if (!sym)
602     return;
603   InternalScopedString out(32 << 20);
604   for (uptr i = 0, n = size(); i < n; i++) {
605     const char *module_name = "<unknown>";
606     uptr module_address = 0;
607     sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
608                                      &module_address);
609     out.append("%s 0x%zx\n", module_name, module_address);
610   }
611   InternalScopedString path(kMaxPathLength);
612   fd_t fd = CovOpenFile(&path, false, "trace-points");
613   if (fd == kInvalidFd) return;
614   WriteToFile(fd, out.data(), out.length());
615   CloseFile(fd);
616
617   fd = CovOpenFile(&path, false, "trace-compunits");
618   if (fd == kInvalidFd) return;
619   out.clear();
620   for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
621     out.append("%s\n", comp_unit_name_vec[i].copied_module_name);
622   WriteToFile(fd, out.data(), out.length());
623   CloseFile(fd);
624
625   fd = CovOpenFile(&path, false, "trace-events");
626   if (fd == kInvalidFd) return;
627   uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
628   u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
629   // The trace file could be huge, and may not be written with a single syscall.
630   while (bytes_to_write) {
631     uptr actually_written;
632     if (WriteToFile(fd, event_bytes, bytes_to_write, &actually_written) &&
633         actually_written <= bytes_to_write) {
634       bytes_to_write -= actually_written;
635       event_bytes += actually_written;
636     } else {
637       break;
638     }
639   }
640   CloseFile(fd);
641   VReport(1, " CovDump: Trace: %zd PCs written\n", size());
642   VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
643 }
644
645 // This function dumps the caller=>callee pairs into a file as a sequence of
646 // lines like "module_name offset".
647 void CoverageData::DumpCallerCalleePairs() {
648   uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
649   if (!max_idx) return;
650   auto sym = Symbolizer::GetOrInit();
651   if (!sym)
652     return;
653   InternalScopedString out(32 << 20);
654   uptr total = 0;
655   for (uptr i = 0; i < max_idx; i++) {
656     uptr *cc_cache = cc_array[i];
657     CHECK(cc_cache);
658     uptr caller = cc_cache[0];
659     uptr n_callees = cc_cache[1];
660     const char *caller_module_name = "<unknown>";
661     uptr caller_module_address = 0;
662     sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
663                                      &caller_module_address);
664     for (uptr j = 2; j < n_callees; j++) {
665       uptr callee = cc_cache[j];
666       if (!callee) break;
667       total++;
668       const char *callee_module_name = "<unknown>";
669       uptr callee_module_address = 0;
670       sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
671                                        &callee_module_address);
672       out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
673                  caller_module_address, callee_module_name,
674                  callee_module_address);
675     }
676   }
677   InternalScopedString path(kMaxPathLength);
678   fd_t fd = CovOpenFile(&path, false, "caller-callee");
679   if (fd == kInvalidFd) return;
680   WriteToFile(fd, out.data(), out.length());
681   CloseFile(fd);
682   VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
683 }
684
685 // Record the current PC into the event buffer.
686 // Every event is a u32 value (index in tr_pc_array_index) so we compute
687 // it once and then cache in the provided 'cache' storage.
688 //
689 // This function will eventually be inlined by the compiler.
690 void CoverageData::TraceBasicBlock(u32 *id) {
691   // Will trap here if
692   //  1. coverage is not enabled at run-time.
693   //  2. The array tr_event_array is full.
694   *tr_event_pointer = *id - 1;
695   tr_event_pointer++;
696 }
697
698 void CoverageData::DumpCounters() {
699   if (!common_flags()->coverage_counters) return;
700   uptr n = coverage_data.GetNumberOf8bitCounters();
701   if (!n) return;
702   InternalScopedBuffer<u8> bitset(n);
703   coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
704   InternalScopedString path(kMaxPathLength);
705
706   for (uptr m = 0; m < module_name_vec.size(); m++) {
707     auto r = module_name_vec[m];
708     CHECK(r.copied_module_name);
709     CHECK_LE(r.beg, r.end);
710     CHECK_LE(r.end, size());
711     const char *base_name = StripModuleName(r.copied_module_name);
712     fd_t fd =
713         CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
714     if (fd == kInvalidFd) return;
715     WriteToFile(fd, bitset.data() + r.beg, r.end - r.beg);
716     CloseFile(fd);
717     VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
718             base_name);
719   }
720 }
721
722 void CoverageData::DumpAsBitSet() {
723   if (!common_flags()->coverage_bitset) return;
724   if (!size()) return;
725   InternalScopedBuffer<char> out(size());
726   InternalScopedString path(kMaxPathLength);
727   for (uptr m = 0; m < module_name_vec.size(); m++) {
728     uptr n_set_bits = 0;
729     auto r = module_name_vec[m];
730     CHECK(r.copied_module_name);
731     CHECK_LE(r.beg, r.end);
732     CHECK_LE(r.end, size());
733     for (uptr i = r.beg; i < r.end; i++) {
734       uptr pc = UnbundlePc(pc_array[i]);
735       out[i] = pc ? '1' : '0';
736       if (pc)
737         n_set_bits++;
738     }
739     const char *base_name = StripModuleName(r.copied_module_name);
740     fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
741     if (fd == kInvalidFd) return;
742     WriteToFile(fd, out.data() + r.beg, r.end - r.beg);
743     CloseFile(fd);
744     VReport(1,
745             " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
746             r.end - r.beg, base_name, n_set_bits);
747   }
748 }
749
750
751 void CoverageData::GetRangeOffsets(const NamedPcRange& r, Symbolizer* sym,
752     InternalMmapVector<uptr>* offsets) const {
753   offsets->clear();
754   for (uptr i = 0; i < kNumWordsForMagic; i++)
755     offsets->push_back(0);
756   CHECK(r.copied_module_name);
757   CHECK_LE(r.beg, r.end);
758   CHECK_LE(r.end, size());
759   for (uptr i = r.beg; i < r.end; i++) {
760     uptr pc = UnbundlePc(pc_array[i]);
761     uptr counter = UnbundleCounter(pc_array[i]);
762     if (!pc) continue; // Not visited.
763     uptr offset = 0;
764     sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
765     offsets->push_back(BundlePcAndCounter(offset, counter));
766   }
767
768   CHECK_GE(offsets->size(), kNumWordsForMagic);
769   SortArray(offsets->data(), offsets->size());
770   for (uptr i = 0; i < offsets->size(); i++)
771     (*offsets)[i] = UnbundlePc((*offsets)[i]);
772 }
773
774 static void GenerateHtmlReport(const InternalMmapVector<char *> &cov_files) {
775   if (!common_flags()->html_cov_report) {
776     return;
777   }
778   char *sancov_path = FindPathToBinary(common_flags()->sancov_path);
779   if (sancov_path == nullptr) {
780     return;
781   }
782
783   InternalMmapVector<char *> sancov_argv(cov_files.size() * 2 + 3);
784   sancov_argv.push_back(sancov_path);
785   sancov_argv.push_back(internal_strdup("-html-report"));
786   auto argv_deleter = at_scope_exit([&] {
787     for (uptr i = 0; i < sancov_argv.size(); ++i) {
788       InternalFree(sancov_argv[i]);
789     }
790   });
791
792   for (const auto &cov_file : cov_files) {
793     sancov_argv.push_back(internal_strdup(cov_file));
794   }
795
796   {
797     ListOfModules modules;
798     modules.init();
799     for (const LoadedModule &module : modules) {
800       sancov_argv.push_back(internal_strdup(module.full_name()));
801     }
802   }
803
804   InternalScopedString report_path(kMaxPathLength);
805   fd_t report_fd =
806       CovOpenFile(&report_path, false /* packed */, GetProcessName(), "html");
807   int pid = StartSubprocess(sancov_argv[0], sancov_argv.data(),
808                             kInvalidFd /* stdin */, report_fd /* std_out */);
809   if (pid > 0) {
810     int result = WaitForProcess(pid);
811     if (result == 0)
812       Printf("coverage report generated to %s\n", report_path.data());
813   }
814 }
815
816 void CoverageData::DumpOffsets() {
817   auto sym = Symbolizer::GetOrInit();
818   if (!common_flags()->coverage_pcs) return;
819   CHECK_NE(sym, nullptr);
820   InternalMmapVector<uptr> offsets(0);
821   InternalScopedString path(kMaxPathLength);
822
823   InternalMmapVector<char *> cov_files(module_name_vec.size());
824   auto cov_files_deleter = at_scope_exit([&] {
825     for (uptr i = 0; i < cov_files.size(); ++i) {
826       InternalFree(cov_files[i]);
827     }
828   });
829
830   for (uptr m = 0; m < module_name_vec.size(); m++) {
831     auto r = module_name_vec[m];
832     GetRangeOffsets(r, sym, &offsets);
833
834     uptr num_offsets = offsets.size() - kNumWordsForMagic;
835     u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
836     CHECK_EQ(*magic_p, 0ULL);
837     // FIXME: we may want to write 32-bit offsets even in 64-mode
838     // if all the offsets are small enough.
839     *magic_p = kMagic;
840
841     const char *module_name = StripModuleName(r.copied_module_name);
842     if (cov_sandboxed) {
843       if (cov_fd != kInvalidFd) {
844         CovWritePacked(internal_getpid(), module_name, offsets.data(),
845                        offsets.size() * sizeof(offsets[0]));
846         VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
847       }
848     } else {
849       // One file per module per process.
850       fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
851       if (fd == kInvalidFd) continue;
852       WriteToFile(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
853       CloseFile(fd);
854       cov_files.push_back(internal_strdup(path.data()));
855       VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
856     }
857   }
858   if (cov_fd != kInvalidFd)
859     CloseFile(cov_fd);
860
861   GenerateHtmlReport(cov_files);
862 }
863
864 void CoverageData::DumpAll() {
865   if (!coverage_enabled || common_flags()->coverage_direct) return;
866   if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
867     return;
868   DumpAsBitSet();
869   DumpCounters();
870   DumpTrace();
871   DumpOffsets();
872   DumpCallerCalleePairs();
873 }
874
875 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
876   if (!args) return;
877   if (!coverage_enabled) return;
878   cov_sandboxed = args->coverage_sandboxed;
879   if (!cov_sandboxed) return;
880   cov_max_block_size = args->coverage_max_block_size;
881   if (args->coverage_fd >= 0) {
882     cov_fd = (fd_t)args->coverage_fd;
883   } else {
884     InternalScopedString path(kMaxPathLength);
885     // Pre-open the file now. The sandbox won't allow us to do it later.
886     cov_fd = CovOpenFile(&path, true /* packed */, nullptr);
887   }
888 }
889
890 fd_t MaybeOpenCovFile(const char *name) {
891   CHECK(name);
892   if (!coverage_enabled) return kInvalidFd;
893   InternalScopedString path(kMaxPathLength);
894   return CovOpenFile(&path, true /* packed */, name);
895 }
896
897 void CovBeforeFork() {
898   coverage_data.BeforeFork();
899 }
900
901 void CovAfterFork(int child_pid) {
902   coverage_data.AfterFork(child_pid);
903 }
904
905 static void MaybeDumpCoverage() {
906   if (common_flags()->coverage)
907     __sanitizer_cov_dump();
908 }
909
910 void InitializeCoverage(bool enabled, const char *dir) {
911   if (coverage_enabled)
912     return;  // May happen if two sanitizer enable coverage in the same process.
913   coverage_enabled = enabled;
914   coverage_dir = dir;
915   coverage_data.Init();
916   if (enabled) coverage_data.Enable();
917   if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
918   AddDieCallback(MaybeDumpCoverage);
919 }
920
921 void ReInitializeCoverage(bool enabled, const char *dir) {
922   coverage_enabled = enabled;
923   coverage_dir = dir;
924   coverage_data.ReInit();
925 }
926
927 void CoverageUpdateMapping() {
928   if (coverage_enabled)
929     CovUpdateMapping(coverage_dir);
930 }
931
932 } // namespace __sanitizer
933
934 extern "C" {
935 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
936   coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
937                     guard);
938 }
939 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
940   atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
941   if (static_cast<s32>(
942           __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
943     __sanitizer_cov(guard);
944 }
945 SANITIZER_INTERFACE_ATTRIBUTE void
946 __sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
947   coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
948                           callee, callee_cache16, 16);
949 }
950 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
951   coverage_enabled = true;
952   coverage_dir = common_flags()->coverage_dir;
953   coverage_data.Init();
954 }
955 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
956   coverage_data.DumpAll();
957 #if SANITIZER_LINUX
958   __sanitizer_dump_trace_pc_guard_coverage();
959 #endif
960 }
961 SANITIZER_INTERFACE_ATTRIBUTE void
962 __sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
963                             const char *comp_unit_name) {
964   coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
965   coverage_data.InitializeCounters(counters, npcs);
966   if (!common_flags()->coverage_direct) return;
967   if (SANITIZER_ANDROID && coverage_enabled) {
968     // dlopen/dlclose interceptors do not work on Android, so we rely on
969     // Extend() calls to update .sancov.map.
970     CovUpdateMapping(coverage_dir, GET_CALLER_PC());
971   }
972   coverage_data.Extend(npcs);
973 }
974 SANITIZER_INTERFACE_ATTRIBUTE
975 sptr __sanitizer_maybe_open_cov_file(const char *name) {
976   return (sptr)MaybeOpenCovFile(name);
977 }
978 SANITIZER_INTERFACE_ATTRIBUTE
979 uptr __sanitizer_get_total_unique_coverage() {
980   return atomic_load(&coverage_counter, memory_order_relaxed);
981 }
982
983 SANITIZER_INTERFACE_ATTRIBUTE
984 uptr __sanitizer_get_total_unique_caller_callee_pairs() {
985   return atomic_load(&caller_callee_counter, memory_order_relaxed);
986 }
987
988 SANITIZER_INTERFACE_ATTRIBUTE
989 void __sanitizer_cov_trace_func_enter(u32 *id) {
990   __sanitizer_cov_with_check(id);
991   coverage_data.TraceBasicBlock(id);
992 }
993 SANITIZER_INTERFACE_ATTRIBUTE
994 void __sanitizer_cov_trace_basic_block(u32 *id) {
995   __sanitizer_cov_with_check(id);
996   coverage_data.TraceBasicBlock(id);
997 }
998 SANITIZER_INTERFACE_ATTRIBUTE
999 void __sanitizer_reset_coverage() {
1000   ResetGlobalCounters();
1001   coverage_data.ReinitializeGuards();
1002   internal_bzero_aligned16(
1003       coverage_data.data(),
1004       RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
1005 }
1006 SANITIZER_INTERFACE_ATTRIBUTE
1007 uptr __sanitizer_get_coverage_guards(uptr **data) {
1008   *data = coverage_data.data();
1009   return coverage_data.size();
1010 }
1011
1012 SANITIZER_INTERFACE_ATTRIBUTE
1013 uptr __sanitizer_get_number_of_counters() {
1014   return coverage_data.GetNumberOf8bitCounters();
1015 }
1016
1017 SANITIZER_INTERFACE_ATTRIBUTE
1018 uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
1019   return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
1020 }
1021 // Default empty implementations (weak). Users should redefine them.
1022 #if !SANITIZER_WINDOWS  // weak does not work on Windows.
1023 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1024 void __sanitizer_cov_trace_cmp() {}
1025 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1026 void __sanitizer_cov_trace_cmp1() {}
1027 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1028 void __sanitizer_cov_trace_cmp2() {}
1029 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1030 void __sanitizer_cov_trace_cmp4() {}
1031 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1032 void __sanitizer_cov_trace_cmp8() {}
1033 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1034 void __sanitizer_cov_trace_switch() {}
1035 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1036 void __sanitizer_cov_trace_div4() {}
1037 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1038 void __sanitizer_cov_trace_div8() {}
1039 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1040 void __sanitizer_cov_trace_gep() {}
1041 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
1042 void __sanitizer_cov_trace_pc_indir() {}
1043 #endif  // !SANITIZER_WINDOWS
1044 } // extern "C"