Home | History | Annotate | Download | only in sanitizer_common
      1 //===-- 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"
     15 #include "sanitizer_libc.h"
     16 
     17 namespace __sanitizer {
     18 
     19 const char *SanitizerToolName = "SanitizerTool";
     20 uptr SanitizerVerbosity = 0;
     21 
     22 uptr GetPageSizeCached() {
     23   static uptr PageSize;
     24   if (!PageSize)
     25     PageSize = GetPageSize();
     26   return PageSize;
     27 }
     28 
     29 static bool log_to_file = false;  // Set to true by __sanitizer_set_report_path
     30 
     31 // By default, dump to stderr. If |log_to_file| is true and |report_fd_pid|
     32 // isn't equal to the current PID, try to obtain file descriptor by opening
     33 // file "report_path_prefix.<PID>".
     34 static fd_t report_fd = kStderrFd;
     35 static char report_path_prefix[4096];  // Set via __sanitizer_set_report_path.
     36 // PID of process that opened |report_fd|. If a fork() occurs, the PID of the
     37 // child thread will be different from |report_fd_pid|.
     38 static int report_fd_pid = 0;
     39 
     40 static void (*DieCallback)(void);
     41 void SetDieCallback(void (*callback)(void)) {
     42   DieCallback = callback;
     43 }
     44 
     45 void NORETURN Die() {
     46   if (DieCallback) {
     47     DieCallback();
     48   }
     49   internal__exit(1);
     50 }
     51 
     52 static CheckFailedCallbackType CheckFailedCallback;
     53 void SetCheckFailedCallback(CheckFailedCallbackType callback) {
     54   CheckFailedCallback = callback;
     55 }
     56 
     57 void NORETURN CheckFailed(const char *file, int line, const char *cond,
     58                           u64 v1, u64 v2) {
     59   if (CheckFailedCallback) {
     60     CheckFailedCallback(file, line, cond, v1, v2);
     61   }
     62   Report("Sanitizer CHECK failed: %s:%d %s (%lld, %lld)\n", file, line, cond,
     63                                                             v1, v2);
     64   Die();
     65 }
     66 
     67 static void MaybeOpenReportFile() {
     68   if (!log_to_file || (report_fd_pid == GetPid())) return;
     69   InternalScopedBuffer<char> report_path_full(4096);
     70   internal_snprintf(report_path_full.data(), report_path_full.size(),
     71                     "%s.%d", report_path_prefix, GetPid());
     72   fd_t fd = OpenFile(report_path_full.data(), true);
     73   if (fd == kInvalidFd) {
     74     report_fd = kStderrFd;
     75     log_to_file = false;
     76     Report("ERROR: Can't open file: %s\n", report_path_full.data());
     77     Die();
     78   }
     79   if (report_fd != kInvalidFd) {
     80     // We're in the child. Close the parent's log.
     81     internal_close(report_fd);
     82   }
     83   report_fd = fd;
     84   report_fd_pid = GetPid();
     85 }
     86 
     87 bool PrintsToTty() {
     88   MaybeOpenReportFile();
     89   return internal_isatty(report_fd);
     90 }
     91 
     92 void RawWrite(const char *buffer) {
     93   static const char *kRawWriteError = "RawWrite can't output requested buffer!";
     94   uptr length = (uptr)internal_strlen(buffer);
     95   MaybeOpenReportFile();
     96   if (length != internal_write(report_fd, buffer, length)) {
     97     internal_write(report_fd, kRawWriteError, internal_strlen(kRawWriteError));
     98     Die();
     99   }
    100 }
    101 
    102 uptr ReadFileToBuffer(const char *file_name, char **buff,
    103                       uptr *buff_size, uptr max_len) {
    104   uptr PageSize = GetPageSizeCached();
    105   uptr kMinFileLen = PageSize;
    106   uptr read_len = 0;
    107   *buff = 0;
    108   *buff_size = 0;
    109   // The files we usually open are not seekable, so try different buffer sizes.
    110   for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
    111     fd_t fd = OpenFile(file_name, /*write*/ false);
    112     if (fd == kInvalidFd) return 0;
    113     UnmapOrDie(*buff, *buff_size);
    114     *buff = (char*)MmapOrDie(size, __FUNCTION__);
    115     *buff_size = size;
    116     // Read up to one page at a time.
    117     read_len = 0;
    118     bool reached_eof = false;
    119     while (read_len + PageSize <= size) {
    120       uptr just_read = internal_read(fd, *buff + read_len, PageSize);
    121       if (just_read == 0) {
    122         reached_eof = true;
    123         break;
    124       }
    125       read_len += just_read;
    126     }
    127     internal_close(fd);
    128     if (reached_eof)  // We've read the whole file.
    129       break;
    130   }
    131   return read_len;
    132 }
    133 
    134 // We don't want to use std::sort to avoid including <algorithm>, as
    135 // we may end up with two implementation of std::sort - one in instrumented
    136 // code, and the other in runtime.
    137 // qsort() from stdlib won't work as it calls malloc(), which results
    138 // in deadlock in ASan allocator.
    139 // We re-implement in-place sorting w/o recursion as straightforward heapsort.
    140 void SortArray(uptr *array, uptr size) {
    141   if (size < 2)
    142     return;
    143   // Stage 1: insert elements to the heap.
    144   for (uptr i = 1; i < size; i++) {
    145     uptr j, p;
    146     for (j = i; j > 0; j = p) {
    147       p = (j - 1) / 2;
    148       if (array[j] > array[p])
    149         Swap(array[j], array[p]);
    150       else
    151         break;
    152     }
    153   }
    154   // Stage 2: swap largest element with the last one,
    155   // and sink the new top.
    156   for (uptr i = size - 1; i > 0; i--) {
    157     Swap(array[0], array[i]);
    158     uptr j, max_ind;
    159     for (j = 0; j < i; j = max_ind) {
    160       uptr left = 2 * j + 1;
    161       uptr right = 2 * j + 2;
    162       max_ind = j;
    163       if (left < i && array[left] > array[max_ind])
    164         max_ind = left;
    165       if (right < i && array[right] > array[max_ind])
    166         max_ind = right;
    167       if (max_ind != j)
    168         Swap(array[j], array[max_ind]);
    169       else
    170         break;
    171     }
    172   }
    173 }
    174 
    175 // We want to map a chunk of address space aligned to 'alignment'.
    176 // We do it by maping a bit more and then unmaping redundant pieces.
    177 // We probably can do it with fewer syscalls in some OS-dependent way.
    178 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type) {
    179 // uptr PageSize = GetPageSizeCached();
    180   CHECK(IsPowerOfTwo(size));
    181   CHECK(IsPowerOfTwo(alignment));
    182   uptr map_size = size + alignment;
    183   uptr map_res = (uptr)MmapOrDie(map_size, mem_type);
    184   uptr map_end = map_res + map_size;
    185   uptr res = map_res;
    186   if (res & (alignment - 1))  // Not aligned.
    187     res = (map_res + alignment) & ~(alignment - 1);
    188   uptr end = res + size;
    189   if (res != map_res)
    190     UnmapOrDie((void*)map_res, res - map_res);
    191   if (end != map_end)
    192     UnmapOrDie((void*)end, map_end - end);
    193   return (void*)res;
    194 }
    195 
    196 void ReportErrorSummary(const char *error_type, const char *file,
    197                         int line, const char *function) {
    198   const int kMaxSize = 1024;  // We don't want a summary too long.
    199   InternalScopedBuffer<char> buff(kMaxSize);
    200   internal_snprintf(buff.data(), kMaxSize, "%s: %s %s:%d %s",
    201                     SanitizerToolName, error_type,
    202                     file ? file : "??", line, function ? function : "??");
    203   __sanitizer_report_error_summary(buff.data());
    204 }
    205 
    206 }  // namespace __sanitizer
    207 
    208 using namespace __sanitizer;  // NOLINT
    209 
    210 extern "C" {
    211 void __sanitizer_set_report_path(const char *path) {
    212   if (!path) return;
    213   uptr len = internal_strlen(path);
    214   if (len > sizeof(report_path_prefix) - 100) {
    215     Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
    216            path[0], path[1], path[2], path[3],
    217            path[4], path[5], path[6], path[7]);
    218     Die();
    219   }
    220   internal_strncpy(report_path_prefix, path, sizeof(report_path_prefix));
    221   report_path_prefix[len] = '\0';
    222   report_fd = kInvalidFd;
    223   log_to_file = true;
    224 }
    225 
    226 void __sanitizer_set_report_fd(int fd) {
    227   if (report_fd != kStdoutFd &&
    228       report_fd != kStderrFd &&
    229       report_fd != kInvalidFd)
    230     internal_close(report_fd);
    231   report_fd = fd;
    232 }
    233 
    234 void NOINLINE __sanitizer_sandbox_on_notify(void *reserved) {
    235   (void)reserved;
    236   PrepareForSandboxing();
    237 }
    238 
    239 void __sanitizer_report_error_summary(const char *error_summary) {
    240   Printf("SUMMARY: %s\n", error_summary);
    241 }
    242 }  // extern "C"
    243