xref: /freebsd/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 //===-- sanitizer_common.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries.
11 //===----------------------------------------------------------------------===//
12 
13 #include "sanitizer_common.h"
14 
15 #include "sanitizer_allocator_interface.h"
16 #include "sanitizer_allocator_internal.h"
17 #include "sanitizer_atomic.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_interface_internal.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_placement_new.h"
22 
23 namespace __sanitizer {
24 
25 const char *SanitizerToolName = "SanitizerTool";
26 
27 atomic_uint32_t current_verbosity;
28 uptr PageSizeCached;
29 u32 NumberOfCPUsCached;
30 
31 // PID of the tracer task in StopTheWorld. It shares the address space with the
32 // main process, but has a different PID and thus requires special handling.
33 uptr stoptheworld_tracer_pid = 0;
34 // Cached pid of parent process - if the parent process dies, we want to keep
35 // writing to the same log file.
36 uptr stoptheworld_tracer_ppid = 0;
37 
38 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
39                                       const char *mmap_type, error_t err,
40                                       bool raw_report) {
41   static int recursion_count;
42   if (raw_report || recursion_count) {
43     // If raw report is requested or we went into recursion just die.  The
44     // Report() and CHECK calls below may call mmap recursively and fail.
45     RawWrite("ERROR: Failed to mmap\n");
46     Die();
47   }
48   recursion_count++;
49   if (ErrorIsOOM(err)) {
50     ERROR_OOM("failed to %s 0x%zx (%zd) bytes of %s (error code: %d)\n",
51               mmap_type, size, size, mem_type, err);
52   } else {
53     Report(
54         "ERROR: %s failed to "
55         "%s 0x%zx (%zd) bytes of %s (error code: %d)\n",
56         SanitizerToolName, mmap_type, size, size, mem_type, err);
57   }
58 #if !SANITIZER_GO
59   DumpProcessMap();
60 #endif
61   UNREACHABLE("unable to mmap");
62 }
63 
64 void NORETURN ReportMunmapFailureAndDie(void *addr, uptr size, error_t err,
65                                         bool raw_report) {
66   static int recursion_count;
67   if (raw_report || recursion_count) {
68     // If raw report is requested or we went into recursion just die.  The
69     // Report() and CHECK calls below may call munmap recursively and fail.
70     RawWrite("ERROR: Failed to munmap\n");
71     Die();
72   }
73   recursion_count++;
74   Report(
75       "ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p (error "
76       "code: %d)\n",
77       SanitizerToolName, size, size, addr, err);
78 #if !SANITIZER_GO
79   DumpProcessMap();
80 #endif
81   UNREACHABLE("unable to unmmap");
82 }
83 
84 typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
85 typedef bool U32ComparisonFunction(const u32 &a, const u32 &b);
86 
87 const char *StripPathPrefix(const char *filepath,
88                             const char *strip_path_prefix) {
89   if (!filepath) return nullptr;
90   if (!strip_path_prefix) return filepath;
91   const char *res = filepath;
92   if (const char *pos = internal_strstr(filepath, strip_path_prefix))
93     res = pos + internal_strlen(strip_path_prefix);
94   if (res[0] == '.' && res[1] == '/')
95     res += 2;
96   return res;
97 }
98 
99 const char *StripModuleName(const char *module) {
100   if (!module)
101     return nullptr;
102   if (SANITIZER_WINDOWS) {
103     // On Windows, both slash and backslash are possible.
104     // Pick the one that goes last.
105     if (const char *bslash_pos = internal_strrchr(module, '\\'))
106       return StripModuleName(bslash_pos + 1);
107   }
108   if (const char *slash_pos = internal_strrchr(module, '/')) {
109     return slash_pos + 1;
110   }
111   return module;
112 }
113 
114 void ReportErrorSummary(const char *error_message, const char *alt_tool_name) {
115   if (!common_flags()->print_summary)
116     return;
117   InternalScopedString buff;
118   buff.append("SUMMARY: %s: %s",
119               alt_tool_name ? alt_tool_name : SanitizerToolName, error_message);
120   __sanitizer_report_error_summary(buff.data());
121 }
122 
123 // Removes the ANSI escape sequences from the input string (in-place).
124 void RemoveANSIEscapeSequencesFromString(char *str) {
125   if (!str)
126     return;
127 
128   // We are going to remove the escape sequences in place.
129   char *s = str;
130   char *z = str;
131   while (*s != '\0') {
132     CHECK_GE(s, z);
133     // Skip over ANSI escape sequences with pointer 's'.
134     if (*s == '\033' && *(s + 1) == '[') {
135       s = internal_strchrnul(s, 'm');
136       if (*s == '\0') {
137         break;
138       }
139       s++;
140       continue;
141     }
142     // 's' now points at a character we want to keep. Copy over the buffer
143     // content if the escape sequence has been perviously skipped andadvance
144     // both pointers.
145     if (s != z)
146       *z = *s;
147 
148     // If we have not seen an escape sequence, just advance both pointers.
149     z++;
150     s++;
151   }
152 
153   // Null terminate the string.
154   *z = '\0';
155 }
156 
157 void LoadedModule::set(const char *module_name, uptr base_address) {
158   clear();
159   full_name_ = internal_strdup(module_name);
160   base_address_ = base_address;
161 }
162 
163 void LoadedModule::set(const char *module_name, uptr base_address,
164                        ModuleArch arch, u8 uuid[kModuleUUIDSize],
165                        bool instrumented) {
166   set(module_name, base_address);
167   arch_ = arch;
168   internal_memcpy(uuid_, uuid, sizeof(uuid_));
169   uuid_size_ = kModuleUUIDSize;
170   instrumented_ = instrumented;
171 }
172 
173 void LoadedModule::setUuid(const char *uuid, uptr size) {
174   if (size > kModuleUUIDSize)
175     size = kModuleUUIDSize;
176   internal_memcpy(uuid_, uuid, size);
177   uuid_size_ = size;
178 }
179 
180 void LoadedModule::clear() {
181   InternalFree(full_name_);
182   base_address_ = 0;
183   max_address_ = 0;
184   full_name_ = nullptr;
185   arch_ = kModuleArchUnknown;
186   internal_memset(uuid_, 0, kModuleUUIDSize);
187   instrumented_ = false;
188   while (!ranges_.empty()) {
189     AddressRange *r = ranges_.front();
190     ranges_.pop_front();
191     InternalFree(r);
192   }
193 }
194 
195 void LoadedModule::addAddressRange(uptr beg, uptr end, bool executable,
196                                    bool writable, const char *name) {
197   void *mem = InternalAlloc(sizeof(AddressRange));
198   AddressRange *r =
199       new(mem) AddressRange(beg, end, executable, writable, name);
200   ranges_.push_back(r);
201   max_address_ = Max(max_address_, end);
202 }
203 
204 bool LoadedModule::containsAddress(uptr address) const {
205   for (const AddressRange &r : ranges()) {
206     if (r.beg <= address && address < r.end)
207       return true;
208   }
209   return false;
210 }
211 
212 static atomic_uintptr_t g_total_mmaped;
213 
214 void IncreaseTotalMmap(uptr size) {
215   if (!common_flags()->mmap_limit_mb) return;
216   uptr total_mmaped =
217       atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
218   // Since for now mmap_limit_mb is not a user-facing flag, just kill
219   // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
220   RAW_CHECK((total_mmaped >> 20) < common_flags()->mmap_limit_mb);
221 }
222 
223 void DecreaseTotalMmap(uptr size) {
224   if (!common_flags()->mmap_limit_mb) return;
225   atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
226 }
227 
228 bool TemplateMatch(const char *templ, const char *str) {
229   if ((!str) || str[0] == 0)
230     return false;
231   bool start = false;
232   if (templ && templ[0] == '^') {
233     start = true;
234     templ++;
235   }
236   bool asterisk = false;
237   while (templ && templ[0]) {
238     if (templ[0] == '*') {
239       templ++;
240       start = false;
241       asterisk = true;
242       continue;
243     }
244     if (templ[0] == '$')
245       return str[0] == 0 || asterisk;
246     if (str[0] == 0)
247       return false;
248     char *tpos = (char*)internal_strchr(templ, '*');
249     char *tpos1 = (char*)internal_strchr(templ, '$');
250     if ((!tpos) || (tpos1 && tpos1 < tpos))
251       tpos = tpos1;
252     if (tpos)
253       tpos[0] = 0;
254     const char *str0 = str;
255     const char *spos = internal_strstr(str, templ);
256     str = spos + internal_strlen(templ);
257     templ = tpos;
258     if (tpos)
259       tpos[0] = tpos == tpos1 ? '$' : '*';
260     if (!spos)
261       return false;
262     if (start && spos != str0)
263       return false;
264     start = false;
265     asterisk = false;
266   }
267   return true;
268 }
269 
270 static char binary_name_cache_str[kMaxPathLength];
271 static char process_name_cache_str[kMaxPathLength];
272 
273 const char *GetProcessName() {
274   return process_name_cache_str;
275 }
276 
277 static uptr ReadProcessName(/*out*/ char *buf, uptr buf_len) {
278   ReadLongProcessName(buf, buf_len);
279   char *s = const_cast<char *>(StripModuleName(buf));
280   uptr len = internal_strlen(s);
281   if (s != buf) {
282     internal_memmove(buf, s, len);
283     buf[len] = '\0';
284   }
285   return len;
286 }
287 
288 void UpdateProcessName() {
289   ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
290 }
291 
292 // Call once to make sure that binary_name_cache_str is initialized
293 void CacheBinaryName() {
294   if (binary_name_cache_str[0] != '\0')
295     return;
296   ReadBinaryName(binary_name_cache_str, sizeof(binary_name_cache_str));
297   ReadProcessName(process_name_cache_str, sizeof(process_name_cache_str));
298 }
299 
300 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len) {
301   CacheBinaryName();
302   uptr name_len = internal_strlen(binary_name_cache_str);
303   name_len = (name_len < buf_len - 1) ? name_len : buf_len - 1;
304   if (buf_len == 0)
305     return 0;
306   internal_memcpy(buf, binary_name_cache_str, name_len);
307   buf[name_len] = '\0';
308   return name_len;
309 }
310 
311 uptr ReadBinaryDir(/*out*/ char *buf, uptr buf_len) {
312   ReadBinaryNameCached(buf, buf_len);
313   const char *exec_name_pos = StripModuleName(buf);
314   uptr name_len = exec_name_pos - buf;
315   buf[name_len] = '\0';
316   return name_len;
317 }
318 
319 #if !SANITIZER_GO
320 void PrintCmdline() {
321   char **argv = GetArgv();
322   if (!argv) return;
323   Printf("\nCommand: ");
324   for (uptr i = 0; argv[i]; ++i)
325     Printf("%s ", argv[i]);
326   Printf("\n\n");
327 }
328 #endif
329 
330 // Malloc hooks.
331 static const int kMaxMallocFreeHooks = 5;
332 struct MallocFreeHook {
333   void (*malloc_hook)(const void *, uptr);
334   void (*free_hook)(const void *);
335 };
336 
337 static MallocFreeHook MFHooks[kMaxMallocFreeHooks];
338 
339 void RunMallocHooks(void *ptr, uptr size) {
340   __sanitizer_malloc_hook(ptr, size);
341   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
342     auto hook = MFHooks[i].malloc_hook;
343     if (!hook)
344       break;
345     hook(ptr, size);
346   }
347 }
348 
349 void RunFreeHooks(void *ptr) {
350   __sanitizer_free_hook(ptr);
351   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
352     auto hook = MFHooks[i].free_hook;
353     if (!hook)
354       break;
355     hook(ptr);
356   }
357 }
358 
359 static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
360                                   void (*free_hook)(const void *)) {
361   if (!malloc_hook || !free_hook) return 0;
362   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
363     if (MFHooks[i].malloc_hook == nullptr) {
364       MFHooks[i].malloc_hook = malloc_hook;
365       MFHooks[i].free_hook = free_hook;
366       return i + 1;
367     }
368   }
369   return 0;
370 }
371 
372 void internal_sleep(unsigned seconds) {
373   internal_usleep((u64)seconds * 1000 * 1000);
374 }
375 void SleepForSeconds(unsigned seconds) {
376   internal_usleep((u64)seconds * 1000 * 1000);
377 }
378 void SleepForMillis(unsigned millis) { internal_usleep((u64)millis * 1000); }
379 
380 void WaitForDebugger(unsigned seconds, const char *label) {
381   if (seconds) {
382     Report("Sleeping for %u second(s) %s\n", seconds, label);
383     SleepForSeconds(seconds);
384   }
385 }
386 
387 } // namespace __sanitizer
388 
389 using namespace __sanitizer;
390 
391 extern "C" {
392 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary,
393                              const char *error_summary) {
394   Printf("%s\n", error_summary);
395 }
396 
397 SANITIZER_INTERFACE_ATTRIBUTE
398 int __sanitizer_acquire_crash_state() {
399   static atomic_uint8_t in_crash_state = {};
400   return !atomic_exchange(&in_crash_state, 1, memory_order_relaxed);
401 }
402 
403 SANITIZER_INTERFACE_ATTRIBUTE
404 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const void *,
405                                                                   uptr),
406                                               void (*free_hook)(const void *)) {
407   return InstallMallocFreeHooks(malloc_hook, free_hook);
408 }
409 
410 // Provide default (no-op) implementation of malloc hooks.
411 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr,
412                              uptr size) {
413   (void)ptr;
414   (void)size;
415 }
416 
417 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
418   (void)ptr;
419 }
420 
421 } // extern "C"
422