1 //===-- sanitizer_common.cc -----------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries.
10 //===----------------------------------------------------------------------===//
11 
12 #include "sanitizer_common.h"
13 #include "sanitizer_flags.h"
14 #include "sanitizer_libc.h"
15 #include "sanitizer_stacktrace.h"
16 #include "sanitizer_symbolizer.h"
17 
18 namespace __sanitizer {
19 
20 const char *SanitizerToolName = "SanitizerTool";
21 
GetPageSizeCached()22 uptr GetPageSizeCached() {
23   static uptr PageSize;
24   if (!PageSize)
25     PageSize = GetPageSize();
26   return PageSize;
27 }
28 
29 
30 // By default, dump to stderr. If |log_to_file| is true and |report_fd_pid|
31 // isn't equal to the current PID, try to obtain file descriptor by opening
32 // file "report_path_prefix.<PID>".
33 fd_t report_fd = kStderrFd;
34 
35 // Set via __sanitizer_set_report_path.
36 bool log_to_file = false;
37 char report_path_prefix[sizeof(report_path_prefix)];
38 
39 // PID of process that opened |report_fd|. If a fork() occurs, the PID of the
40 // child thread will be different from |report_fd_pid|.
41 uptr report_fd_pid = 0;
42 
43 // PID of the tracer task in StopTheWorld. It shares the address space with the
44 // main process, but has a different PID and thus requires special handling.
45 uptr stoptheworld_tracer_pid = 0;
46 // Cached pid of parent process - if the parent process dies, we want to keep
47 // writing to the same log file.
48 uptr stoptheworld_tracer_ppid = 0;
49 
50 static DieCallbackType DieCallback;
SetDieCallback(DieCallbackType callback)51 void SetDieCallback(DieCallbackType callback) {
52   DieCallback = callback;
53 }
54 
GetDieCallback()55 DieCallbackType GetDieCallback() {
56   return DieCallback;
57 }
58 
Die()59 void NORETURN Die() {
60   if (DieCallback) {
61     DieCallback();
62   }
63   internal__exit(1);
64 }
65 
66 static CheckFailedCallbackType CheckFailedCallback;
SetCheckFailedCallback(CheckFailedCallbackType callback)67 void SetCheckFailedCallback(CheckFailedCallbackType callback) {
68   CheckFailedCallback = callback;
69 }
70 
CheckFailed(const char * file,int line,const char * cond,u64 v1,u64 v2)71 void NORETURN CheckFailed(const char *file, int line, const char *cond,
72                           u64 v1, u64 v2) {
73   if (CheckFailedCallback) {
74     CheckFailedCallback(file, line, cond, v1, v2);
75   }
76   Report("Sanitizer CHECK failed: %s:%d %s (%lld, %lld)\n", file, line, cond,
77                                                             v1, v2);
78   Die();
79 }
80 
ReadFileToBuffer(const char * file_name,char ** buff,uptr * buff_size,uptr max_len)81 uptr ReadFileToBuffer(const char *file_name, char **buff,
82                       uptr *buff_size, uptr max_len) {
83   uptr PageSize = GetPageSizeCached();
84   uptr kMinFileLen = PageSize;
85   uptr read_len = 0;
86   *buff = 0;
87   *buff_size = 0;
88   // The files we usually open are not seekable, so try different buffer sizes.
89   for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
90     uptr openrv = OpenFile(file_name, /*write*/ false);
91     if (internal_iserror(openrv)) return 0;
92     fd_t fd = openrv;
93     UnmapOrDie(*buff, *buff_size);
94     *buff = (char*)MmapOrDie(size, __FUNCTION__);
95     *buff_size = size;
96     // Read up to one page at a time.
97     read_len = 0;
98     bool reached_eof = false;
99     while (read_len + PageSize <= size) {
100       uptr just_read = internal_read(fd, *buff + read_len, PageSize);
101       if (just_read == 0) {
102         reached_eof = true;
103         break;
104       }
105       read_len += just_read;
106     }
107     internal_close(fd);
108     if (reached_eof)  // We've read the whole file.
109       break;
110   }
111   return read_len;
112 }
113 
114 typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
115 
116 template<class T>
CompareLess(const T & a,const T & b)117 static inline bool CompareLess(const T &a, const T &b) {
118   return a < b;
119 }
120 
SortArray(uptr * array,uptr size)121 void SortArray(uptr *array, uptr size) {
122   InternalSort<uptr*, UptrComparisonFunction>(&array, size, CompareLess);
123 }
124 
125 // We want to map a chunk of address space aligned to 'alignment'.
126 // We do it by maping a bit more and then unmaping redundant pieces.
127 // We probably can do it with fewer syscalls in some OS-dependent way.
MmapAlignedOrDie(uptr size,uptr alignment,const char * mem_type)128 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type) {
129 // uptr PageSize = GetPageSizeCached();
130   CHECK(IsPowerOfTwo(size));
131   CHECK(IsPowerOfTwo(alignment));
132   uptr map_size = size + alignment;
133   uptr map_res = (uptr)MmapOrDie(map_size, mem_type);
134   uptr map_end = map_res + map_size;
135   uptr res = map_res;
136   if (res & (alignment - 1))  // Not aligned.
137     res = (map_res + alignment) & ~(alignment - 1);
138   uptr end = res + size;
139   if (res != map_res)
140     UnmapOrDie((void*)map_res, res - map_res);
141   if (end != map_end)
142     UnmapOrDie((void*)end, map_end - end);
143   return (void*)res;
144 }
145 
StripPathPrefix(const char * filepath,const char * strip_path_prefix)146 const char *StripPathPrefix(const char *filepath,
147                             const char *strip_path_prefix) {
148   if (filepath == 0) return 0;
149   if (strip_path_prefix == 0) return filepath;
150   const char *pos = internal_strstr(filepath, strip_path_prefix);
151   if (pos == 0) return filepath;
152   pos += internal_strlen(strip_path_prefix);
153   if (pos[0] == '.' && pos[1] == '/')
154     pos += 2;
155   return pos;
156 }
157 
PrintSourceLocation(InternalScopedString * buffer,const char * file,int line,int column)158 void PrintSourceLocation(InternalScopedString *buffer, const char *file,
159                          int line, int column) {
160   CHECK(file);
161   buffer->append("%s",
162                  StripPathPrefix(file, common_flags()->strip_path_prefix));
163   if (line > 0) {
164     buffer->append(":%d", line);
165     if (column > 0)
166       buffer->append(":%d", column);
167   }
168 }
169 
PrintModuleAndOffset(InternalScopedString * buffer,const char * module,uptr offset)170 void PrintModuleAndOffset(InternalScopedString *buffer, const char *module,
171                           uptr offset) {
172   buffer->append("(%s+0x%zx)",
173                  StripPathPrefix(module, common_flags()->strip_path_prefix),
174                  offset);
175 }
176 
ReportErrorSummary(const char * error_message)177 void ReportErrorSummary(const char *error_message) {
178   if (!common_flags()->print_summary)
179     return;
180   InternalScopedBuffer<char> buff(kMaxSummaryLength);
181   internal_snprintf(buff.data(), buff.size(),
182                     "SUMMARY: %s: %s", SanitizerToolName, error_message);
183   __sanitizer_report_error_summary(buff.data());
184 }
185 
ReportErrorSummary(const char * error_type,const char * file,int line,const char * function)186 void ReportErrorSummary(const char *error_type, const char *file,
187                         int line, const char *function) {
188   if (!common_flags()->print_summary)
189     return;
190   InternalScopedBuffer<char> buff(kMaxSummaryLength);
191   internal_snprintf(
192       buff.data(), buff.size(), "%s %s:%d %s", error_type,
193       file ? StripPathPrefix(file, common_flags()->strip_path_prefix) : "??",
194       line, function ? function : "??");
195   ReportErrorSummary(buff.data());
196 }
197 
ReportErrorSummary(const char * error_type,StackTrace * stack)198 void ReportErrorSummary(const char *error_type, StackTrace *stack) {
199   if (!common_flags()->print_summary)
200     return;
201   AddressInfo ai;
202 #if !SANITIZER_GO
203   if (stack->size > 0 && Symbolizer::Get()->IsAvailable()) {
204     // Currently, we include the first stack frame into the report summary.
205     // Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
206     uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
207     Symbolizer::Get()->SymbolizeCode(pc, &ai, 1);
208   }
209 #endif
210   ReportErrorSummary(error_type, ai.file, ai.line, ai.function);
211 }
212 
LoadedModule(const char * module_name,uptr base_address)213 LoadedModule::LoadedModule(const char *module_name, uptr base_address) {
214   full_name_ = internal_strdup(module_name);
215   base_address_ = base_address;
216   n_ranges_ = 0;
217 }
218 
addAddressRange(uptr beg,uptr end)219 void LoadedModule::addAddressRange(uptr beg, uptr end) {
220   CHECK_LT(n_ranges_, kMaxNumberOfAddressRanges);
221   ranges_[n_ranges_].beg = beg;
222   ranges_[n_ranges_].end = end;
223   n_ranges_++;
224 }
225 
containsAddress(uptr address) const226 bool LoadedModule::containsAddress(uptr address) const {
227   for (uptr i = 0; i < n_ranges_; i++) {
228     if (ranges_[i].beg <= address && address < ranges_[i].end)
229       return true;
230   }
231   return false;
232 }
233 
StripModuleName(const char * module)234 char *StripModuleName(const char *module) {
235   if (module == 0)
236     return 0;
237   const char *short_module_name = internal_strrchr(module, '/');
238   if (short_module_name)
239     short_module_name += 1;
240   else
241     short_module_name = module;
242   return internal_strdup(short_module_name);
243 }
244 
245 }  // namespace __sanitizer
246 
247 using namespace __sanitizer;  // NOLINT
248 
249 extern "C" {
__sanitizer_set_report_path(const char * path)250 void __sanitizer_set_report_path(const char *path) {
251   if (!path)
252     return;
253   uptr len = internal_strlen(path);
254   if (len > sizeof(report_path_prefix) - 100) {
255     Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
256            path[0], path[1], path[2], path[3],
257            path[4], path[5], path[6], path[7]);
258     Die();
259   }
260   if (report_fd != kStdoutFd &&
261       report_fd != kStderrFd &&
262       report_fd != kInvalidFd)
263     internal_close(report_fd);
264   report_fd = kInvalidFd;
265   log_to_file = false;
266   if (internal_strcmp(path, "stdout") == 0) {
267     report_fd = kStdoutFd;
268   } else if (internal_strcmp(path, "stderr") == 0) {
269     report_fd = kStderrFd;
270   } else {
271     internal_strncpy(report_path_prefix, path, sizeof(report_path_prefix));
272     report_path_prefix[len] = '\0';
273     log_to_file = true;
274   }
275 }
276 
__sanitizer_sandbox_on_notify(void * reserved)277 void NOINLINE __sanitizer_sandbox_on_notify(void *reserved) {
278   (void)reserved;
279   PrepareForSandboxing();
280 }
281 
__sanitizer_report_error_summary(const char * error_summary)282 void __sanitizer_report_error_summary(const char *error_summary) {
283   Printf("%s\n", error_summary);
284 }
285 }  // extern "C"
286