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