]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_common.cc
Merge lld trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_common.cc
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_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"
22
23 namespace __sanitizer {
24
25 const char *SanitizerToolName = "SanitizerTool";
26
27 atomic_uint32_t current_verbosity;
28 uptr PageSizeCached;
29
30 StaticSpinMutex report_file_mu;
31 ReportFile report_file = {&report_file_mu, kStderrFd, "", "", 0};
32
33 void RawWrite(const char *buffer) {
34   report_file.Write(buffer, internal_strlen(buffer));
35 }
36
37 void ReportFile::ReopenIfNecessary() {
38   mu->CheckLocked();
39   if (fd == kStdoutFd || fd == kStderrFd) return;
40
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.
49     if (fd_pid == pid)
50       return;
51     else
52       CloseFile(fd);
53   }
54
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,
58                       exe_name, pid);
59   } else {
60     internal_snprintf(full_path, kMaxPathLength, "%s.%zu", path_prefix, pid);
61   }
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));
67     Die();
68   }
69   fd_pid = pid;
70 }
71
72 void ReportFile::SetReportPath(const char *path) {
73   if (!path)
74     return;
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]);
80     Die();
81   }
82
83   SpinMutexLock l(mu);
84   if (fd != kStdoutFd && fd != kStderrFd && fd != kInvalidFd)
85     CloseFile(fd);
86   fd = kInvalidFd;
87   if (internal_strcmp(path, "stdout") == 0) {
88     fd = kStdoutFd;
89   } else if (internal_strcmp(path, "stderr") == 0) {
90     fd = kStderrFd;
91   } else {
92     internal_snprintf(path_prefix, kMaxPathLength, "%s", path);
93   }
94 }
95
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;
102
103 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
104                                       const char *mmap_type, error_t err,
105                                       bool raw_report) {
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");
111     Die();
112   }
113   recursion_count++;
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);
117 #if !SANITIZER_GO
118   DumpProcessMap();
119 #endif
120   UNREACHABLE("unable to mmap");
121 }
122
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;
127   *buff = nullptr;
128   *buff_size = 0;
129   *read_len = 0;
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__);
136     *buff_size = size;
137     *read_len = 0;
138     // Read up to one page at a time.
139     bool reached_eof = false;
140     while (*read_len + PageSize <= size) {
141       uptr just_read;
142       if (!ReadFromFile(fd, *buff + *read_len, PageSize, &just_read, errno_p)) {
143         UnmapOrDie(*buff, *buff_size);
144         return false;
145       }
146       if (just_read == 0) {
147         reached_eof = true;
148         break;
149       }
150       *read_len += just_read;
151     }
152     CloseFile(fd);
153     if (reached_eof)  // We've read the whole file.
154       break;
155   }
156   return true;
157 }
158
159 typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
160 typedef bool U32ComparisonFunction(const u32 &a, const u32 &b);
161
162 template<class T>
163 static inline bool CompareLess(const T &a, const T &b) {
164   return a < b;
165 }
166
167 void SortArray(uptr *array, uptr size) {
168   InternalSort<uptr*, UptrComparisonFunction>(&array, size, CompareLess);
169 }
170
171 void SortArray(u32 *array, uptr size) {
172   InternalSort<u32*, U32ComparisonFunction>(&array, size, CompareLess);
173 }
174
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] == '/')
183     res += 2;
184   return res;
185 }
186
187 const char *StripModuleName(const char *module) {
188   if (!module)
189     return nullptr;
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);
195   }
196   if (const char *slash_pos = internal_strrchr(module, '/')) {
197     return slash_pos + 1;
198   }
199   return module;
200 }
201
202 void ReportErrorSummary(const char *error_message) {
203   if (!common_flags()->print_summary)
204     return;
205   InternalScopedString buff(kMaxSummaryLength);
206   buff.append("SUMMARY: %s: %s", SanitizerToolName, error_message);
207   __sanitizer_report_error_summary(buff.data());
208 }
209
210 #if !SANITIZER_GO
211 void ReportErrorSummary(const char *error_type, const AddressInfo &info) {
212   if (!common_flags()->print_summary)
213     return;
214   InternalScopedString buff(kMaxSummaryLength);
215   buff.append("%s ", error_type);
216   RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
217               common_flags()->strip_path_prefix);
218   ReportErrorSummary(buff.data());
219 }
220 #endif
221
222 // Removes the ANSI escape sequences from the input string (in-place).
223 void RemoveANSIEscapeSequencesFromString(char *str) {
224   if (!str)
225     return;
226
227   // We are going to remove the escape sequences in place.
228   char *s = str;
229   char *z = str;
230   while (*s != '\0') {
231     CHECK_GE(s, z);
232     // Skip over ANSI escape sequences with pointer 's'.
233     if (*s == '\033' && *(s + 1) == '[') {
234       s = internal_strchrnul(s, 'm');
235       if (*s == '\0') {
236         break;
237       }
238       s++;
239       continue;
240     }
241     // 's' now points at a character we want to keep. Copy over the buffer
242     // content if the escape sequence has been perviously skipped andadvance
243     // both pointers.
244     if (s != z)
245       *z = *s;
246
247     // If we have not seen an escape sequence, just advance both pointers.
248     z++;
249     s++;
250   }
251
252   // Null terminate the string.
253   *z = '\0';
254 }
255
256 void LoadedModule::set(const char *module_name, uptr base_address) {
257   clear();
258   full_name_ = internal_strdup(module_name);
259   base_address_ = base_address;
260 }
261
262 void LoadedModule::set(const char *module_name, uptr base_address,
263                        ModuleArch arch, u8 uuid[kModuleUUIDSize],
264                        bool instrumented) {
265   set(module_name, base_address);
266   arch_ = arch;
267   internal_memcpy(uuid_, uuid, sizeof(uuid_));
268   instrumented_ = instrumented;
269 }
270
271 void LoadedModule::clear() {
272   InternalFree(full_name_);
273   base_address_ = 0;
274   max_executable_address_ = 0;
275   full_name_ = nullptr;
276   arch_ = kModuleArchUnknown;
277   internal_memset(uuid_, 0, kModuleUUIDSize);
278   instrumented_ = false;
279   while (!ranges_.empty()) {
280     AddressRange *r = ranges_.front();
281     ranges_.pop_front();
282     InternalFree(r);
283   }
284 }
285
286 void LoadedModule::addAddressRange(uptr beg, uptr end, bool executable) {
287   void *mem = InternalAlloc(sizeof(AddressRange));
288   AddressRange *r = new(mem) AddressRange(beg, end, executable);
289   ranges_.push_back(r);
290   if (executable && end > max_executable_address_)
291     max_executable_address_ = end;
292 }
293
294 bool LoadedModule::containsAddress(uptr address) const {
295   for (const AddressRange &r : ranges()) {
296     if (r.beg <= address && address < r.end)
297       return true;
298   }
299   return false;
300 }
301
302 static atomic_uintptr_t g_total_mmaped;
303
304 void IncreaseTotalMmap(uptr size) {
305   if (!common_flags()->mmap_limit_mb) return;
306   uptr total_mmaped =
307       atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
308   // Since for now mmap_limit_mb is not a user-facing flag, just kill
309   // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
310   RAW_CHECK((total_mmaped >> 20) < common_flags()->mmap_limit_mb);
311 }
312
313 void DecreaseTotalMmap(uptr size) {
314   if (!common_flags()->mmap_limit_mb) return;
315   atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
316 }
317
318 bool TemplateMatch(const char *templ, const char *str) {
319   if ((!str) || str[0] == 0)
320     return false;
321   bool start = false;
322   if (templ && templ[0] == '^') {
323     start = true;
324     templ++;
325   }
326   bool asterisk = false;
327   while (templ && templ[0]) {
328     if (templ[0] == '*') {
329       templ++;
330       start = false;
331       asterisk = true;
332       continue;
333     }
334     if (templ[0] == '$')
335       return str[0] == 0 || asterisk;
336     if (str[0] == 0)
337       return false;
338     char *tpos = (char*)internal_strchr(templ, '*');
339     char *tpos1 = (char*)internal_strchr(templ, '$');
340     if ((!tpos) || (tpos1 && tpos1 < tpos))
341       tpos = tpos1;
342     if (tpos)
343       tpos[0] = 0;
344     const char *str0 = str;
345     const char *spos = internal_strstr(str, templ);
346     str = spos + internal_strlen(templ);
347     templ = tpos;
348     if (tpos)
349       tpos[0] = tpos == tpos1 ? '$' : '*';
350     if (!spos)
351       return false;
352     if (start && spos != str0)
353       return false;
354     start = false;
355     asterisk = false;
356   }
357   return true;
358 }
359
360 static const char kPathSeparator = SANITIZER_WINDOWS ? ';' : ':';
361
362 char *FindPathToBinary(const char *name) {
363   if (FileExists(name)) {
364     return internal_strdup(name);
365   }
366
367   const char *path = GetEnv("PATH");
368   if (!path)
369     return nullptr;
370   uptr name_len = internal_strlen(name);
371   InternalScopedBuffer<char> buffer(kMaxPathLength);
372   const char *beg = path;
373   while (true) {
374     const char *end = internal_strchrnul(beg, kPathSeparator);
375     uptr prefix_len = end - beg;
376     if (prefix_len + name_len + 2 <= kMaxPathLength) {
377       internal_memcpy(buffer.data(), beg, prefix_len);
378       buffer[prefix_len] = '/';
379       internal_memcpy(&buffer[prefix_len + 1], name, name_len);
380       buffer[prefix_len + 1 + name_len] = '\0';
381       if (FileExists(buffer.data()))
382         return internal_strdup(buffer.data());
383     }
384     if (*end == '\0') break;
385     beg = end + 1;
386   }
387   return nullptr;
388 }
389
390 static char binary_name_cache_str[kMaxPathLength];
391 static char process_name_cache_str[kMaxPathLength];
392
393 const char *GetProcessName() {
394   return process_name_cache_str;
395 }
396
397 static uptr ReadProcessName(/*out*/ char *buf, uptr buf_len) {
398   ReadLongProcessName(buf, buf_len);
399   char *s = const_cast<char *>(StripModuleName(buf));
400   uptr len = internal_strlen(s);
401   if (s != buf) {
402     internal_memmove(buf, s, len);
403     buf[len] = '\0';
404   }
405   return len;
406 }
407
408 void UpdateProcessName() {
409   ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
410 }
411
412 // Call once to make sure that binary_name_cache_str is initialized
413 void CacheBinaryName() {
414   if (binary_name_cache_str[0] != '\0')
415     return;
416   ReadBinaryName(binary_name_cache_str, sizeof(binary_name_cache_str));
417   ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
418 }
419
420 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len) {
421   CacheBinaryName();
422   uptr name_len = internal_strlen(binary_name_cache_str);
423   name_len = (name_len < buf_len - 1) ? name_len : buf_len - 1;
424   if (buf_len == 0)
425     return 0;
426   internal_memcpy(buf, binary_name_cache_str, name_len);
427   buf[name_len] = '\0';
428   return name_len;
429 }
430
431 void PrintCmdline() {
432   char **argv = GetArgv();
433   if (!argv) return;
434   Printf("\nCommand: ");
435   for (uptr i = 0; argv[i]; ++i)
436     Printf("%s ", argv[i]);
437   Printf("\n\n");
438 }
439
440 // Malloc hooks.
441 static const int kMaxMallocFreeHooks = 5;
442 struct MallocFreeHook {
443   void (*malloc_hook)(const void *, uptr);
444   void (*free_hook)(const void *);
445 };
446
447 static MallocFreeHook MFHooks[kMaxMallocFreeHooks];
448
449 void RunMallocHooks(const void *ptr, uptr size) {
450   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
451     auto hook = MFHooks[i].malloc_hook;
452     if (!hook) return;
453     hook(ptr, size);
454   }
455 }
456
457 void RunFreeHooks(const void *ptr) {
458   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
459     auto hook = MFHooks[i].free_hook;
460     if (!hook) return;
461     hook(ptr);
462   }
463 }
464
465 static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
466                                   void (*free_hook)(const void *)) {
467   if (!malloc_hook || !free_hook) return 0;
468   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
469     if (MFHooks[i].malloc_hook == nullptr) {
470       MFHooks[i].malloc_hook = malloc_hook;
471       MFHooks[i].free_hook = free_hook;
472       return i + 1;
473     }
474   }
475   return 0;
476 }
477
478 } // namespace __sanitizer
479
480 using namespace __sanitizer;  // NOLINT
481
482 extern "C" {
483 void __sanitizer_set_report_path(const char *path) {
484   report_file.SetReportPath(path);
485 }
486
487 void __sanitizer_set_report_fd(void *fd) {
488   report_file.fd = (fd_t)reinterpret_cast<uptr>(fd);
489   report_file.fd_pid = internal_getpid();
490 }
491
492 void __sanitizer_report_error_summary(const char *error_summary) {
493   Printf("%s\n", error_summary);
494 }
495
496 SANITIZER_INTERFACE_ATTRIBUTE
497 void __sanitizer_set_death_callback(void (*callback)(void)) {
498   SetUserDieCallback(callback);
499 }
500
501 SANITIZER_INTERFACE_ATTRIBUTE
502 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const void *,
503                                                                   uptr),
504                                               void (*free_hook)(const void *)) {
505   return InstallMallocFreeHooks(malloc_hook, free_hook);
506 }
507
508 #if !SANITIZER_GO && !SANITIZER_SUPPORTS_WEAK_HOOKS
509 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
510 void __sanitizer_print_memory_profile(int top_percent) {
511   (void)top_percent;
512 }
513 #endif
514 } // extern "C"