blob: b335838ad3b63845f5fe0102b55a19920eda59c3 [file] [log] [blame]
Bob Wilsona08e9ac2013-11-15 07:18:15 +00001//===-- 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:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000014// For every interesting basic block the compiler injects the following code:
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000015// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000016// __sanitizer_cov(&Guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +000017// }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000018// At the module start up time __sanitizer_cov_module_init sets the guards
19// to consecutive negative numbers (-1, -2, -3, ...).
Kostya Serebryany714c67c2014-01-17 11:00:30 +000020// It's fine to call __sanitizer_cov more than once for a given block.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000021//
22// Run-time:
Kostya Serebryany714c67c2014-01-17 11:00:30 +000023// - __sanitizer_cov(): record that we've executed the PC (GET_CALLER_PC).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000024// and atomically set Guard to -Guard.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000025// - __sanitizer_cov_dump: dump the coverage data to disk.
26// For every module of the current process that has coverage data
Kostya Serebryany2d56aba2015-03-18 22:03:39 +000027// 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.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000033//
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"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000046#include "sanitizer_stacktrace.h"
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000047#include "sanitizer_symbolizer.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000048#include "sanitizer_flags.h"
49
Kostya Serebryany2d56aba2015-03-18 22:03:39 +000050static const u64 kMagic64 = 0xC0BFFFFFFFFFFF64ULL;
51static const u64 kMagic32 = 0xC0BFFFFFFFFFFF32ULL;
52
Kostya Serebryany183cb6e2014-11-14 23:15:55 +000053static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
54
55static atomic_uintptr_t coverage_counter;
Bob Wilsona08e9ac2013-11-15 07:18:15 +000056
Kostya Serebryany8b530e12014-04-30 10:40:48 +000057// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000058// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000059// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000060
61// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
62// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
63// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000064
Sergey Matveev6cb47a082014-05-19 12:53:03 +000065static bool cov_sandboxed = false;
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +000066static fd_t cov_fd = kInvalidFd;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000067static unsigned int cov_max_block_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000068static bool coverage_enabled = false;
69static const char *coverage_dir;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000070
Bob Wilsona08e9ac2013-11-15 07:18:15 +000071namespace __sanitizer {
72
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000073class CoverageData {
74 public:
75 void Init();
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +000076 void Enable();
77 void Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000078 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000079 void BeforeFork();
80 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000081 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000082 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000083 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
84 uptr cache_size);
85 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000086 void DumpTrace();
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000087 void DumpAsBitSet();
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +000088 void DumpCounters();
Kostya Serebryany769ddaa2015-03-05 22:19:25 +000089 void DumpOffsets();
90 void DumpAll();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000091
92 ALWAYS_INLINE
Kostya Serebryanyd421db02015-01-03 00:54:43 +000093 void TraceBasicBlock(s32 *id);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000094
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +000095 void InitializeGuardArray(s32 *guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +000096 void InitializeGuards(s32 *guards, uptr n, const char *module_name,
97 uptr caller_pc);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000098 void InitializeCounters(u8 *counters, uptr n);
Kostya Serebryany21a1a232015-01-28 22:39:44 +000099 void ReinitializeGuards();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000100 uptr GetNumberOf8bitCounters();
101 uptr Update8bitCounterBitsetAndClearCounters(u8 *bitset);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000102
103 uptr *data();
104 uptr size();
105
106 private:
Timur Iskhodzhanov3e8d3922015-03-25 20:19:51 +0000107 void DirectOpen();
108 void UpdateModuleNameVec(uptr caller_pc, uptr range_beg, uptr range_end);
109
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000110 // Maximal size pc array may ever grow.
111 // We MmapNoReserve this space to ensure that the array is contiguous.
Evgeniy Stepanove2a82412015-04-03 12:59:39 +0000112 static const uptr kPcArrayMaxSize =
113 FIRST_32_SECOND_64(1 << (SANITIZER_ANDROID ? 24 : 26), 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000114 // 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.
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000127 fd_t pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000128
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000129 // Vector of coverage guard arrays, protected by mu.
130 InternalMmapVectorNoCtor<s32*> guard_array_vec;
131
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000132 struct NamedPcRange {
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000133 const char *copied_module_name;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000134 uptr beg, end; // elements [beg,end) in pc_array.
135 };
136
137 // Vector of module and compilation unit pc ranges.
138 InternalMmapVectorNoCtor<NamedPcRange> comp_unit_name_vec;
139 InternalMmapVectorNoCtor<NamedPcRange> module_name_vec;
Kostya Serebryany88599462015-02-20 00:30:44 +0000140
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000141 struct CounterAndSize {
142 u8 *counters;
143 uptr n;
144 };
145
146 InternalMmapVectorNoCtor<CounterAndSize> counters_vec;
147 uptr num_8bit_counters;
148
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000149 // Caller-Callee (cc) array, size and current index.
150 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
151 uptr **cc_array;
152 atomic_uintptr_t cc_array_index;
153 atomic_uintptr_t cc_array_size;
154
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000155 // Tracing event array, size and current pointer.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000156 // We record all events (basic block entries) in a global buffer of u32
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000157 // values. Each such value is the index in pc_array.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000158 // So far the tracing is highly experimental:
159 // - not thread-safe;
160 // - does not support long traces;
161 // - not tuned for performance.
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000162 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
163 u32 *tr_event_array;
164 uptr tr_event_array_size;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000165 u32 *tr_event_pointer;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000166 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000167
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000168 StaticSpinMutex mu;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000169};
170
171static CoverageData coverage_data;
172
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000173void CovUpdateMapping(const char *path, uptr caller_pc = 0);
174
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000175void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000176 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000177 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000178 coverage_dir, internal_getpid());
Alexander Potapenko141e4202015-03-23 10:10:46 +0000179 pc_fd = OpenFile(path.data(), RdWr);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000180 if (pc_fd == kInvalidFd) {
Alexey Samsonovc4ed5482015-03-31 18:16:42 +0000181 Report("Coverage: failed to open %s for reading/writing\n", path.data());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000182 Die();
183 }
184
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000185 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000186 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000187}
188
189void CoverageData::Init() {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000190 pc_fd = kInvalidFd;
191}
192
193void CoverageData::Enable() {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000194 if (pc_array)
195 return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000196 pc_array = reinterpret_cast<uptr *>(
197 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000198 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000199 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000200 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000201 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000202 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
203 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000204
205 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
206 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
207 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
208 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000209
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000210 // Allocate tr_event_array with a guard page at the end.
211 tr_event_array = reinterpret_cast<u32 *>(MmapNoReserveOrDie(
212 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize + GetMmapGranularity(),
213 "CovInit::tr_event_array"));
214 Mprotect(reinterpret_cast<uptr>(&tr_event_array[kTrEventArrayMaxSize]),
215 GetMmapGranularity());
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000216 tr_event_array_size = kTrEventArrayMaxSize;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000217 tr_event_pointer = tr_event_array;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000218
219 num_8bit_counters = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000220}
221
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000222void CoverageData::InitializeGuardArray(s32 *guards) {
Viktor Kutuzov7891c8c2015-02-02 09:38:10 +0000223 Enable(); // Make sure coverage is enabled at this point.
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000224 s32 n = guards[0];
225 for (s32 j = 1; j <= n; j++) {
226 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
227 guards[j] = -static_cast<s32>(idx + 1);
228 }
229}
230
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000231void CoverageData::Disable() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000232 if (pc_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000233 UnmapOrDie(pc_array, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000234 pc_array = nullptr;
235 }
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000236 if (cc_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000237 UnmapOrDie(cc_array, sizeof(uptr *) * kCcArrayMaxSize);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000238 cc_array = nullptr;
239 }
240 if (tr_event_array) {
Timur Iskhodzhanov37453032015-04-08 17:08:24 +0000241 UnmapOrDie(tr_event_array,
242 sizeof(tr_event_array[0]) * kTrEventArrayMaxSize +
243 GetMmapGranularity());
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000244 tr_event_array = nullptr;
245 tr_event_pointer = nullptr;
246 }
247 if (pc_fd != kInvalidFd) {
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000248 CloseFile(pc_fd);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000249 pc_fd = kInvalidFd;
250 }
251}
252
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000253void CoverageData::ReinitializeGuards() {
254 // Assuming single thread.
255 atomic_store(&pc_array_index, 0, memory_order_relaxed);
256 for (uptr i = 0; i < guard_array_vec.size(); i++)
257 InitializeGuardArray(guard_array_vec[i]);
258}
259
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000260void CoverageData::ReInit() {
261 Disable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000262 if (coverage_enabled) {
263 if (common_flags()->coverage_direct) {
264 // In memory-mapped mode we must extend the new file to the known array
265 // size.
266 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000267 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000268 if (size) Extend(size);
269 if (coverage_enabled) CovUpdateMapping(coverage_dir);
270 } else {
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000271 Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000272 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000273 }
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000274 // Re-initialize the guards.
275 // We are single-threaded now, no need to grab any lock.
276 CHECK_EQ(atomic_load(&pc_array_index, memory_order_relaxed), 0);
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000277 ReinitializeGuards();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000278}
279
280void CoverageData::BeforeFork() {
281 mu.Lock();
282}
283
284void CoverageData::AfterFork(int child_pid) {
285 // We are single-threaded so it's OK to release the lock early.
286 mu.Unlock();
287 if (child_pid == 0) ReInit();
288}
289
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000290// Extend coverage PC array to fit additional npcs elements.
291void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000292 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000293 SpinMutexLock l(&mu);
294
295 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
296 size += npcs * sizeof(uptr);
297
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000298 if (coverage_enabled && size > pc_array_mapped_size) {
299 if (pc_fd == kInvalidFd) DirectOpen();
300 CHECK_NE(pc_fd, kInvalidFd);
301
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000302 uptr new_mapped_size = pc_array_mapped_size;
303 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000304 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000305
306 // Extend the file and map the new space at the end of pc_array.
307 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
308 int err;
309 if (internal_iserror(res, &err)) {
310 Printf("failed to extend raw coverage file: %d\n", err);
311 Die();
312 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000313
314 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
315 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000316 new_mapped_size - pc_array_mapped_size,
317 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000318 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000319 pc_array_mapped_size = new_mapped_size;
320 }
321
322 atomic_store(&pc_array_size, size, memory_order_release);
323}
324
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000325void CoverageData::InitializeCounters(u8 *counters, uptr n) {
326 if (!counters) return;
327 CHECK_EQ(reinterpret_cast<uptr>(counters) % 16, 0);
328 n = RoundUpTo(n, 16); // The compiler must ensure that counters is 16-aligned.
329 SpinMutexLock l(&mu);
330 counters_vec.push_back({counters, n});
331 num_8bit_counters += n;
332}
333
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000334void CoverageData::UpdateModuleNameVec(uptr caller_pc, uptr range_beg,
335 uptr range_end) {
336 auto sym = Symbolizer::GetOrInit();
337 if (!sym)
338 return;
339 const char *module_name = sym->GetModuleNameForPc(caller_pc);
340 if (!module_name) return;
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000341 if (module_name_vec.empty() ||
Timur Iskhodzhanov6c66ad02015-03-31 12:50:05 +0000342 module_name_vec.back().copied_module_name != module_name)
343 module_name_vec.push_back({module_name, range_beg, range_end});
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000344 else
345 module_name_vec.back().end = range_end;
346}
347
Kostya Serebryany88599462015-02-20 00:30:44 +0000348void CoverageData::InitializeGuards(s32 *guards, uptr n,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000349 const char *comp_unit_name,
350 uptr caller_pc) {
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000351 // The array 'guards' has n+1 elements, we use the element zero
352 // to store 'n'.
353 CHECK_LT(n, 1 << 30);
354 guards[0] = static_cast<s32>(n);
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000355 InitializeGuardArray(guards);
356 SpinMutexLock l(&mu);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000357 uptr range_end = atomic_load(&pc_array_index, memory_order_relaxed);
358 uptr range_beg = range_end - n;
359 comp_unit_name_vec.push_back({comp_unit_name, range_beg, range_end});
Kostya Serebryany77c5c1a2014-12-30 23:16:12 +0000360 guard_array_vec.push_back(guards);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000361 UpdateModuleNameVec(caller_pc, range_beg, range_end);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000362}
363
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000364static const uptr kBundleCounterBits = 16;
365
366// When coverage_order_pcs==true and SANITIZER_WORDSIZE==64
367// we insert the global counter into the first 16 bits of the PC.
368uptr BundlePcAndCounter(uptr pc, uptr counter) {
369 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
370 return pc;
371 static const uptr kMaxCounter = (1 << kBundleCounterBits) - 1;
372 if (counter > kMaxCounter)
373 counter = kMaxCounter;
374 CHECK_EQ(0, pc >> (SANITIZER_WORDSIZE - kBundleCounterBits));
375 return pc | (counter << (SANITIZER_WORDSIZE - kBundleCounterBits));
376}
377
378uptr UnbundlePc(uptr bundle) {
379 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
380 return bundle;
381 return (bundle << kBundleCounterBits) >> kBundleCounterBits;
382}
383
384uptr UnbundleCounter(uptr bundle) {
385 if (SANITIZER_WORDSIZE != 64 || !common_flags()->coverage_order_pcs)
386 return 0;
387 return bundle >> (SANITIZER_WORDSIZE - kBundleCounterBits);
388}
389
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000390// If guard is negative, atomically set it to -guard and store the PC in
391// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000392void CoverageData::Add(uptr pc, u32 *guard) {
393 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
394 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
395 if (guard_value >= 0) return;
396
397 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000398 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000399
400 uptr idx = -guard_value - 1;
401 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
402 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000403 CHECK_LT(idx * sizeof(uptr),
404 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000405 uptr counter = atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
406 pc_array[idx] = BundlePcAndCounter(pc, counter);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000407}
408
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000409// Registers a pair caller=>callee.
410// When a given caller is seen for the first time, the callee_cache is added
411// to the global array cc_array, callee_cache[0] is set to caller and
412// callee_cache[1] is set to cache_size.
413// Then we are trying to add callee to callee_cache [2,cache_size) if it is
414// not there yet.
415// If the cache is full we drop the callee (may want to fix this later).
416void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
417 uptr cache_size) {
418 if (!cc_array) return;
419 atomic_uintptr_t *atomic_callee_cache =
420 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
421 uptr zero = 0;
422 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
423 memory_order_seq_cst)) {
424 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
425 CHECK_LT(idx * sizeof(uptr),
426 atomic_load(&cc_array_size, memory_order_acquire));
427 callee_cache[1] = cache_size;
428 cc_array[idx] = callee_cache;
429 }
430 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
431 for (uptr i = 2; i < cache_size; i++) {
432 uptr was = 0;
433 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000434 memory_order_seq_cst)) {
435 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000436 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000437 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000438 if (was == callee) // Already have this callee.
439 return;
440 }
441}
442
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000443uptr CoverageData::GetNumberOf8bitCounters() {
444 return num_8bit_counters;
445}
446
447// Map every 8bit counter to a 8-bit bitset and clear the counter.
448uptr CoverageData::Update8bitCounterBitsetAndClearCounters(u8 *bitset) {
449 uptr num_new_bits = 0;
450 uptr cur = 0;
451 // For better speed we map 8 counters to 8 bytes of bitset at once.
452 static const uptr kBatchSize = 8;
453 CHECK_EQ(reinterpret_cast<uptr>(bitset) % kBatchSize, 0);
454 for (uptr i = 0, len = counters_vec.size(); i < len; i++) {
455 u8 *c = counters_vec[i].counters;
456 uptr n = counters_vec[i].n;
457 CHECK_EQ(n % 16, 0);
458 CHECK_EQ(cur % kBatchSize, 0);
459 CHECK_EQ(reinterpret_cast<uptr>(c) % kBatchSize, 0);
460 if (!bitset) {
461 internal_bzero_aligned16(c, n);
462 cur += n;
463 continue;
464 }
465 for (uptr j = 0; j < n; j += kBatchSize, cur += kBatchSize) {
466 CHECK_LT(cur, num_8bit_counters);
467 u64 *pc64 = reinterpret_cast<u64*>(c + j);
468 u64 *pb64 = reinterpret_cast<u64*>(bitset + cur);
469 u64 c64 = *pc64;
470 u64 old_bits_64 = *pb64;
471 u64 new_bits_64 = old_bits_64;
472 if (c64) {
473 *pc64 = 0;
474 for (uptr k = 0; k < kBatchSize; k++) {
475 u64 x = (c64 >> (8 * k)) & 0xff;
476 if (x) {
477 u64 bit = 0;
478 /**/ if (x >= 128) bit = 128;
479 else if (x >= 32) bit = 64;
480 else if (x >= 16) bit = 32;
481 else if (x >= 8) bit = 16;
482 else if (x >= 4) bit = 8;
483 else if (x >= 3) bit = 4;
484 else if (x >= 2) bit = 2;
485 else if (x >= 1) bit = 1;
486 u64 mask = bit << (8 * k);
487 if (!(new_bits_64 & mask)) {
488 num_new_bits++;
489 new_bits_64 |= mask;
490 }
491 }
492 }
493 *pb64 = new_bits_64;
494 }
495 }
496 }
497 CHECK_EQ(cur, num_8bit_counters);
498 return num_new_bits;
499}
500
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000501uptr *CoverageData::data() {
502 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000503}
504
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000505uptr CoverageData::size() {
506 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000507}
508
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000509// Block layout for packed file format: header, followed by module name (no
510// trailing zero), followed by data blob.
511struct CovHeader {
512 int pid;
513 unsigned int module_name_length;
514 unsigned int data_length;
515};
516
517static void CovWritePacked(int pid, const char *module, const void *blob,
518 unsigned int blob_size) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000519 if (cov_fd == kInvalidFd) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000520 unsigned module_name_length = internal_strlen(module);
521 CovHeader header = {pid, module_name_length, blob_size};
522
523 if (cov_max_block_size == 0) {
524 // Writing to a file. Just go ahead.
525 internal_write(cov_fd, &header, sizeof(header));
526 internal_write(cov_fd, module, module_name_length);
527 internal_write(cov_fd, blob, blob_size);
528 } else {
529 // Writing to a socket. We want to split the data into appropriately sized
530 // blocks.
531 InternalScopedBuffer<char> block(cov_max_block_size);
532 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
533 uptr header_size_with_module = sizeof(header) + module_name_length;
534 CHECK_LT(header_size_with_module, cov_max_block_size);
535 unsigned int max_payload_size =
536 cov_max_block_size - header_size_with_module;
537 char *block_pos = block.data();
538 internal_memcpy(block_pos, &header, sizeof(header));
539 block_pos += sizeof(header);
540 internal_memcpy(block_pos, module, module_name_length);
541 block_pos += module_name_length;
542 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000543 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000544 while (blob_size > 0) {
545 unsigned int payload_size = Min(blob_size, max_payload_size);
546 blob_size -= payload_size;
547 internal_memcpy(block_data_begin, blob_pos, payload_size);
548 blob_pos += payload_size;
549 ((CovHeader *)block.data())->data_length = payload_size;
550 internal_write(cov_fd, block.data(),
551 header_size_with_module + payload_size);
552 }
553 }
554}
555
Sergey Matveev83f91e72014-05-21 13:43:52 +0000556// If packed = false: <name>.<pid>.<sancov> (name = module name).
557// If packed = true and name == 0: <pid>.<sancov>.<packed>.
558// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
559// user-supplied).
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000560static fd_t CovOpenFile(InternalScopedString *path, bool packed,
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000561 const char *name, const char *extension = "sancov") {
562 path->clear();
Sergey Matveev83f91e72014-05-21 13:43:52 +0000563 if (!packed) {
564 CHECK(name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000565 path->append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000566 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000567 } else {
568 if (!name)
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000569 path->append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000570 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000571 else
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000572 path->append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000573 }
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000574 fd_t fd = OpenFile(path->data(), WrOnly);
575 if (fd == kInvalidFd)
Alexey Samsonovc4ed5482015-03-31 18:16:42 +0000576 Report("SanitizerCoverage: failed to open %s for writing\n", path->data());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000577 return fd;
578}
579
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000580// Dump trace PCs and trace events into two separate files.
581void CoverageData::DumpTrace() {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000582 uptr max_idx = tr_event_pointer - tr_event_array;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000583 if (!max_idx) return;
584 auto sym = Symbolizer::GetOrInit();
585 if (!sym)
586 return;
587 InternalScopedString out(32 << 20);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000588 for (uptr i = 0, n = size(); i < n; i++) {
589 const char *module_name = "<unknown>";
590 uptr module_address = 0;
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000591 sym->GetModuleNameAndOffsetForPC(UnbundlePc(pc_array[i]), &module_name,
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000592 &module_address);
593 out.append("%s 0x%zx\n", module_name, module_address);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000594 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000595 InternalScopedString path(kMaxPathLength);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000596 fd_t fd = CovOpenFile(&path, false, "trace-points");
597 if (fd == kInvalidFd) return;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000598 internal_write(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000599 CloseFile(fd);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000600
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000601 fd = CovOpenFile(&path, false, "trace-compunits");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000602 if (fd == kInvalidFd) return;
Kostya Serebryany88599462015-02-20 00:30:44 +0000603 out.clear();
604 for (uptr i = 0; i < comp_unit_name_vec.size(); i++)
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000605 out.append("%s\n", comp_unit_name_vec[i].copied_module_name);
Kostya Serebryany88599462015-02-20 00:30:44 +0000606 internal_write(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000607 CloseFile(fd);
Kostya Serebryany88599462015-02-20 00:30:44 +0000608
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000609 fd = CovOpenFile(&path, false, "trace-events");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000610 if (fd == kInvalidFd) return;
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000611 uptr bytes_to_write = max_idx * sizeof(tr_event_array[0]);
612 u8 *event_bytes = reinterpret_cast<u8*>(tr_event_array);
613 // The trace file could be huge, and may not be written with a single syscall.
614 while (bytes_to_write) {
615 uptr actually_written = internal_write(fd, event_bytes, bytes_to_write);
616 if (actually_written <= bytes_to_write) {
617 bytes_to_write -= actually_written;
618 event_bytes += actually_written;
619 } else {
620 break;
621 }
622 }
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000623 CloseFile(fd);
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000624 VReport(1, " CovDump: Trace: %zd PCs written\n", size());
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000625 VReport(1, " CovDump: Trace: %zd Events written\n", max_idx);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000626}
627
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000628// This function dumps the caller=>callee pairs into a file as a sequence of
629// lines like "module_name offset".
630void CoverageData::DumpCallerCalleePairs() {
631 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
632 if (!max_idx) return;
633 auto sym = Symbolizer::GetOrInit();
634 if (!sym)
635 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000636 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000637 uptr total = 0;
638 for (uptr i = 0; i < max_idx; i++) {
639 uptr *cc_cache = cc_array[i];
640 CHECK(cc_cache);
641 uptr caller = cc_cache[0];
642 uptr n_callees = cc_cache[1];
643 const char *caller_module_name = "<unknown>";
644 uptr caller_module_address = 0;
645 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
646 &caller_module_address);
647 for (uptr j = 2; j < n_callees; j++) {
648 uptr callee = cc_cache[j];
649 if (!callee) break;
650 total++;
651 const char *callee_module_name = "<unknown>";
652 uptr callee_module_address = 0;
653 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
654 &callee_module_address);
655 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
656 caller_module_address, callee_module_name,
657 callee_module_address);
658 }
659 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000660 InternalScopedString path(kMaxPathLength);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000661 fd_t fd = CovOpenFile(&path, false, "caller-callee");
662 if (fd == kInvalidFd) return;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000663 internal_write(fd, out.data(), out.length());
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000664 CloseFile(fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000665 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
666}
667
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000668// Record the current PC into the event buffer.
669// Every event is a u32 value (index in tr_pc_array_index) so we compute
670// it once and then cache in the provided 'cache' storage.
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000671//
672// This function will eventually be inlined by the compiler.
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000673void CoverageData::TraceBasicBlock(s32 *id) {
Kostya Serebryany0f53d9a2015-01-03 02:07:58 +0000674 // Will trap here if
675 // 1. coverage is not enabled at run-time.
676 // 2. The array tr_event_array is full.
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000677 *tr_event_pointer = static_cast<u32>(*id - 1);
678 tr_event_pointer++;
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000679}
680
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000681void CoverageData::DumpCounters() {
682 if (!common_flags()->coverage_counters) return;
683 uptr n = coverage_data.GetNumberOf8bitCounters();
684 if (!n) return;
685 InternalScopedBuffer<u8> bitset(n);
686 coverage_data.Update8bitCounterBitsetAndClearCounters(bitset.data());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000687 InternalScopedString path(kMaxPathLength);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000688
689 for (uptr m = 0; m < module_name_vec.size(); m++) {
690 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000691 CHECK(r.copied_module_name);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000692 CHECK_LE(r.beg, r.end);
693 CHECK_LE(r.end, size());
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000694 const char *base_name = StripModuleName(r.copied_module_name);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000695 fd_t fd =
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000696 CovOpenFile(&path, /* packed */ false, base_name, "counters-sancov");
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000697 if (fd == kInvalidFd) return;
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000698 internal_write(fd, bitset.data() + r.beg, r.end - r.beg);
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000699 CloseFile(fd);
Kostya Serebryanyc1d6ab92015-03-05 02:48:51 +0000700 VReport(1, " CovDump: %zd counters written for '%s'\n", r.end - r.beg,
701 base_name);
702 }
703}
704
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000705void CoverageData::DumpAsBitSet() {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000706 if (!common_flags()->coverage_bitset) return;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000707 if (!size()) return;
708 InternalScopedBuffer<char> out(size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000709 InternalScopedString path(kMaxPathLength);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000710 for (uptr m = 0; m < module_name_vec.size(); m++) {
711 uptr n_set_bits = 0;
712 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000713 CHECK(r.copied_module_name);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000714 CHECK_LE(r.beg, r.end);
715 CHECK_LE(r.end, size());
716 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000717 uptr pc = UnbundlePc(pc_array[i]);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000718 out[i] = pc ? '1' : '0';
719 if (pc)
720 n_set_bits++;
721 }
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000722 const char *base_name = StripModuleName(r.copied_module_name);
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000723 fd_t fd = CovOpenFile(&path, /* packed */false, base_name, "bitset-sancov");
724 if (fd == kInvalidFd) return;
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000725 internal_write(fd, out.data() + r.beg, r.end - r.beg);
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000726 CloseFile(fd);
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000727 VReport(1,
728 " CovDump: bitset of %zd bits written for '%s', %zd bits are set\n",
729 r.end - r.beg, base_name, n_set_bits);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000730 }
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000731}
732
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000733void CoverageData::DumpOffsets() {
734 auto sym = Symbolizer::GetOrInit();
Kostya Serebryanya7ee2732014-12-30 19:55:04 +0000735 if (!common_flags()->coverage_pcs) return;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000736 CHECK_NE(sym, nullptr);
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000737 InternalMmapVector<uptr> offsets(0);
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000738 InternalScopedString path(kMaxPathLength);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000739 for (uptr m = 0; m < module_name_vec.size(); m++) {
740 offsets.clear();
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000741 uptr num_words_for_magic = SANITIZER_WORDSIZE == 64 ? 1 : 2;
742 for (uptr i = 0; i < num_words_for_magic; i++)
743 offsets.push_back(0);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000744 auto r = module_name_vec[m];
Kostya Serebryanycd019f32015-03-23 23:19:13 +0000745 CHECK(r.copied_module_name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000746 CHECK_LE(r.beg, r.end);
747 CHECK_LE(r.end, size());
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000748 for (uptr i = r.beg; i < r.end; i++) {
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000749 uptr pc = UnbundlePc(pc_array[i]);
750 uptr counter = UnbundleCounter(pc_array[i]);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000751 if (!pc) continue; // Not visited.
752 uptr offset = 0;
Timur Iskhodzhanov6c66ad02015-03-31 12:50:05 +0000753 sym->GetModuleNameAndOffsetForPC(pc, nullptr, &offset);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000754 offsets.push_back(BundlePcAndCounter(offset, counter));
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000755 }
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000756
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000757 CHECK_GE(offsets.size(), num_words_for_magic);
Kostya Serebryanycba49d42015-03-18 00:23:44 +0000758 SortArray(offsets.data(), offsets.size());
759 for (uptr i = 0; i < offsets.size(); i++)
760 offsets[i] = UnbundlePc(offsets[i]);
761
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000762 uptr num_offsets = offsets.size() - num_words_for_magic;
763 u64 *magic_p = reinterpret_cast<u64*>(offsets.data());
764 CHECK_EQ(*magic_p, 0ULL);
765 // FIXME: we may want to write 32-bit offsets even in 64-mode
766 // if all the offsets are small enough.
767 *magic_p = SANITIZER_WORDSIZE == 64 ? kMagic64 : kMagic32;
768
Timur Iskhodzhanov3e8d3922015-03-25 20:19:51 +0000769 const char *module_name = StripModuleName(r.copied_module_name);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000770 if (cov_sandboxed) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000771 if (cov_fd != kInvalidFd) {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000772 CovWritePacked(internal_getpid(), module_name, offsets.data(),
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000773 offsets.size() * sizeof(offsets[0]));
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000774 VReport(1, " CovDump: %zd PCs written to packed file\n", num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000775 }
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000776 } else {
777 // One file per module per process.
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000778 fd_t fd = CovOpenFile(&path, false /* packed */, module_name);
779 if (fd == kInvalidFd) continue;
Kostya Serebryany9f1243e2015-03-17 22:09:19 +0000780 internal_write(fd, offsets.data(), offsets.size() * sizeof(offsets[0]));
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000781 CloseFile(fd);
Kostya Serebryany2d56aba2015-03-18 22:03:39 +0000782 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(), num_offsets);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000783 }
784 }
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000785 if (cov_fd != kInvalidFd)
Timur Iskhodzhanov864308a2015-04-09 12:37:05 +0000786 CloseFile(cov_fd);
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000787}
788
789void CoverageData::DumpAll() {
790 if (!coverage_enabled || common_flags()->coverage_direct) return;
791 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
792 return;
793 DumpAsBitSet();
794 DumpCounters();
795 DumpTrace();
796 DumpOffsets();
797 DumpCallerCalleePairs();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000798}
799
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000800void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
801 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000802 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000803 cov_sandboxed = args->coverage_sandboxed;
804 if (!cov_sandboxed) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000805 cov_max_block_size = args->coverage_max_block_size;
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000806 if (args->coverage_fd >= 0) {
807 cov_fd = args->coverage_fd;
808 } else {
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000809 InternalScopedString path(kMaxPathLength);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000810 // Pre-open the file now. The sandbox won't allow us to do it later.
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000811 cov_fd = CovOpenFile(&path, true /* packed */, 0);
812 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000813}
814
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000815fd_t MaybeOpenCovFile(const char *name) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000816 CHECK(name);
Timur Iskhodzhanov1b2ff682015-04-09 12:20:02 +0000817 if (!coverage_enabled) return kInvalidFd;
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000818 InternalScopedString path(kMaxPathLength);
819 return CovOpenFile(&path, true /* packed */, name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000820}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000821
822void CovBeforeFork() {
823 coverage_data.BeforeFork();
824}
825
826void CovAfterFork(int child_pid) {
827 coverage_data.AfterFork(child_pid);
828}
829
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000830void InitializeCoverage(bool enabled, const char *dir) {
Kostya Serebryanye02839b2015-01-06 01:11:23 +0000831 if (coverage_enabled)
832 return; // May happen if two sanitizer enable coverage in the same process.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000833 coverage_enabled = enabled;
834 coverage_dir = dir;
Evgeniy Stepanov3f2e7612015-01-12 17:13:20 +0000835 coverage_data.Init();
836 if (enabled) coverage_data.Enable();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000837 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000838}
839
840void ReInitializeCoverage(bool enabled, const char *dir) {
841 coverage_enabled = enabled;
842 coverage_dir = dir;
843 coverage_data.ReInit();
844}
845
846void CoverageUpdateMapping() {
847 if (coverage_enabled)
848 CovUpdateMapping(coverage_dir);
849}
850
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000851} // namespace __sanitizer
852
853extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000854SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000855 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
856 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000857}
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000858SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_with_check(u32 *guard) {
859 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000860 if (static_cast<s32>(
861 __sanitizer::atomic_load(atomic_guard, memory_order_relaxed)) < 0)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000862 __sanitizer_cov(guard);
863}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000864SANITIZER_INTERFACE_ATTRIBUTE void
865__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
866 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
867 callee, callee_cache16, 16);
868}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000869SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000870 coverage_enabled = true;
871 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000872 coverage_data.Init();
873}
Kostya Serebryany769ddaa2015-03-05 22:19:25 +0000874SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() {
875 coverage_data.DumpAll();
876}
Kostya Serebryany88599462015-02-20 00:30:44 +0000877SANITIZER_INTERFACE_ATTRIBUTE void
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000878__sanitizer_cov_module_init(s32 *guards, uptr npcs, u8 *counters,
Kostya Serebryany07aee9c2015-03-04 23:41:55 +0000879 const char *comp_unit_name) {
880 coverage_data.InitializeGuards(guards, npcs, comp_unit_name, GET_CALLER_PC());
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000881 coverage_data.InitializeCounters(counters, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000882 if (!common_flags()->coverage_direct) return;
883 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000884 // dlopen/dlclose interceptors do not work on Android, so we rely on
885 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000886 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000887 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000888 coverage_data.Extend(npcs);
889}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000890SANITIZER_INTERFACE_ATTRIBUTE
891sptr __sanitizer_maybe_open_cov_file(const char *name) {
Timur Iskhodzhanovdaa9e2d2015-04-08 16:03:22 +0000892 return (sptr)MaybeOpenCovFile(name);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000893}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000894SANITIZER_INTERFACE_ATTRIBUTE
895uptr __sanitizer_get_total_unique_coverage() {
896 return atomic_load(&coverage_counter, memory_order_relaxed);
897}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000898
899SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000900void __sanitizer_cov_trace_func_enter(s32 *id) {
901 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000902}
903SANITIZER_INTERFACE_ATTRIBUTE
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000904void __sanitizer_cov_trace_basic_block(s32 *id) {
905 coverage_data.TraceBasicBlock(id);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000906}
Kostya Serebryany21a1a232015-01-28 22:39:44 +0000907SANITIZER_INTERFACE_ATTRIBUTE
908void __sanitizer_reset_coverage() {
909 coverage_data.ReinitializeGuards();
910 internal_bzero_aligned16(
911 coverage_data.data(),
912 RoundUpTo(coverage_data.size() * sizeof(coverage_data.data()[0]), 16));
913}
914SANITIZER_INTERFACE_ATTRIBUTE
915uptr __sanitizer_get_coverage_guards(uptr **data) {
916 *data = coverage_data.data();
917 return coverage_data.size();
918}
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000919
920SANITIZER_INTERFACE_ATTRIBUTE
921uptr __sanitizer_get_number_of_counters() {
922 return coverage_data.GetNumberOf8bitCounters();
923}
924
925SANITIZER_INTERFACE_ATTRIBUTE
926uptr __sanitizer_update_counter_bitset_and_clear_counters(u8 *bitset) {
927 return coverage_data.Update8bitCounterBitsetAndClearCounters(bitset);
928}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000929} // extern "C"