blob: 05bd8764c61c0a348d929992f60b4fcccc49492f [file] [log] [blame]
Alexey Samsonov230c3be2012-06-06 09:26:25 +00001//===-- sanitizer_common.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// This file is shared between AddressSanitizer and ThreadSanitizer
11// run-time libraries.
12//===----------------------------------------------------------------------===//
13
14#include "sanitizer_common.h"
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +000015#include "sanitizer_flags.h"
Alexey Samsonov230c3be2012-06-06 09:26:25 +000016#include "sanitizer_libc.h"
Alexey Samsonov2fb08722013-11-01 17:02:14 +000017#include "sanitizer_stacktrace.h"
18#include "sanitizer_symbolizer.h"
Alexey Samsonov4c496662012-06-15 07:00:31 +000019
Alexey Samsonov230c3be2012-06-06 09:26:25 +000020namespace __sanitizer {
21
Kostya Serebryany859778a2013-01-31 14:11:21 +000022const char *SanitizerToolName = "SanitizerTool";
23
Kostya Serebryanyf67ec2b2012-11-23 15:38:49 +000024uptr GetPageSizeCached() {
25 static uptr PageSize;
26 if (!PageSize)
27 PageSize = GetPageSize();
28 return PageSize;
29}
30
Alexander Potapenkodedba5d2013-01-18 16:44:27 +000031
32// By default, dump to stderr. If |log_to_file| is true and |report_fd_pid|
33// isn't equal to the current PID, try to obtain file descriptor by opening
34// file "report_path_prefix.<PID>".
Peter Collingbourne0c547de2013-05-17 16:17:19 +000035fd_t report_fd = kStderrFd;
Reid Kleckner923bac72013-09-05 03:19:57 +000036
37// Set via __sanitizer_set_report_path.
38bool log_to_file = false;
39char report_path_prefix[sizeof(report_path_prefix)];
40
Alexander Potapenkodedba5d2013-01-18 16:44:27 +000041// PID of process that opened |report_fd|. If a fork() occurs, the PID of the
42// child thread will be different from |report_fd_pid|.
Reid Kleckner923bac72013-09-05 03:19:57 +000043uptr report_fd_pid = 0;
Kostya Serebryany81dfbb72012-09-14 04:35:14 +000044
Stephen Hines2d1fdb22014-05-28 23:58:16 -070045// PID of the tracer task in StopTheWorld. It shares the address space with the
46// main process, but has a different PID and thus requires special handling.
47uptr stoptheworld_tracer_pid = 0;
48// Cached pid of parent process - if the parent process dies, we want to keep
49// writing to the same log file.
50uptr stoptheworld_tracer_ppid = 0;
51
Sergey Matveev90629fb2013-08-26 13:20:31 +000052static DieCallbackType DieCallback;
53void SetDieCallback(DieCallbackType callback) {
Alexey Samsonov591616d2012-09-11 09:44:48 +000054 DieCallback = callback;
55}
56
Sergey Matveev90629fb2013-08-26 13:20:31 +000057DieCallbackType GetDieCallback() {
58 return DieCallback;
59}
60
Alexey Samsonov591616d2012-09-11 09:44:48 +000061void NORETURN Die() {
62 if (DieCallback) {
63 DieCallback();
64 }
Alexey Samsonovf8822472013-02-20 13:54:32 +000065 internal__exit(1);
Alexey Samsonov591616d2012-09-11 09:44:48 +000066}
67
68static CheckFailedCallbackType CheckFailedCallback;
69void SetCheckFailedCallback(CheckFailedCallbackType callback) {
70 CheckFailedCallback = callback;
71}
72
73void NORETURN CheckFailed(const char *file, int line, const char *cond,
74 u64 v1, u64 v2) {
75 if (CheckFailedCallback) {
76 CheckFailedCallback(file, line, cond, v1, v2);
77 }
Dmitry Vyukove3c35c72013-01-11 15:07:49 +000078 Report("Sanitizer CHECK failed: %s:%d %s (%lld, %lld)\n", file, line, cond,
79 v1, v2);
Alexey Samsonov591616d2012-09-11 09:44:48 +000080 Die();
81}
82
Alexey Samsonovcffe2f52012-06-07 05:38:26 +000083uptr ReadFileToBuffer(const char *file_name, char **buff,
84 uptr *buff_size, uptr max_len) {
Kostya Serebryanyf67ec2b2012-11-23 15:38:49 +000085 uptr PageSize = GetPageSizeCached();
86 uptr kMinFileLen = PageSize;
Alexey Samsonovcffe2f52012-06-07 05:38:26 +000087 uptr read_len = 0;
88 *buff = 0;
89 *buff_size = 0;
90 // The files we usually open are not seekable, so try different buffer sizes.
91 for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
Peter Collingbourne9578a3e2013-05-08 14:43:49 +000092 uptr openrv = OpenFile(file_name, /*write*/ false);
93 if (internal_iserror(openrv)) return 0;
94 fd_t fd = openrv;
Alexey Samsonovcffe2f52012-06-07 05:38:26 +000095 UnmapOrDie(*buff, *buff_size);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070096 *buff = (char*)MmapOrDie(size, __func__);
Alexey Samsonovcffe2f52012-06-07 05:38:26 +000097 *buff_size = size;
98 // Read up to one page at a time.
99 read_len = 0;
100 bool reached_eof = false;
Kostya Serebryanyf67ec2b2012-11-23 15:38:49 +0000101 while (read_len + PageSize <= size) {
102 uptr just_read = internal_read(fd, *buff + read_len, PageSize);
Alexey Samsonovcffe2f52012-06-07 05:38:26 +0000103 if (just_read == 0) {
104 reached_eof = true;
105 break;
106 }
107 read_len += just_read;
108 }
109 internal_close(fd);
110 if (reached_eof) // We've read the whole file.
111 break;
112 }
113 return read_len;
114}
115
Sergey Matveev15bb32b2013-05-13 11:58:48 +0000116typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
117
118template<class T>
119static inline bool CompareLess(const T &a, const T &b) {
120 return a < b;
121}
122
Alexey Samsonov4c496662012-06-15 07:00:31 +0000123void SortArray(uptr *array, uptr size) {
Sergey Matveev15bb32b2013-05-13 11:58:48 +0000124 InternalSort<uptr*, UptrComparisonFunction>(&array, size, CompareLess);
Alexey Samsonov4c496662012-06-15 07:00:31 +0000125}
126
Kostya Serebryanycc752592012-12-06 06:10:31 +0000127// We want to map a chunk of address space aligned to 'alignment'.
128// We do it by maping a bit more and then unmaping redundant pieces.
129// We probably can do it with fewer syscalls in some OS-dependent way.
130void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type) {
Bill Wendling2dae63a2012-12-06 07:43:17 +0000131// uptr PageSize = GetPageSizeCached();
Kostya Serebryanycc752592012-12-06 06:10:31 +0000132 CHECK(IsPowerOfTwo(size));
133 CHECK(IsPowerOfTwo(alignment));
134 uptr map_size = size + alignment;
135 uptr map_res = (uptr)MmapOrDie(map_size, mem_type);
136 uptr map_end = map_res + map_size;
137 uptr res = map_res;
138 if (res & (alignment - 1)) // Not aligned.
Dmitry Vyukov3617ad72012-12-06 15:42:54 +0000139 res = (map_res + alignment) & ~(alignment - 1);
Kostya Serebryanycc752592012-12-06 06:10:31 +0000140 uptr end = res + size;
141 if (res != map_res)
142 UnmapOrDie((void*)map_res, res - map_res);
143 if (end != map_end)
144 UnmapOrDie((void*)end, map_end - end);
145 return (void*)res;
146}
147
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000148const char *StripPathPrefix(const char *filepath,
149 const char *strip_path_prefix) {
150 if (filepath == 0) return 0;
151 if (strip_path_prefix == 0) return filepath;
152 const char *pos = internal_strstr(filepath, strip_path_prefix);
153 if (pos == 0) return filepath;
154 pos += internal_strlen(strip_path_prefix);
155 if (pos[0] == '.' && pos[1] == '/')
156 pos += 2;
157 return pos;
158}
159
Alexey Samsonovbb4697f2013-11-14 09:41:24 +0000160void PrintSourceLocation(InternalScopedString *buffer, const char *file,
161 int line, int column) {
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000162 CHECK(file);
Alexey Samsonovbb4697f2013-11-14 09:41:24 +0000163 buffer->append("%s",
164 StripPathPrefix(file, common_flags()->strip_path_prefix));
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000165 if (line > 0) {
Alexey Samsonovbb4697f2013-11-14 09:41:24 +0000166 buffer->append(":%d", line);
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000167 if (column > 0)
Alexey Samsonovbb4697f2013-11-14 09:41:24 +0000168 buffer->append(":%d", column);
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000169 }
170}
171
Alexey Samsonovbb4697f2013-11-14 09:41:24 +0000172void PrintModuleAndOffset(InternalScopedString *buffer, const char *module,
173 uptr offset) {
174 buffer->append("(%s+0x%zx)",
175 StripPathPrefix(module, common_flags()->strip_path_prefix),
176 offset);
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000177}
178
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000179void ReportErrorSummary(const char *error_message) {
Alexey Samsonov694d8562013-11-14 08:56:59 +0000180 if (!common_flags()->print_summary)
181 return;
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000182 InternalScopedBuffer<char> buff(kMaxSummaryLength);
183 internal_snprintf(buff.data(), buff.size(),
184 "SUMMARY: %s: %s", SanitizerToolName, error_message);
185 __sanitizer_report_error_summary(buff.data());
186}
187
Kostya Serebryany2673fd82013-02-06 12:36:49 +0000188void ReportErrorSummary(const char *error_type, const char *file,
189 int line, const char *function) {
Alexey Samsonov694d8562013-11-14 08:56:59 +0000190 if (!common_flags()->print_summary)
191 return;
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000192 InternalScopedBuffer<char> buff(kMaxSummaryLength);
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000193 internal_snprintf(
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000194 buff.data(), buff.size(), "%s %s:%d %s", error_type,
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000195 file ? StripPathPrefix(file, common_flags()->strip_path_prefix) : "??",
196 line, function ? function : "??");
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000197 ReportErrorSummary(buff.data());
198}
199
200void ReportErrorSummary(const char *error_type, StackTrace *stack) {
Alexey Samsonov694d8562013-11-14 08:56:59 +0000201 if (!common_flags()->print_summary)
202 return;
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000203 AddressInfo ai;
Alexey Samsonov50cdc5a2013-11-01 18:00:22 +0000204#if !SANITIZER_GO
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700205 if (stack->size > 0 && Symbolizer::Get()->CanReturnFileLineInfo()) {
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000206 // Currently, we include the first stack frame into the report summary.
207 // Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
208 uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700209 Symbolizer::Get()->SymbolizePC(pc, &ai, 1);
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000210 }
Alexey Samsonov50cdc5a2013-11-01 18:00:22 +0000211#endif
Alexey Samsonov2fb08722013-11-01 17:02:14 +0000212 ReportErrorSummary(error_type, ai.file, ai.line, ai.function);
Kostya Serebryany2673fd82013-02-06 12:36:49 +0000213}
214
Alexey Samsonov7847d772013-09-10 14:36:16 +0000215LoadedModule::LoadedModule(const char *module_name, uptr base_address) {
216 full_name_ = internal_strdup(module_name);
217 base_address_ = base_address;
218 n_ranges_ = 0;
219}
220
221void LoadedModule::addAddressRange(uptr beg, uptr end) {
222 CHECK_LT(n_ranges_, kMaxNumberOfAddressRanges);
223 ranges_[n_ranges_].beg = beg;
224 ranges_[n_ranges_].end = end;
225 n_ranges_++;
226}
227
228bool LoadedModule::containsAddress(uptr address) const {
229 for (uptr i = 0; i < n_ranges_; i++) {
230 if (ranges_[i].beg <= address && address < ranges_[i].end)
231 return true;
232 }
233 return false;
234}
235
Bob Wilsondbd69cc2013-11-15 07:18:15 +0000236char *StripModuleName(const char *module) {
237 if (module == 0)
238 return 0;
239 const char *short_module_name = internal_strrchr(module, '/');
240 if (short_module_name)
241 short_module_name += 1;
242 else
243 short_module_name = module;
244 return internal_strdup(short_module_name);
245}
246
Stephen Hines2d1fdb22014-05-28 23:58:16 -0700247static atomic_uintptr_t g_total_mmaped;
248
249void IncreaseTotalMmap(uptr size) {
250 if (!common_flags()->mmap_limit_mb) return;
251 uptr total_mmaped =
252 atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
253 if ((total_mmaped >> 20) > common_flags()->mmap_limit_mb) {
254 // Since for now mmap_limit_mb is not a user-facing flag, just CHECK.
255 uptr mmap_limit_mb = common_flags()->mmap_limit_mb;
256 common_flags()->mmap_limit_mb = 0; // Allow mmap in CHECK.
257 RAW_CHECK(total_mmaped >> 20 < mmap_limit_mb);
258 }
259}
260
261void DecreaseTotalMmap(uptr size) {
262 if (!common_flags()->mmap_limit_mb) return;
263 atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
264}
265
Alexey Samsonov230c3be2012-06-06 09:26:25 +0000266} // namespace __sanitizer
Kostya Serebryany81dfbb72012-09-14 04:35:14 +0000267
Alexey Samsonovac8564e2012-11-02 09:23:36 +0000268using namespace __sanitizer; // NOLINT
269
270extern "C" {
Kostya Serebryany81dfbb72012-09-14 04:35:14 +0000271void __sanitizer_set_report_path(const char *path) {
Dmitry Vyukovb48c2b22013-10-15 12:25:29 +0000272 if (!path)
273 return;
Kostya Serebryany81dfbb72012-09-14 04:35:14 +0000274 uptr len = internal_strlen(path);
Alexander Potapenkodedba5d2013-01-18 16:44:27 +0000275 if (len > sizeof(report_path_prefix) - 100) {
Kostya Serebryany81dfbb72012-09-14 04:35:14 +0000276 Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
277 path[0], path[1], path[2], path[3],
278 path[4], path[5], path[6], path[7]);
279 Die();
280 }
Alexey Samsonovf3457cb2012-11-02 09:38:47 +0000281 if (report_fd != kStdoutFd &&
282 report_fd != kStderrFd &&
283 report_fd != kInvalidFd)
284 internal_close(report_fd);
Dmitry Vyukovb48c2b22013-10-15 12:25:29 +0000285 report_fd = kInvalidFd;
286 log_to_file = false;
287 if (internal_strcmp(path, "stdout") == 0) {
288 report_fd = kStdoutFd;
289 } else if (internal_strcmp(path, "stderr") == 0) {
290 report_fd = kStderrFd;
291 } else {
292 internal_strncpy(report_path_prefix, path, sizeof(report_path_prefix));
293 report_path_prefix[len] = '\0';
294 log_to_file = true;
295 }
Alexey Samsonovac8564e2012-11-02 09:23:36 +0000296}
Alexander Potapenko25742572012-12-10 13:10:40 +0000297
Kostya Serebryany2673fd82013-02-06 12:36:49 +0000298void __sanitizer_report_error_summary(const char *error_summary) {
Nick Lewycky47fcd762013-10-23 07:45:53 +0000299 Printf("%s\n", error_summary);
Kostya Serebryany2673fd82013-02-06 12:36:49 +0000300}
Alexey Samsonovac8564e2012-11-02 09:23:36 +0000301} // extern "C"