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