1 //===-- sanitizer_common.cc -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common.h"
15 #include "sanitizer_allocator_interface.h"
16 #include "sanitizer_allocator_internal.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_libc.h"
19 #include "sanitizer_placement_new.h"
20 #include "sanitizer_stacktrace_printer.h"
21 #include "sanitizer_symbolizer.h"
23 namespace __sanitizer {
25 const char *SanitizerToolName = "SanitizerTool";
27 atomic_uint32_t current_verbosity;
30 StaticSpinMutex report_file_mu;
31 ReportFile report_file = {&report_file_mu, kStderrFd, "", "", 0};
33 void RawWrite(const char *buffer) {
34 report_file.Write(buffer, internal_strlen(buffer));
37 void ReportFile::ReopenIfNecessary() {
39 if (fd == kStdoutFd || fd == kStderrFd) return;
41 uptr pid = internal_getpid();
42 // If in tracer, use the parent's file.
43 if (pid == stoptheworld_tracer_pid)
44 pid = stoptheworld_tracer_ppid;
45 if (fd != kInvalidFd) {
46 // If the report file is already opened by the current process,
47 // do nothing. Otherwise the report file was opened by the parent
48 // process, close it now.
55 const char *exe_name = GetProcessName();
56 if (common_flags()->log_exe_name && exe_name) {
57 internal_snprintf(full_path, kMaxPathLength, "%s.%s.%zu", path_prefix,
60 internal_snprintf(full_path, kMaxPathLength, "%s.%zu", path_prefix, pid);
62 fd = OpenFile(full_path, WrOnly);
63 if (fd == kInvalidFd) {
64 const char *ErrorMsgPrefix = "ERROR: Can't open file: ";
65 WriteToFile(kStderrFd, ErrorMsgPrefix, internal_strlen(ErrorMsgPrefix));
66 WriteToFile(kStderrFd, full_path, internal_strlen(full_path));
72 void ReportFile::SetReportPath(const char *path) {
75 uptr len = internal_strlen(path);
76 if (len > sizeof(path_prefix) - 100) {
77 Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
78 path[0], path[1], path[2], path[3],
79 path[4], path[5], path[6], path[7]);
84 if (fd != kStdoutFd && fd != kStderrFd && fd != kInvalidFd)
87 if (internal_strcmp(path, "stdout") == 0) {
89 } else if (internal_strcmp(path, "stderr") == 0) {
92 internal_snprintf(path_prefix, kMaxPathLength, "%s", path);
96 // PID of the tracer task in StopTheWorld. It shares the address space with the
97 // main process, but has a different PID and thus requires special handling.
98 uptr stoptheworld_tracer_pid = 0;
99 // Cached pid of parent process - if the parent process dies, we want to keep
100 // writing to the same log file.
101 uptr stoptheworld_tracer_ppid = 0;
103 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
104 const char *mmap_type, error_t err,
106 static int recursion_count;
107 if (raw_report || recursion_count) {
108 // If raw report is requested or we went into recursion, just die.
109 // The Report() and CHECK calls below may call mmap recursively and fail.
110 RawWrite("ERROR: Failed to mmap\n");
114 Report("ERROR: %s failed to "
115 "%s 0x%zx (%zd) bytes of %s (error code: %d)\n",
116 SanitizerToolName, mmap_type, size, size, mem_type, err);
120 UNREACHABLE("unable to mmap");
123 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
124 uptr *read_len, uptr max_len, error_t *errno_p) {
125 uptr PageSize = GetPageSizeCached();
126 uptr kMinFileLen = PageSize;
130 // The files we usually open are not seekable, so try different buffer sizes.
131 for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
132 fd_t fd = OpenFile(file_name, RdOnly, errno_p);
133 if (fd == kInvalidFd) return false;
134 UnmapOrDie(*buff, *buff_size);
135 *buff = (char*)MmapOrDie(size, __func__);
138 // Read up to one page at a time.
139 bool reached_eof = false;
140 while (*read_len + PageSize <= size) {
142 if (!ReadFromFile(fd, *buff + *read_len, PageSize, &just_read, errno_p)) {
143 UnmapOrDie(*buff, *buff_size);
146 if (just_read == 0) {
150 *read_len += just_read;
153 if (reached_eof) // We've read the whole file.
159 typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
160 typedef bool U32ComparisonFunction(const u32 &a, const u32 &b);
163 static inline bool CompareLess(const T &a, const T &b) {
167 void SortArray(uptr *array, uptr size) {
168 InternalSort<uptr*, UptrComparisonFunction>(&array, size, CompareLess);
171 void SortArray(u32 *array, uptr size) {
172 InternalSort<u32*, U32ComparisonFunction>(&array, size, CompareLess);
175 const char *StripPathPrefix(const char *filepath,
176 const char *strip_path_prefix) {
177 if (!filepath) return nullptr;
178 if (!strip_path_prefix) return filepath;
179 const char *res = filepath;
180 if (const char *pos = internal_strstr(filepath, strip_path_prefix))
181 res = pos + internal_strlen(strip_path_prefix);
182 if (res[0] == '.' && res[1] == '/')
187 const char *StripModuleName(const char *module) {
190 if (SANITIZER_WINDOWS) {
191 // On Windows, both slash and backslash are possible.
192 // Pick the one that goes last.
193 if (const char *bslash_pos = internal_strrchr(module, '\\'))
194 return StripModuleName(bslash_pos + 1);
196 if (const char *slash_pos = internal_strrchr(module, '/')) {
197 return slash_pos + 1;
202 void ReportErrorSummary(const char *error_message, const char *alt_tool_name) {
203 if (!common_flags()->print_summary)
205 InternalScopedString buff(kMaxSummaryLength);
206 buff.append("SUMMARY: %s: %s",
207 alt_tool_name ? alt_tool_name : SanitizerToolName, error_message);
208 __sanitizer_report_error_summary(buff.data());
212 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
213 const char *alt_tool_name) {
214 if (!common_flags()->print_summary) return;
215 InternalScopedString buff(kMaxSummaryLength);
216 buff.append("%s ", error_type);
217 RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
218 common_flags()->strip_path_prefix);
219 ReportErrorSummary(buff.data(), alt_tool_name);
223 // Removes the ANSI escape sequences from the input string (in-place).
224 void RemoveANSIEscapeSequencesFromString(char *str) {
228 // We are going to remove the escape sequences in place.
233 // Skip over ANSI escape sequences with pointer 's'.
234 if (*s == '\033' && *(s + 1) == '[') {
235 s = internal_strchrnul(s, 'm');
242 // 's' now points at a character we want to keep. Copy over the buffer
243 // content if the escape sequence has been perviously skipped andadvance
248 // If we have not seen an escape sequence, just advance both pointers.
253 // Null terminate the string.
257 void LoadedModule::set(const char *module_name, uptr base_address) {
259 full_name_ = internal_strdup(module_name);
260 base_address_ = base_address;
263 void LoadedModule::set(const char *module_name, uptr base_address,
264 ModuleArch arch, u8 uuid[kModuleUUIDSize],
266 set(module_name, base_address);
268 internal_memcpy(uuid_, uuid, sizeof(uuid_));
269 instrumented_ = instrumented;
272 void LoadedModule::clear() {
273 InternalFree(full_name_);
275 max_executable_address_ = 0;
276 full_name_ = nullptr;
277 arch_ = kModuleArchUnknown;
278 internal_memset(uuid_, 0, kModuleUUIDSize);
279 instrumented_ = false;
280 while (!ranges_.empty()) {
281 AddressRange *r = ranges_.front();
287 void LoadedModule::addAddressRange(uptr beg, uptr end, bool executable,
289 void *mem = InternalAlloc(sizeof(AddressRange));
290 AddressRange *r = new(mem) AddressRange(beg, end, executable, writable);
291 ranges_.push_back(r);
292 if (executable && end > max_executable_address_)
293 max_executable_address_ = end;
296 bool LoadedModule::containsAddress(uptr address) const {
297 for (const AddressRange &r : ranges()) {
298 if (r.beg <= address && address < r.end)
304 static atomic_uintptr_t g_total_mmaped;
306 void IncreaseTotalMmap(uptr size) {
307 if (!common_flags()->mmap_limit_mb) return;
309 atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
310 // Since for now mmap_limit_mb is not a user-facing flag, just kill
311 // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
312 RAW_CHECK((total_mmaped >> 20) < common_flags()->mmap_limit_mb);
315 void DecreaseTotalMmap(uptr size) {
316 if (!common_flags()->mmap_limit_mb) return;
317 atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
320 bool TemplateMatch(const char *templ, const char *str) {
321 if ((!str) || str[0] == 0)
324 if (templ && templ[0] == '^') {
328 bool asterisk = false;
329 while (templ && templ[0]) {
330 if (templ[0] == '*') {
337 return str[0] == 0 || asterisk;
340 char *tpos = (char*)internal_strchr(templ, '*');
341 char *tpos1 = (char*)internal_strchr(templ, '$');
342 if ((!tpos) || (tpos1 && tpos1 < tpos))
346 const char *str0 = str;
347 const char *spos = internal_strstr(str, templ);
348 str = spos + internal_strlen(templ);
351 tpos[0] = tpos == tpos1 ? '$' : '*';
354 if (start && spos != str0)
362 static const char kPathSeparator = SANITIZER_WINDOWS ? ';' : ':';
364 char *FindPathToBinary(const char *name) {
365 if (FileExists(name)) {
366 return internal_strdup(name);
369 const char *path = GetEnv("PATH");
372 uptr name_len = internal_strlen(name);
373 InternalScopedBuffer<char> buffer(kMaxPathLength);
374 const char *beg = path;
376 const char *end = internal_strchrnul(beg, kPathSeparator);
377 uptr prefix_len = end - beg;
378 if (prefix_len + name_len + 2 <= kMaxPathLength) {
379 internal_memcpy(buffer.data(), beg, prefix_len);
380 buffer[prefix_len] = '/';
381 internal_memcpy(&buffer[prefix_len + 1], name, name_len);
382 buffer[prefix_len + 1 + name_len] = '\0';
383 if (FileExists(buffer.data()))
384 return internal_strdup(buffer.data());
386 if (*end == '\0') break;
392 static char binary_name_cache_str[kMaxPathLength];
393 static char process_name_cache_str[kMaxPathLength];
395 const char *GetProcessName() {
396 return process_name_cache_str;
399 static uptr ReadProcessName(/*out*/ char *buf, uptr buf_len) {
400 ReadLongProcessName(buf, buf_len);
401 char *s = const_cast<char *>(StripModuleName(buf));
402 uptr len = internal_strlen(s);
404 internal_memmove(buf, s, len);
410 void UpdateProcessName() {
411 ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
414 // Call once to make sure that binary_name_cache_str is initialized
415 void CacheBinaryName() {
416 if (binary_name_cache_str[0] != '\0')
418 ReadBinaryName(binary_name_cache_str, sizeof(binary_name_cache_str));
419 ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
422 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len) {
424 uptr name_len = internal_strlen(binary_name_cache_str);
425 name_len = (name_len < buf_len - 1) ? name_len : buf_len - 1;
428 internal_memcpy(buf, binary_name_cache_str, name_len);
429 buf[name_len] = '\0';
433 void PrintCmdline() {
434 char **argv = GetArgv();
436 Printf("\nCommand: ");
437 for (uptr i = 0; argv[i]; ++i)
438 Printf("%s ", argv[i]);
443 static const int kMaxMallocFreeHooks = 5;
444 struct MallocFreeHook {
445 void (*malloc_hook)(const void *, uptr);
446 void (*free_hook)(const void *);
449 static MallocFreeHook MFHooks[kMaxMallocFreeHooks];
451 void RunMallocHooks(const void *ptr, uptr size) {
452 for (int i = 0; i < kMaxMallocFreeHooks; i++) {
453 auto hook = MFHooks[i].malloc_hook;
459 void RunFreeHooks(const void *ptr) {
460 for (int i = 0; i < kMaxMallocFreeHooks; i++) {
461 auto hook = MFHooks[i].free_hook;
467 static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
468 void (*free_hook)(const void *)) {
469 if (!malloc_hook || !free_hook) return 0;
470 for (int i = 0; i < kMaxMallocFreeHooks; i++) {
471 if (MFHooks[i].malloc_hook == nullptr) {
472 MFHooks[i].malloc_hook = malloc_hook;
473 MFHooks[i].free_hook = free_hook;
480 } // namespace __sanitizer
482 using namespace __sanitizer; // NOLINT
485 void __sanitizer_set_report_path(const char *path) {
486 report_file.SetReportPath(path);
489 void __sanitizer_set_report_fd(void *fd) {
490 report_file.fd = (fd_t)reinterpret_cast<uptr>(fd);
491 report_file.fd_pid = internal_getpid();
494 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary,
495 const char *error_summary) {
496 Printf("%s\n", error_summary);
499 SANITIZER_INTERFACE_ATTRIBUTE
500 void __sanitizer_set_death_callback(void (*callback)(void)) {
501 SetUserDieCallback(callback);
504 SANITIZER_INTERFACE_ATTRIBUTE
505 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const void *,
507 void (*free_hook)(const void *)) {
508 return InstallMallocFreeHooks(malloc_hook, free_hook);