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_allocator_interface.h"
14 #include "sanitizer_allocator_internal.h"
15 #include "sanitizer_atomic.h"
16 #include "sanitizer_flags.h"
17 #include "sanitizer_libc.h"
18 #include "sanitizer_placement_new.h"
19 
20 namespace __sanitizer {
21 
22 const char *SanitizerToolName = "SanitizerTool";
23 
24 atomic_uint32_t current_verbosity;
25 uptr PageSizeCached;
26 u32 NumberOfCPUsCached;
27 
28 // PID of the tracer task in StopTheWorld. It shares the address space with the
29 // main process, but has a different PID and thus requires special handling.
30 uptr stoptheworld_tracer_pid = 0;
31 // Cached pid of parent process - if the parent process dies, we want to keep
32 // writing to the same log file.
33 uptr stoptheworld_tracer_ppid = 0;
34 
ReportMmapFailureAndDie(uptr size,const char * mem_type,const char * mmap_type,error_t err,bool raw_report)35 void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
36                                       const char *mmap_type, error_t err,
37                                       bool raw_report) {
38   static int recursion_count;
39   if (SANITIZER_RTEMS || raw_report || recursion_count) {
40     // If we are on RTEMS or raw report is requested or we went into recursion,
41     // just die.  The Report() and CHECK calls below may call mmap recursively
42     // 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 
StripPathPrefix(const char * filepath,const char * strip_path_prefix)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 
StripModuleName(const char * module)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 
ReportErrorSummary(const char * error_message,const char * alt_tool_name)86 void ReportErrorSummary(const char *error_message, const char *alt_tool_name) {
87   if (!common_flags()->print_summary)
88     return;
89   InternalScopedString buff(kMaxSummaryLength);
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).
RemoveANSIEscapeSequencesFromString(char * str)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 
set(const char * module_name,uptr base_address)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 
set(const char * module_name,uptr base_address,ModuleArch arch,u8 uuid[kModuleUUIDSize],bool instrumented)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 
clear()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 
addAddressRange(uptr beg,uptr end,bool executable,bool writable,const char * name)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 
containsAddress(uptr address) const169 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 
IncreaseTotalMmap(uptr size)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 
DecreaseTotalMmap(uptr size)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 
TemplateMatch(const char * templ,const char * str)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 
GetProcessName()238 const char *GetProcessName() {
239   return process_name_cache_str;
240 }
241 
ReadProcessName(char * buf,uptr buf_len)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 
UpdateProcessName()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
CacheBinaryName()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 
ReadBinaryNameCached(char * buf,uptr buf_len)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 
PrintCmdline()276 void PrintCmdline() {
277   char **argv = GetArgv();
278   if (!argv) return;
279   Printf("\nCommand: ");
280   for (uptr i = 0; argv[i]; ++i)
281     Printf("%s ", argv[i]);
282   Printf("\n\n");
283 }
284 
285 // Malloc hooks.
286 static const int kMaxMallocFreeHooks = 5;
287 struct MallocFreeHook {
288   void (*malloc_hook)(const void *, uptr);
289   void (*free_hook)(const void *);
290 };
291 
292 static MallocFreeHook MFHooks[kMaxMallocFreeHooks];
293 
RunMallocHooks(const void * ptr,uptr size)294 void RunMallocHooks(const void *ptr, uptr size) {
295   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
296     auto hook = MFHooks[i].malloc_hook;
297     if (!hook) return;
298     hook(ptr, size);
299   }
300 }
301 
RunFreeHooks(const void * ptr)302 void RunFreeHooks(const void *ptr) {
303   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
304     auto hook = MFHooks[i].free_hook;
305     if (!hook) return;
306     hook(ptr);
307   }
308 }
309 
InstallMallocFreeHooks(void (* malloc_hook)(const void *,uptr),void (* free_hook)(const void *))310 static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
311                                   void (*free_hook)(const void *)) {
312   if (!malloc_hook || !free_hook) return 0;
313   for (int i = 0; i < kMaxMallocFreeHooks; i++) {
314     if (MFHooks[i].malloc_hook == nullptr) {
315       MFHooks[i].malloc_hook = malloc_hook;
316       MFHooks[i].free_hook = free_hook;
317       return i + 1;
318     }
319   }
320   return 0;
321 }
322 
323 } // namespace __sanitizer
324 
325 using namespace __sanitizer;  // NOLINT
326 
327 extern "C" {
SANITIZER_INTERFACE_WEAK_DEF(void,__sanitizer_report_error_summary,const char * error_summary)328 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary,
329                              const char *error_summary) {
330   Printf("%s\n", error_summary);
331 }
332 
333 SANITIZER_INTERFACE_ATTRIBUTE
__sanitizer_acquire_crash_state()334 int __sanitizer_acquire_crash_state() {
335   static atomic_uint8_t in_crash_state = {};
336   return !atomic_exchange(&in_crash_state, 1, memory_order_relaxed);
337 }
338 
339 SANITIZER_INTERFACE_ATTRIBUTE
__sanitizer_install_malloc_and_free_hooks(void (* malloc_hook)(const void *,uptr),void (* free_hook)(const void *))340 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const void *,
341                                                                   uptr),
342                                               void (*free_hook)(const void *)) {
343   return InstallMallocFreeHooks(malloc_hook, free_hook);
344 }
345 } // extern "C"
346