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