blob: e28a6aee3755ed62f9518c81d122dd38ca3b4087 [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
27// this will create a file module_name.PID.sancov. The file format is simple:
28// it's just a sorted sequence of 4-byte offsets in the module.
29//
30// Eventually, this coverage implementation should be obsoleted by a more
31// powerful general purpose Clang/LLVM coverage instrumentation.
32// Consider this implementation as prototype.
33//
34// FIXME: support (or at least test with) dlclose.
35//===----------------------------------------------------------------------===//
36
37#include "sanitizer_allocator_internal.h"
38#include "sanitizer_common.h"
39#include "sanitizer_libc.h"
40#include "sanitizer_mutex.h"
41#include "sanitizer_procmaps.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000042#include "sanitizer_stacktrace.h"
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000043#include "sanitizer_symbolizer.h"
Bob Wilsona08e9ac2013-11-15 07:18:15 +000044#include "sanitizer_flags.h"
45
Kostya Serebryany183cb6e2014-11-14 23:15:55 +000046static atomic_uint32_t dump_once_guard; // Ensure that CovDump runs only once.
47
48static atomic_uintptr_t coverage_counter;
Bob Wilsona08e9ac2013-11-15 07:18:15 +000049
Kostya Serebryany8b530e12014-04-30 10:40:48 +000050// pc_array is the array containing the covered PCs.
Sergey Matveev6cb47a082014-05-19 12:53:03 +000051// To make the pc_array thread- and async-signal-safe it has to be large enough.
Kostya Serebryany8b530e12014-04-30 10:40:48 +000052// 128M counters "ought to be enough for anybody" (4M on 32-bit).
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000053
54// With coverage_direct=1 in ASAN_OPTIONS, pc_array memory is mapped to a file.
55// In this mode, __sanitizer_cov_dump does nothing, and CovUpdateMapping()
56// dump current memory layout to another file.
Bob Wilsona08e9ac2013-11-15 07:18:15 +000057
Sergey Matveev6cb47a082014-05-19 12:53:03 +000058static bool cov_sandboxed = false;
59static int cov_fd = kInvalidFd;
60static unsigned int cov_max_block_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000061static bool coverage_enabled = false;
62static const char *coverage_dir;
Sergey Matveev6cb47a082014-05-19 12:53:03 +000063
Bob Wilsona08e9ac2013-11-15 07:18:15 +000064namespace __sanitizer {
65
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000066class CoverageData {
67 public:
68 void Init();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +000069 void ReInit();
Evgeniy Stepanovfe181022014-06-04 12:13:54 +000070 void BeforeFork();
71 void AfterFork(int child_pid);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000072 void Extend(uptr npcs);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000073 void Add(uptr pc, u32 *guard);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +000074 void IndirCall(uptr caller, uptr callee, uptr callee_cache[],
75 uptr cache_size);
76 void DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +000077 void DumpTrace();
78
79 ALWAYS_INLINE
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000080 void TraceBasicBlock(uptr *cache);
81
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +000082 void InitializeGuards(s32 *guards, uptr n);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000083
84 uptr *data();
85 uptr size();
86
87 private:
88 // Maximal size pc array may ever grow.
89 // We MmapNoReserve this space to ensure that the array is contiguous.
Evgeniy Stepanov10308462014-12-26 13:54:11 +000090 static const uptr kPcArrayMaxSize = FIRST_32_SECOND_64(1 << 24, 1 << 27);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +000091 // The amount file mapping for the pc array is grown by.
92 static const uptr kPcArrayMmapSize = 64 * 1024;
93
94 // pc_array is allocated with MmapNoReserveOrDie and so it uses only as
95 // much RAM as it really needs.
96 uptr *pc_array;
97 // Index of the first available pc_array slot.
98 atomic_uintptr_t pc_array_index;
99 // Array size.
100 atomic_uintptr_t pc_array_size;
101 // Current file mapped size of the pc array.
102 uptr pc_array_mapped_size;
103 // Descriptor of the file mapped pc array.
104 int pc_fd;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000105
106 // Caller-Callee (cc) array, size and current index.
107 static const uptr kCcArrayMaxSize = FIRST_32_SECOND_64(1 << 18, 1 << 24);
108 uptr **cc_array;
109 atomic_uintptr_t cc_array_index;
110 atomic_uintptr_t cc_array_size;
111
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000112 // Tracing (tr) pc and event arrays, their size and current index.
113 // We record all events (basic block entries) in a global buffer of u32
114 // values. Each such value is an index in the table of TracedPc objects.
115 // So far the tracing is highly experimental:
116 // - not thread-safe;
117 // - does not support long traces;
118 // - not tuned for performance.
119 struct TracedPc {
120 uptr pc;
121 const char *module_name;
122 uptr module_offset;
123 };
124 static const uptr kTrEventArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 30);
125 u32 *tr_event_array;
126 uptr tr_event_array_size;
127 uptr tr_event_array_index;
128 static const uptr kTrPcArrayMaxSize = FIRST_32_SECOND_64(1 << 22, 1 << 27);
129 TracedPc *tr_pc_array;
130 uptr tr_pc_array_size;
131 uptr tr_pc_array_index;
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000132
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000133 StaticSpinMutex mu;
134
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000135 void DirectOpen();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000136};
137
138static CoverageData coverage_data;
139
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000140void CovUpdateMapping(const char *path, uptr caller_pc = 0);
141
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000142void CoverageData::DirectOpen() {
Alexey Samsonov4cc76cb2014-11-26 01:48:39 +0000143 InternalScopedString path(kMaxPathLength);
Evgeniy Stepanovfa5c0752014-05-29 14:33:16 +0000144 internal_snprintf((char *)path.data(), path.size(), "%s/%zd.sancov.raw",
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000145 coverage_dir, internal_getpid());
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000146 pc_fd = OpenFile(path.data(), true);
147 if (internal_iserror(pc_fd)) {
148 Report(" Coverage: failed to open %s for writing\n", path.data());
149 Die();
150 }
151
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000152 pc_array_mapped_size = 0;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000153 CovUpdateMapping(coverage_dir);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000154}
155
156void CoverageData::Init() {
157 pc_array = reinterpret_cast<uptr *>(
158 MmapNoReserveOrDie(sizeof(uptr) * kPcArrayMaxSize, "CovInit"));
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000159 pc_fd = kInvalidFd;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000160 atomic_store(&pc_array_index, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000161 if (common_flags()->coverage_direct) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000162 atomic_store(&pc_array_size, 0, memory_order_relaxed);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000163 } else {
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000164 atomic_store(&pc_array_size, kPcArrayMaxSize, memory_order_relaxed);
165 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000166
167 cc_array = reinterpret_cast<uptr **>(MmapNoReserveOrDie(
168 sizeof(uptr *) * kCcArrayMaxSize, "CovInit::cc_array"));
169 atomic_store(&cc_array_size, kCcArrayMaxSize, memory_order_relaxed);
170 atomic_store(&cc_array_index, 0, memory_order_relaxed);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000171
172 tr_event_array = reinterpret_cast<u32 *>(
173 MmapNoReserveOrDie(sizeof(tr_event_array[0]) * kTrEventArrayMaxSize,
174 "CovInit::tr_event_array"));
175 tr_event_array_size = kTrEventArrayMaxSize;
176 tr_event_array_index = 0;
177
178 tr_pc_array = reinterpret_cast<TracedPc *>(MmapNoReserveOrDie(
179 sizeof(tr_pc_array[0]) * kTrEventArrayMaxSize, "CovInit::tr_pc_array"));
180 tr_pc_array_size = kTrEventArrayMaxSize;
181 tr_pc_array_index = 0;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000182}
183
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000184void CoverageData::ReInit() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000185 if (pc_array) {
186 internal_munmap(pc_array, sizeof(uptr) * kPcArrayMaxSize);
187 pc_array = nullptr;
188 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000189 if (pc_fd != kInvalidFd) internal_close(pc_fd);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000190 if (coverage_enabled) {
191 if (common_flags()->coverage_direct) {
192 // In memory-mapped mode we must extend the new file to the known array
193 // size.
194 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
195 Init();
196 if (size) Extend(size);
197 if (coverage_enabled) CovUpdateMapping(coverage_dir);
198 } else {
199 Init();
200 }
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000201 }
202}
203
204void CoverageData::BeforeFork() {
205 mu.Lock();
206}
207
208void CoverageData::AfterFork(int child_pid) {
209 // We are single-threaded so it's OK to release the lock early.
210 mu.Unlock();
211 if (child_pid == 0) ReInit();
212}
213
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000214// Extend coverage PC array to fit additional npcs elements.
215void CoverageData::Extend(uptr npcs) {
Evgeniy Stepanovce984522014-06-03 15:27:15 +0000216 if (!common_flags()->coverage_direct) return;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000217 SpinMutexLock l(&mu);
218
219 uptr size = atomic_load(&pc_array_size, memory_order_relaxed);
220 size += npcs * sizeof(uptr);
221
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000222 if (coverage_enabled && size > pc_array_mapped_size) {
223 if (pc_fd == kInvalidFd) DirectOpen();
224 CHECK_NE(pc_fd, kInvalidFd);
225
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000226 uptr new_mapped_size = pc_array_mapped_size;
227 while (size > new_mapped_size) new_mapped_size += kPcArrayMmapSize;
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000228 CHECK_LE(new_mapped_size, sizeof(uptr) * kPcArrayMaxSize);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000229
230 // Extend the file and map the new space at the end of pc_array.
231 uptr res = internal_ftruncate(pc_fd, new_mapped_size);
232 int err;
233 if (internal_iserror(res, &err)) {
234 Printf("failed to extend raw coverage file: %d\n", err);
235 Die();
236 }
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000237
238 uptr next_map_base = ((uptr)pc_array) + pc_array_mapped_size;
239 void *p = MapWritableFileToMemory((void *)next_map_base,
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000240 new_mapped_size - pc_array_mapped_size,
241 pc_fd, pc_array_mapped_size);
Evgeniy Stepanovca9e0452014-12-24 13:57:11 +0000242 CHECK_EQ((uptr)p, next_map_base);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000243 pc_array_mapped_size = new_mapped_size;
244 }
245
246 atomic_store(&pc_array_size, size, memory_order_release);
247}
248
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000249void CoverageData::InitializeGuards(s32 *guards, uptr n) {
250 // The array 'guards' has n+1 elements, we use the element zero
251 // to store 'n'.
252 CHECK_LT(n, 1 << 30);
253 guards[0] = static_cast<s32>(n);
254 for (uptr i = 1; i <= n; i++) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000255 uptr idx = atomic_fetch_add(&pc_array_index, 1, memory_order_relaxed);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000256 guards[i] = -static_cast<s32>(idx + 1);
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000257 }
258}
259
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000260// If guard is negative, atomically set it to -guard and store the PC in
261// pc_array.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000262void CoverageData::Add(uptr pc, u32 *guard) {
263 atomic_uint32_t *atomic_guard = reinterpret_cast<atomic_uint32_t*>(guard);
264 s32 guard_value = atomic_load(atomic_guard, memory_order_relaxed);
265 if (guard_value >= 0) return;
266
267 atomic_store(atomic_guard, -guard_value, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000268 if (!pc_array) return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000269
270 uptr idx = -guard_value - 1;
271 if (idx >= atomic_load(&pc_array_index, memory_order_acquire))
272 return; // May happen after fork when pc_array_index becomes 0.
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000273 CHECK_LT(idx * sizeof(uptr),
274 atomic_load(&pc_array_size, memory_order_acquire));
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000275 pc_array[idx] = pc;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000276 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000277}
278
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000279// Registers a pair caller=>callee.
280// When a given caller is seen for the first time, the callee_cache is added
281// to the global array cc_array, callee_cache[0] is set to caller and
282// callee_cache[1] is set to cache_size.
283// Then we are trying to add callee to callee_cache [2,cache_size) if it is
284// not there yet.
285// If the cache is full we drop the callee (may want to fix this later).
286void CoverageData::IndirCall(uptr caller, uptr callee, uptr callee_cache[],
287 uptr cache_size) {
288 if (!cc_array) return;
289 atomic_uintptr_t *atomic_callee_cache =
290 reinterpret_cast<atomic_uintptr_t *>(callee_cache);
291 uptr zero = 0;
292 if (atomic_compare_exchange_strong(&atomic_callee_cache[0], &zero, caller,
293 memory_order_seq_cst)) {
294 uptr idx = atomic_fetch_add(&cc_array_index, 1, memory_order_relaxed);
295 CHECK_LT(idx * sizeof(uptr),
296 atomic_load(&cc_array_size, memory_order_acquire));
297 callee_cache[1] = cache_size;
298 cc_array[idx] = callee_cache;
299 }
300 CHECK_EQ(atomic_load(&atomic_callee_cache[0], memory_order_relaxed), caller);
301 for (uptr i = 2; i < cache_size; i++) {
302 uptr was = 0;
303 if (atomic_compare_exchange_strong(&atomic_callee_cache[i], &was, callee,
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000304 memory_order_seq_cst)) {
305 atomic_fetch_add(&coverage_counter, 1, memory_order_relaxed);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000306 return;
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000307 }
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000308 if (was == callee) // Already have this callee.
309 return;
310 }
311}
312
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000313uptr *CoverageData::data() {
314 return pc_array;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000315}
316
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000317uptr CoverageData::size() {
318 return atomic_load(&pc_array_index, memory_order_relaxed);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000319}
320
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000321// Block layout for packed file format: header, followed by module name (no
322// trailing zero), followed by data blob.
323struct CovHeader {
324 int pid;
325 unsigned int module_name_length;
326 unsigned int data_length;
327};
328
329static void CovWritePacked(int pid, const char *module, const void *blob,
330 unsigned int blob_size) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000331 if (cov_fd < 0) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000332 unsigned module_name_length = internal_strlen(module);
333 CovHeader header = {pid, module_name_length, blob_size};
334
335 if (cov_max_block_size == 0) {
336 // Writing to a file. Just go ahead.
337 internal_write(cov_fd, &header, sizeof(header));
338 internal_write(cov_fd, module, module_name_length);
339 internal_write(cov_fd, blob, blob_size);
340 } else {
341 // Writing to a socket. We want to split the data into appropriately sized
342 // blocks.
343 InternalScopedBuffer<char> block(cov_max_block_size);
344 CHECK_EQ((uptr)block.data(), (uptr)(CovHeader *)block.data());
345 uptr header_size_with_module = sizeof(header) + module_name_length;
346 CHECK_LT(header_size_with_module, cov_max_block_size);
347 unsigned int max_payload_size =
348 cov_max_block_size - header_size_with_module;
349 char *block_pos = block.data();
350 internal_memcpy(block_pos, &header, sizeof(header));
351 block_pos += sizeof(header);
352 internal_memcpy(block_pos, module, module_name_length);
353 block_pos += module_name_length;
354 char *block_data_begin = block_pos;
Alexey Samsonov4925fd42014-11-13 22:40:59 +0000355 const char *blob_pos = (const char *)blob;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000356 while (blob_size > 0) {
357 unsigned int payload_size = Min(blob_size, max_payload_size);
358 blob_size -= payload_size;
359 internal_memcpy(block_data_begin, blob_pos, payload_size);
360 blob_pos += payload_size;
361 ((CovHeader *)block.data())->data_length = payload_size;
362 internal_write(cov_fd, block.data(),
363 header_size_with_module + payload_size);
364 }
365 }
366}
367
Sergey Matveev83f91e72014-05-21 13:43:52 +0000368// If packed = false: <name>.<pid>.<sancov> (name = module name).
369// If packed = true and name == 0: <pid>.<sancov>.<packed>.
370// If packed = true and name != 0: <name>.<sancov>.<packed> (name is
371// user-supplied).
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000372static int CovOpenFile(bool packed, const char *name,
373 const char *extension = "sancov") {
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000374 InternalScopedString path(kMaxPathLength);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000375 if (!packed) {
376 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000377 path.append("%s/%s.%zd.%s", coverage_dir, name, internal_getpid(),
378 extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000379 } else {
380 if (!name)
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000381 path.append("%s/%zd.%s.packed", coverage_dir, internal_getpid(),
Evgeniy Stepanovf8c7e252014-12-26 10:19:56 +0000382 extension);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000383 else
384 path.append("%s/%s.%s.packed", coverage_dir, name, extension);
Sergey Matveev83f91e72014-05-21 13:43:52 +0000385 }
386 uptr fd = OpenFile(path.data(), true);
387 if (internal_iserror(fd)) {
388 Report(" SanitizerCoverage: failed to open %s for writing\n", path.data());
389 return -1;
390 }
391 return fd;
392}
393
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000394// Dump trace PCs and trace events into two separate files.
395void CoverageData::DumpTrace() {
396 uptr max_idx = tr_event_array_index;
397 if (!max_idx) return;
398 auto sym = Symbolizer::GetOrInit();
399 if (!sym)
400 return;
401 InternalScopedString out(32 << 20);
402 for (uptr i = 0; i < max_idx; i++) {
403 u32 pc_idx = tr_event_array[i];
404 TracedPc *t = &tr_pc_array[pc_idx];
405 if (!t->module_name) {
406 const char *module_name = "<unknown>";
407 uptr module_address = 0;
408 sym->GetModuleNameAndOffsetForPC(t->pc, &module_name, &module_address);
409 t->module_name = internal_strdup(module_name);
410 t->module_offset = module_address;
411 out.append("%s 0x%zx\n", t->module_name, t->module_offset);
412 }
413 }
414 int fd = CovOpenFile(false, "trace-points");
415 if (fd < 0) return;
416 internal_write(fd, out.data(), out.length());
417 internal_close(fd);
418
419 fd = CovOpenFile(false, "trace-events");
420 if (fd < 0) return;
421 internal_write(fd, tr_event_array, max_idx * sizeof(tr_event_array[0]));
422 internal_close(fd);
423 VReport(1, " CovDump: Trace: %zd PCs written\n", tr_pc_array_index);
424 VReport(1, " CovDump: Trace: %zd Events written\n", tr_event_array_index);
425}
426
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000427// This function dumps the caller=>callee pairs into a file as a sequence of
428// lines like "module_name offset".
429void CoverageData::DumpCallerCalleePairs() {
430 uptr max_idx = atomic_load(&cc_array_index, memory_order_relaxed);
431 if (!max_idx) return;
432 auto sym = Symbolizer::GetOrInit();
433 if (!sym)
434 return;
Kostya Serebryany40aa4a22014-10-31 19:49:46 +0000435 InternalScopedString out(32 << 20);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000436 uptr total = 0;
437 for (uptr i = 0; i < max_idx; i++) {
438 uptr *cc_cache = cc_array[i];
439 CHECK(cc_cache);
440 uptr caller = cc_cache[0];
441 uptr n_callees = cc_cache[1];
442 const char *caller_module_name = "<unknown>";
443 uptr caller_module_address = 0;
444 sym->GetModuleNameAndOffsetForPC(caller, &caller_module_name,
445 &caller_module_address);
446 for (uptr j = 2; j < n_callees; j++) {
447 uptr callee = cc_cache[j];
448 if (!callee) break;
449 total++;
450 const char *callee_module_name = "<unknown>";
451 uptr callee_module_address = 0;
452 sym->GetModuleNameAndOffsetForPC(callee, &callee_module_name,
453 &callee_module_address);
454 out.append("%s 0x%zx\n%s 0x%zx\n", caller_module_name,
455 caller_module_address, callee_module_name,
456 callee_module_address);
457 }
458 }
459 int fd = CovOpenFile(false, "caller-callee");
460 if (fd < 0) return;
461 internal_write(fd, out.data(), out.length());
462 internal_close(fd);
463 VReport(1, " CovDump: %zd caller-callee pairs written\n", total);
464}
465
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000466// Record the current PC into the event buffer.
467// Every event is a u32 value (index in tr_pc_array_index) so we compute
468// it once and then cache in the provided 'cache' storage.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000469void CoverageData::TraceBasicBlock(uptr *cache) {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000470 CHECK(coverage_enabled);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000471 uptr idx = *cache;
472 if (!idx) {
473 CHECK_LT(tr_pc_array_index, kTrPcArrayMaxSize);
474 idx = tr_pc_array_index++;
475 TracedPc *t = &tr_pc_array[idx];
476 t->pc = GET_CALLER_PC();
477 *cache = idx;
478 CHECK_LT(idx, 1U << 31);
479 }
480 CHECK_LT(tr_event_array_index, tr_event_array_size);
481 tr_event_array[tr_event_array_index] = static_cast<u32>(idx);
482 tr_event_array_index++;
483}
484
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000485static void CovDumpAsBitSet() {
486 if (!common_flags()->coverage_bitset) return;
487 if (!coverage_data.size()) return;
488 int fd = CovOpenFile(/* packed */false, "combined", "bitset-sancov");
489 if (fd < 0) return;
490 uptr n = coverage_data.size();
491 uptr n_set_bits = 0;
492 InternalScopedBuffer<char> out(n);
493 for (uptr i = 0; i < n; i++) {
494 uptr pc = coverage_data.data()[i];
495 out[i] = pc ? '1' : '0';
496 if (pc)
497 n_set_bits++;
498 }
499 internal_write(fd, out.data(), n);
500 internal_close(fd);
501 VReport(1, " CovDump: bitset of %zd bits written, %zd bits are set\n", n,
502 n_set_bits);
503}
504
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000505// Dump the coverage on disk.
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000506static void CovDump() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000507 if (!coverage_enabled || common_flags()->coverage_direct) return;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000508#if !SANITIZER_WINDOWS
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000509 if (atomic_fetch_add(&dump_once_guard, 1, memory_order_relaxed))
510 return;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000511 CovDumpAsBitSet();
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000512 uptr size = coverage_data.size();
Kostya Serebryany8b530e12014-04-30 10:40:48 +0000513 InternalMmapVector<u32> offsets(size);
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000514 uptr *vb = coverage_data.data();
515 uptr *ve = vb + size;
516 SortArray(vb, size);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000517 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000518 uptr mb, me, off, prot;
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000519 InternalScopedString module(kMaxPathLength);
520 InternalScopedString path(kMaxPathLength);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000521 for (int i = 0;
522 proc_maps.Next(&mb, &me, &off, module.data(), module.size(), &prot);
523 i++) {
524 if ((prot & MemoryMappingLayout::kProtectionExecute) == 0)
525 continue;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000526 while (vb < ve && *vb < mb) vb++;
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000527 if (vb >= ve) break;
Sergey Matveev76e02e92014-05-08 16:09:54 +0000528 if (*vb < me) {
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000529 offsets.clear();
530 const uptr *old_vb = vb;
531 CHECK_LE(off, *vb);
532 for (; vb < ve && *vb < me; vb++) {
533 uptr diff = *vb - (i ? mb : 0) + off;
534 CHECK_LE(diff, 0xffffffffU);
535 offsets.push_back(static_cast<u32>(diff));
536 }
Alexey Samsonov26ca05a2014-11-04 19:34:29 +0000537 const char *module_name = StripModuleName(module.data());
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000538 if (cov_sandboxed) {
Sergey Matveev83f91e72014-05-21 13:43:52 +0000539 if (cov_fd >= 0) {
540 CovWritePacked(internal_getpid(), module_name, offsets.data(),
541 offsets.size() * sizeof(u32));
542 VReport(1, " CovDump: %zd PCs written to packed file\n", vb - old_vb);
543 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000544 } else {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000545 // One file per module per process.
Alexey Samsonov656c29b2014-12-02 22:20:11 +0000546 path.clear();
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000547 path.append("%s/%s.%zd.sancov", coverage_dir, module_name,
548 internal_getpid());
Sergey Matveev83f91e72014-05-21 13:43:52 +0000549 int fd = CovOpenFile(false /* packed */, module_name);
550 if (fd > 0) {
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000551 internal_write(fd, offsets.data(), offsets.size() * sizeof(u32));
552 internal_close(fd);
553 VReport(1, " CovDump: %s: %zd PCs written\n", path.data(),
554 vb - old_vb);
555 }
Evgeniy Stepanov8ab205f2014-02-12 15:29:22 +0000556 }
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000557 }
558 }
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000559 if (cov_fd >= 0)
560 internal_close(cov_fd);
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000561 coverage_data.DumpCallerCalleePairs();
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000562 coverage_data.DumpTrace();
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000563#endif // !SANITIZER_WINDOWS
564}
565
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000566void CovPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
567 if (!args) return;
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000568 if (!coverage_enabled) return;
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000569 cov_sandboxed = args->coverage_sandboxed;
570 if (!cov_sandboxed) return;
571 cov_fd = args->coverage_fd;
572 cov_max_block_size = args->coverage_max_block_size;
573 if (cov_fd < 0)
574 // Pre-open the file now. The sandbox won't allow us to do it later.
Sergey Matveev83f91e72014-05-21 13:43:52 +0000575 cov_fd = CovOpenFile(true /* packed */, 0);
Sergey Matveev6cb47a082014-05-19 12:53:03 +0000576}
577
Sergey Matveev83f91e72014-05-21 13:43:52 +0000578int MaybeOpenCovFile(const char *name) {
579 CHECK(name);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000580 if (!coverage_enabled) return -1;
Sergey Matveev83f91e72014-05-21 13:43:52 +0000581 return CovOpenFile(true /* packed */, name);
582}
Evgeniy Stepanovfe181022014-06-04 12:13:54 +0000583
584void CovBeforeFork() {
585 coverage_data.BeforeFork();
586}
587
588void CovAfterFork(int child_pid) {
589 coverage_data.AfterFork(child_pid);
590}
591
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000592void InitializeCoverage(bool enabled, const char *dir) {
593 coverage_enabled = enabled;
594 coverage_dir = dir;
595 if (enabled) coverage_data.Init();
596#if !SANITIZER_WINDOWS
597 if (!common_flags()->coverage_direct) Atexit(__sanitizer_cov_dump);
598#endif
599}
600
601void ReInitializeCoverage(bool enabled, const char *dir) {
602 coverage_enabled = enabled;
603 coverage_dir = dir;
604 coverage_data.ReInit();
605}
606
607void CoverageUpdateMapping() {
608 if (coverage_enabled)
609 CovUpdateMapping(coverage_dir);
610}
611
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000612} // namespace __sanitizer
613
614extern "C" {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000615SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov(u32 *guard) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000616 coverage_data.Add(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
617 guard);
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000618}
Kostya Serebryanyb6eae0c2014-10-31 17:19:11 +0000619SANITIZER_INTERFACE_ATTRIBUTE void
620__sanitizer_cov_indir_call16(uptr callee, uptr callee_cache16[]) {
621 coverage_data.IndirCall(StackTrace::GetPreviousInstructionPc(GET_CALLER_PC()),
622 callee, callee_cache16, 16);
623}
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000624SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_init() {
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000625 coverage_enabled = true;
626 coverage_dir = common_flags()->coverage_dir;
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000627 coverage_data.Init();
628}
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000629SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_dump() { CovDump(); }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000630SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cov_module_init(s32 *guards,
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000631 uptr npcs) {
632 coverage_data.InitializeGuards(guards, npcs);
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000633 if (!common_flags()->coverage_direct) return;
634 if (SANITIZER_ANDROID && coverage_enabled) {
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000635 // dlopen/dlclose interceptors do not work on Android, so we rely on
636 // Extend() calls to update .sancov.map.
Evgeniy Stepanov05dc4be2014-12-26 12:32:32 +0000637 CovUpdateMapping(coverage_dir, GET_CALLER_PC());
Evgeniy Stepanov38c228a2014-06-05 14:38:53 +0000638 }
Evgeniy Stepanov567e5162014-05-27 12:37:52 +0000639 coverage_data.Extend(npcs);
640}
Sergey Matveev83f91e72014-05-21 13:43:52 +0000641SANITIZER_INTERFACE_ATTRIBUTE
642sptr __sanitizer_maybe_open_cov_file(const char *name) {
643 return MaybeOpenCovFile(name);
644}
Kostya Serebryany183cb6e2014-11-14 23:15:55 +0000645SANITIZER_INTERFACE_ATTRIBUTE
646uptr __sanitizer_get_total_unique_coverage() {
647 return atomic_load(&coverage_counter, memory_order_relaxed);
648}
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000649
650SANITIZER_INTERFACE_ATTRIBUTE
651void __sanitizer_cov_trace_func_enter(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000652 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000653}
654SANITIZER_INTERFACE_ATTRIBUTE
655void __sanitizer_cov_trace_basic_block(uptr *cache) {
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000656 coverage_data.TraceBasicBlock(cache);
Kostya Serebryanyc9d251e2014-11-19 00:24:11 +0000657}
Bob Wilsona08e9ac2013-11-15 07:18:15 +0000658} // extern "C"