]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep.cc
Merge ^/head r317281 through r317502.
[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
61 // pc_array is the array containing the covered PCs.
62 // To make the pc_array thread- and async-signal-safe it has to be large enough.
63 // 128M counters "ought to be enough for anybody" (4M on 32-bit).
64
65 // With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
66 // In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
67 // dump current memory layout to another file.
68
69 static bool cov_sandboxed = false;
70 static fd_t cov_fd = kInvalidFd;
71 static unsigned int cov_max_block_size = 0;
72 static bool coverage_enabled = false;
73 static const char *coverage_dir;
74
75 namespace __sanitizer {
76
77 class CoverageData {
78  public:
79   void Init();
80   void Enable();
81   void Disable();
82   void ReInit();
83   void BeforeFork();
84   void AfterFork(int child_pid);
85   void Extend(uptr npcs);
86   void Add(uptr pc, u32 *guard);
87   void DumpAsBitSet();
88   void DumpOffsets();
89   void DumpAll();
90
91   void InitializeGuardArray(s32 *guards);
92   void InitializeGuards(s32 *guards, uptr n, const char *module_name,
93                         uptr caller_pc);
94   void ReinitializeGuards();
95
96   uptr *data();
97   uptr size() const;
98
99  private:
100   struct NamedPcRange {
101     const char *copied_module_name;
102     uptr beg, end; // elements [beg,end) in pc_array.
103   };
104
105   void DirectOpen();
106   void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
107   void GetRangeOffsets(const NamedPcRange& r, Symbolizer* s,
108       InternalMmapVector<uptr>* offsets) const;
109
110   // Maximal size pc array may ever grow.
111   // We MmapNoReserve this space to ensure that the array is contiguous.
112   static const uptr kPcArrayMaxSize =
113       FIRST_32_SECOND_64(1 << (SANITIZER_ANDROID ? 24 : 26), 1 << 27);
114   // The amount file mapping for the pc array is grown by.
115   static const uptr kPcArrayMmapSize = 64 * 1024;
116
117   // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
118   // much RAM as it really needs.
119   uptr *pc_array;
120   // Index of the first available pc_array slot.
121   atomic_uintptr_t pc_array_index;
122   // Array size.
123   atomic_uintptr_t pc_array_size;
124   // Current file mapped size of the pc array.
125   uptr pc_array_mapped_size;
126   // Descriptor of the file mapped pc array.
127   fd_t pc_fd;
128
129   // Vector of coverage guard arrays, protected by mu.
130   InternalMmapVectorNoCtor<s32*> guard_array_vec;
131
132   // Vector of module and compilation unit pc ranges.
133   InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
134   InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
135
136   StaticSpinMutex mu;
137 };
138
139 static CoverageData coverage_data;
140
141 void CovUpdateMapping(const char *path, uptr caller_pc = 0);
142
143 void CoverageData::DirectOpen() {
144   InternalScopedString path(kMaxPathLength);
145   internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
146                     coverage_dir, internal_getpid());
147   pc_fd = OpenFile(path.data(), RdWr);
148   if (pc_fd == kInvalidFd) {
149     Report("Coverage: failed to open %s for reading/writing\n", path.data());
150     Die();
151   }
152
153   pc_array_mapped_size = 0;
154   CovUpdateMapping(coverage_dir);
155 }
156
157 void CoverageData::Init() {
158   pc_fd = kInvalidFd;
159 }
160
161 void CoverageData::Enable() {
162   if (pc_array)
163     return;
164   pc_array = reinterpret_cast<uptr *>(
165       MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
166   atomic_store(&pc_array_index, 0, memory_order_relaxed);
167   if (common_flags()->coverage_direct) {
168     atomic_store(&pc_array_size, 0, memory_order_relaxed);
169   } else {
170     atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
171   }
172 }
173
174 void CoverageData::InitializeGuardArray(s32 *guards) {
175   Enable();  // Make sure coverage is enabled at this point.
176   s32 n = guards[0];
177   for (s32 j = 1; j <= n; j++) {
178     uptr idx = atomic_load_relaxed(&pc_array_index);
179     atomic_store_relaxed(&pc_array_index, idx + 1);
180     guards[j] = -static_cast<s32>(idx + 1);
181   }
182 }
183
184 void CoverageData::Disable() {
185   if (pc_array) {
186     UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
187     pc_array = nullptr;
188   }
189   if (pc_fd != kInvalidFd) {
190     CloseFile(pc_fd);
191     pc_fd = kInvalidFd;
192   }
193 }
194
195 void CoverageData::ReinitializeGuards() {
196   // Assuming single thread.
197   atomic_store(&pc_array_index, 0, memory_order_relaxed);
198   for (uptr i = 0; i < guard_array_vec.size(); i++)
199     InitializeGuardArray(guard_array_vec[i]);
200 }
201
202 void CoverageData::ReInit() {
203   Disable();
204   if (coverage_enabled) {
205     if (common_flags()->coverage_direct) {
206       // In memory-mapped mode we must extend the new file to the known array
207       // size.
208       uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
209       uptr npcs = size / sizeof(uptr);
210       Enable();
211       if (size) Extend(npcs);
212       if (coverage_enabled) CovUpdateMapping(coverage_dir);
213     } else {
214       Enable();
215     }
216   }
217   // Re-initialize the guards.
218   // We are single-threaded now, no need to grab any lock.
219   CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
220   ReinitializeGuards();
221 }
222
223 void CoverageData::BeforeFork() {
224   mu.Lock();
225 }
226
227 void CoverageData::AfterFork(int child_pid) {
228   // We are single-threaded so it's OK to release the lock early.
229   mu.Unlock();
230   if (child_pid == 0) ReInit();
231 }
232
233 // Extend coverage PC array to fit additional npcs elements.
234 void CoverageData::Extend(uptr npcs) {
235   if (!common_flags()->coverage_direct) return;
236   SpinMutexLock l(&mu);
237
238   uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
239   size += npcs * sizeof(uptr);
240
241   if (coverage_enabled && size > pc_array_mapped_size) {
242     if (pc_fd == kInvalidFd) DirectOpen();
243     CHECK_NE(pc_fd, kInvalidFd);
244
245     uptr new_mapped_size = pc_array_mapped_size;
246     while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
247     CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
248
249     // Extend the file and map the new space at the end of pc_array.
250     uptr res = internal_ftruncate(pc_fd, new_mapped_size);
251     int err;
252     if (internal_iserror(res, &err)) {
253       Printf("failed to extend raw coverage file: %d\n", err);
254       Die();
255     }
256
257     uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
258     void *p = MapWritableFileToMemory((void *)next_map_base,
259                                       new_mapped_size - pc_array_mapped_size,
260                                       pc_fd, pc_array_mapped_size);
261     CHECK_EQ((uptr)p, next_map_base);
262     pc_array_mapped_size = new_mapped_size;
263   }
264
265   atomic_store(&pc_array_size, size, memory_order_release);
266 }
267
268 void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
269                                        uptr range_end) {
270   auto sym = Symbolizer::GetOrInit();
271   if (!sym)
272     return;
273   const char *module_name = sym->GetModuleNameForPc(caller_pc);
274   if (!module_name) return;
275   if (module_name_vec.empty() ||
276       module_name_vec.back().copied_module_name != module_name)
277     module_name_vec.push_back({module_name, range_beg, range_end});
278   else
279     module_name_vec.back().end = range_end;
280 }
281
282 void CoverageData::InitializeGuards(s32 *guards, uptr n,
283                                     const char *comp_unit_name,
284                                     uptr caller_pc) {
285   // The array 'guards' has n+1 elements, we use the element zero
286   // to store 'n'.
287   CHECK_LT(n, 1 << 30);
288   guards[0] = static_cast<s32>(n);
289   InitializeGuardArray(guards);
290   SpinMutexLock l(&mu);
291   uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
292   uptr range_beg = range_end - n;
293   comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
294   guard_array_vec.push_back(guards);
295   UpdateModuleNameVec(caller_pc, range_beg, range_end);
296 }
297
298 static const uptr kBundleCounterBits = 16;
299
300 // When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
301 // we insert the global counter into the first 16 bits of the PC.
302 uptr BundlePcAndCounter(uptr pc, uptr counter) {
303   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
304     return pc;
305   static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
306   if (counter > kMaxCounter)
307     counter = kMaxCounter;
308   CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
309   return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
310 }
311
312 uptr UnbundlePc(uptr bundle) {
313   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
314     return bundle;
315   return (bundle << kBundleCounterBits) >> kBundleCounterBits;
316 }
317
318 uptr UnbundleCounter(uptr bundle) {
319   if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
320     return 0;
321   return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
322 }
323
324 // If guard is negative, atomically set it to -guard and store the PC in
325 // pc_array.
326 void CoverageData::Add(uptr pc, u32 *guard) {
327   atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
328   s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
329   if (guard_value >= 0) return;
330
331   atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
332   if (!pc_array) return;
333
334   uptr idx = -guard_value - 1;
335   if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
336     return;  // May happen after fork when pc_array_index becomes 0.
337   CHECK_LT(idx, atomic_load(&pc_array_size, memory_order_acquire));
338   uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
339   pc_array[idx] = BundlePcAndCounter(pc, counter);
340 }
341
342 uptr *CoverageData::data() {
343   return pc_array;
344 }
345
346 uptr CoverageData::size() const {
347   return atomic_load(&pc_array_index, memory_order_relaxed);
348 }
349
350 // Block layout for packed file format: header, followed by module name (no
351 // trailing zero), followed by data blob.
352 struct CovHeader {
353   int pid;
354   unsigned int module_name_length;
355   unsigned int data_length;
356 };
357
358 static void CovWritePacked(int pid, const char *module, const void *blob,
359                            unsigned int blob_size) {
360   if (cov_fd == kInvalidFd) return;
361   unsigned module_name_length = internal_strlen(module);
362   CovHeader header = {pid, module_name_length, blob_size};
363
364   if (cov_max_block_size == 0) {
365     // Writing to a file. Just go ahead.
366     WriteToFile(cov_fd, &header, sizeof(header));
367     WriteToFile(cov_fd, module, module_name_length);
368     WriteToFile(cov_fd, blob, blob_size);
369   } else {
370     // Writing to a socket. We want to split the data into appropriately sized
371     // blocks.
372     InternalScopedBuffer<char> block(cov_max_block_size);
373     CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
374     uptr header_size_with_module = sizeof(header) + module_name_length;
375     CHECK_LT(header_size_with_module, cov_max_block_size);
376     unsigned int max_payload_size =
377         cov_max_block_size - header_size_with_module;
378     char *block_pos = block.data();
379     internal_memcpy(block_pos, &header, sizeof(header));
380     block_pos += sizeof(header);
381     internal_memcpy(block_pos, module, module_name_length);
382     block_pos += module_name_length;
383     char *block_data_begin = block_pos;
384     const char *blob_pos = (const char *)blob;
385     while (blob_size > 0) {
386       unsigned int payload_size = Min(blob_size, max_payload_size);
387       blob_size -= payload_size;
388       internal_memcpy(block_data_begin, blob_pos, payload_size);
389       blob_pos += payload_size;
390       ((CovHeader *)block.data())->data_length = payload_size;
391       WriteToFile(cov_fd, block.data(), header_size_with_module + payload_size);
392     }
393   }
394 }
395
396 // If packed = false: <name>.<pid>.<sancov> (name = module name).
397 // If packed = true and name == 0: <pid>.<sancov>.<packed>.
398 // If packed = true and name != 0: <name>.<sancov>.<packed> (name is
399 // user-supplied).
400 static fd_t CovOpenFile(InternalScopedString *path, bool packed,
401                        const char *name, const char *extension = "sancov") {
402   path->clear();
403   if (!packed) {
404     CHECK(name);
405     path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
406                 extension);
407   } else {
408     if (!name)
409       path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
410                   extension);
411     else
412       path->append("%s/%s.%s.packed", coverage_dir, name, extension);
413   }
414   error_t err;
415   fd_t fd = OpenFile(path->data(), WrOnly, &err);
416   if (fd == kInvalidFd)
417     Report("SanitizerCoverage: failed to open %s for writing (reason: %d)\n",
418            path->data(), err);
419   return fd;
420 }
421
422 void CoverageData::DumpAsBitSet() {
423   if (!common_flags()->coverage_bitset) return;
424   if (!size()) return;
425   InternalScopedBuffer<char> out(size());
426   InternalScopedString path(kMaxPathLength);
427   for (uptr m = 0; m < module_name_vec.size(); m++) {
428     uptr n_set_bits = 0;
429     auto r = module_name_vec[m];
430     CHECK(r.copied_module_name);
431     CHECK_LE(r.beg, r.end);
432     CHECK_LE(r.end, size());
433     for (uptr i = r.beg; i < r.end; i++) {
434       uptr pc = UnbundlePc(pc_array[i]);
435       out[i] = pc ? '1' : '0';
436       if (pc)
437         n_set_bits++;
438     }
439     const char *base_name = StripModuleName(r.copied_module_name);
440     fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
441     if (fd == kInvalidFd) return;
442     WriteToFile(fd, out.data() + r.beg, r.end - r.beg);
443     CloseFile(fd);
444     VReport(1,
445             " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
446             r.end - r.beg, base_name, n_set_bits);
447   }
448 }
449
450
451 void CoverageData::GetRangeOffsets(const NamedPcRange& r, Symbolizer* sym,
452     InternalMmapVector<uptr>* offsets) const {
453   offsets->clear();
454   for (uptr i = 0; i < kNumWordsForMagic; i++)
455     offsets->push_back(0);
456   CHECK(r.copied_module_name);
457   CHECK_LE(r.beg, r.end);
458   CHECK_LE(r.end, size());
459   for (uptr i = r.beg; i < r.end; i++) {
460     uptr pc = UnbundlePc(pc_array[i]);
461     uptr counter = UnbundleCounter(pc_array[i]);
462     if (!pc) continue; // Not visited.
463     uptr offset = 0;
464     sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
465     offsets->push_back(BundlePcAndCounter(offset, counter));
466   }
467
468   CHECK_GE(offsets->size(), kNumWordsForMagic);
469   SortArray(offsets->data(), offsets->size());
470   for (uptr i = 0; i < offsets->size(); i++)
471     (*offsets)[i] = UnbundlePc((*offsets)[i]);
472 }
473
474 static void GenerateHtmlReport(const InternalMmapVector<char *> &cov_files) {
475   if (!common_flags()->html_cov_report) {
476     return;
477   }
478   char *sancov_path = FindPathToBinary(common_flags()->sancov_path);
479   if (sancov_path == nullptr) {
480     return;
481   }
482
483   InternalMmapVector<char *> sancov_argv(cov_files.size() * 2 + 3);
484   sancov_argv.push_back(sancov_path);
485   sancov_argv.push_back(internal_strdup("-html-report"));
486   auto argv_deleter = at_scope_exit([&] {
487     for (uptr i = 0; i < sancov_argv.size(); ++i) {
488       InternalFree(sancov_argv[i]);
489     }
490   });
491
492   for (const auto &cov_file : cov_files) {
493     sancov_argv.push_back(internal_strdup(cov_file));
494   }
495
496   {
497     ListOfModules modules;
498     modules.init();
499     for (const LoadedModule &module : modules) {
500       sancov_argv.push_back(internal_strdup(module.full_name()));
501     }
502   }
503
504   InternalScopedString report_path(kMaxPathLength);
505   fd_t report_fd =
506       CovOpenFile(&report_path, false /* packed */, GetProcessName(), "html");
507   int pid = StartSubprocess(sancov_argv[0], sancov_argv.data(),
508                             kInvalidFd /* stdin */, report_fd /* std_out */);
509   if (pid > 0) {
510     int result = WaitForProcess(pid);
511     if (result == 0)
512       Printf("coverage report generated to %s\n", report_path.data());
513   }
514 }
515
516 void CoverageData::DumpOffsets() {
517   auto sym = Symbolizer::GetOrInit();
518   if (!common_flags()->coverage_pcs) return;
519   CHECK_NE(sym, nullptr);
520   InternalMmapVector<uptr> offsets(0);
521   InternalScopedString path(kMaxPathLength);
522
523   InternalMmapVector<char *> cov_files(module_name_vec.size());
524   auto cov_files_deleter = at_scope_exit([&] {
525     for (uptr i = 0; i < cov_files.size(); ++i) {
526       InternalFree(cov_files[i]);
527     }
528   });
529
530   for (uptr m = 0; m < module_name_vec.size(); m++) {
531     auto r = module_name_vec[m];
532     GetRangeOffsets(r, sym, &offsets);
533
534     uptr num_offsets = offsets.size() - kNumWordsForMagic;
535     u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
536     CHECK_EQ(*magic_p, 0ULL);
537     // FIXME: we may want to write 32-bit offsets even in 64-mode
538     // if all the offsets are small enough.
539     *magic_p = kMagic;
540
541     const char *module_name = StripModuleName(r.copied_module_name);
542     if (cov_sandboxed) {
543       if (cov_fd != kInvalidFd) {
544         CovWritePacked(internal_getpid(), module_name, offsets.data(),
545                        offsets.size() * sizeof(offsets[0]));
546         VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
547       }
548     } else {
549       // One file per module per process.
550       fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
551       if (fd == kInvalidFd) continue;
552       WriteToFile(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
553       CloseFile(fd);
554       cov_files.push_back(internal_strdup(path.data()));
555       VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
556     }
557   }
558   if (cov_fd != kInvalidFd)
559     CloseFile(cov_fd);
560
561   GenerateHtmlReport(cov_files);
562 }
563
564 void CoverageData::DumpAll() {
565   if (!coverage_enabled || common_flags()->coverage_direct) return;
566   if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
567     return;
568   DumpAsBitSet();
569   DumpOffsets();
570 }
571
572 void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
573   if (!args) return;
574   if (!coverage_enabled) return;
575   cov_sandboxed = args->coverage_sandboxed;
576   if (!cov_sandboxed) return;
577   cov_max_block_size = args->coverage_max_block_size;
578   if (args->coverage_fd >= 0) {
579     cov_fd = (fd_t)args->coverage_fd;
580   } else {
581     InternalScopedString path(kMaxPathLength);
582     // Pre-open the file now. The sandbox won't allow us to do it later.
583     cov_fd = CovOpenFile(&path, true /* packed */, nullptr);
584   }
585 }
586
587 fd_t MaybeOpenCovFile(const char *name) {
588   CHECK(name);
589   if (!coverage_enabled) return kInvalidFd;
590   InternalScopedString path(kMaxPathLength);
591   return CovOpenFile(&path, true /* packed */, name);
592 }
593
594 void CovBeforeFork() {
595   coverage_data.BeforeFork();
596 }
597
598 void CovAfterFork(int child_pid) {
599   coverage_data.AfterFork(child_pid);
600 }
601
602 static void MaybeDumpCoverage() {
603   if (common_flags()->coverage)
604     __sanitizer_cov_dump();
605 }
606
607 void InitializeCoverage(bool enabled, const char *dir) {
608   if (coverage_enabled)
609     return;  // May happen if two sanitizer enable coverage in the same process.
610   coverage_enabled = enabled;
611   coverage_dir = dir;
612   coverage_data.Init();
613   if (enabled) coverage_data.Enable();
614   if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
615   AddDieCallback(MaybeDumpCoverage);
616 }
617
618 void ReInitializeCoverage(bool enabled, const char *dir) {
619   coverage_enabled = enabled;
620   coverage_dir = dir;
621   coverage_data.ReInit();
622 }
623
624 void CoverageUpdateMapping() {
625   if (coverage_enabled)
626     CovUpdateMapping(coverage_dir);
627 }
628
629 } // namespace __sanitizer
630
631 extern "C" {
632 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
633   coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
634                     guard);
635 }
636 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
637   atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
638   if (static_cast<s32>(
639           __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
640   coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
641                     guard);
642 }
643 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
644   coverage_enabled = true;
645   coverage_dir = common_flags()->coverage_dir;
646   coverage_data.Init();
647 }
648 SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
649   coverage_data.DumpAll();
650   __sanitizer_dump_trace_pc_guard_coverage();
651 }
652 SANITIZER_INTERFACE_ATTRIBUTE void
653 __sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
654                             const char *comp_unit_name) {
655   coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
656   if (!common_flags()->coverage_direct) return;
657   if (SANITIZER_ANDROID && coverage_enabled) {
658     // dlopen/dlclose interceptors do not work on Android, so we rely on
659     // Extend() calls to update .sancov.map.
660     CovUpdateMapping(coverage_dir, GET_CALLER_PC());
661   }
662   coverage_data.Extend(npcs);
663 }
664 SANITIZER_INTERFACE_ATTRIBUTE
665 sptr __sanitizer_maybe_open_cov_file(const char *name) {
666   return (sptr)MaybeOpenCovFile(name);
667 }
668 SANITIZER_INTERFACE_ATTRIBUTE
669 uptr __sanitizer_get_total_unique_coverage() {
670   return atomic_load(&coverage_counter, memory_order_relaxed);
671 }
672
673 // Default empty implementations (weak). Users should redefine them.
674 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_cmp, void) {}
675 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_cmp1, void) {}
676 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_cmp2, void) {}
677 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_cmp4, void) {}
678 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_cmp8, void) {}
679 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_switch, void) {}
680 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_div4, void) {}
681 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_div8, void) {}
682 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_gep, void) {}
683 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_cov_trace_pc_indir, void) {}
684 } // extern "C"