1 //===-- sanitizer_common.cc -----------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
10 //===----------------------------------------------------------------------===//
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"
20 namespace __sanitizer
{
22 const char *SanitizerToolName
= "SanitizerTool";
24 atomic_uint32_t current_verbosity
;
26 u32 NumberOfCPUsCached
;
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;
35 void NORETURN
ReportMmapFailureAndDie(uptr size
, const char *mem_type
,
36 const char *mmap_type
, error_t err
,
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
43 RawWrite("ERROR: Failed to mmap\n");
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
);
53 UNREACHABLE("unable to mmap");
56 typedef bool UptrComparisonFunction(const uptr
&a
, const uptr
&b
);
57 typedef bool U32ComparisonFunction(const u32
&a
, const u32
&b
);
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] == '/')
71 const char *StripModuleName(const char *module
) {
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);
80 if (const char *slash_pos
= internal_strrchr(module
, '/')) {
86 void ReportErrorSummary(const char *error_message
, const char *alt_tool_name
) {
87 if (!common_flags()->print_summary
)
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());
95 // Removes the ANSI escape sequences from the input string (in-place).
96 void RemoveANSIEscapeSequencesFromString(char *str
) {
100 // We are going to remove the escape sequences in place.
105 // Skip over ANSI escape sequences with pointer 's'.
106 if (*s
== '\033' && *(s
+ 1) == '[') {
107 s
= internal_strchrnul(s
, 'm');
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
120 // If we have not seen an escape sequence, just advance both pointers.
125 // Null terminate the string.
129 void LoadedModule::set(const char *module_name
, uptr base_address
) {
131 full_name_
= internal_strdup(module_name
);
132 base_address_
= base_address
;
135 void LoadedModule::set(const char *module_name
, uptr base_address
,
136 ModuleArch arch
, u8 uuid
[kModuleUUIDSize
],
138 set(module_name
, base_address
);
140 internal_memcpy(uuid_
, uuid
, sizeof(uuid_
));
141 instrumented_
= instrumented
;
144 void LoadedModule::clear() {
145 InternalFree(full_name_
);
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();
159 void LoadedModule::addAddressRange(uptr beg
, uptr end
, bool executable
,
160 bool writable
, const char *name
) {
161 void *mem
= InternalAlloc(sizeof(AddressRange
));
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
;
169 bool LoadedModule::containsAddress(uptr address
) const {
170 for (const AddressRange
&r
: ranges()) {
171 if (r
.beg
<= address
&& address
< r
.end
)
177 static atomic_uintptr_t g_total_mmaped
;
179 void IncreaseTotalMmap(uptr size
) {
180 if (!common_flags()->mmap_limit_mb
) return;
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
);
188 void DecreaseTotalMmap(uptr size
) {
189 if (!common_flags()->mmap_limit_mb
) return;
190 atomic_fetch_sub(&g_total_mmaped
, size
, memory_order_relaxed
);
193 bool TemplateMatch(const char *templ
, const char *str
) {
194 if ((!str
) || str
[0] == 0)
197 if (templ
&& templ
[0] == '^') {
201 bool asterisk
= false;
202 while (templ
&& templ
[0]) {
203 if (templ
[0] == '*') {
210 return str
[0] == 0 || asterisk
;
213 char *tpos
= (char*)internal_strchr(templ
, '*');
214 char *tpos1
= (char*)internal_strchr(templ
, '$');
215 if ((!tpos
) || (tpos1
&& tpos1
< tpos
))
219 const char *str0
= str
;
220 const char *spos
= internal_strstr(str
, templ
);
221 str
= spos
+ internal_strlen(templ
);
224 tpos
[0] = tpos
== tpos1
? '$' : '*';
227 if (start
&& spos
!= str0
)
235 static char binary_name_cache_str
[kMaxPathLength
];
236 static char process_name_cache_str
[kMaxPathLength
];
238 const char *GetProcessName() {
239 return process_name_cache_str
;
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
);
247 internal_memmove(buf
, s
, len
);
253 void UpdateProcessName() {
254 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
257 // Call once to make sure that binary_name_cache_str is initialized
258 void CacheBinaryName() {
259 if (binary_name_cache_str
[0] != '\0')
261 ReadBinaryName(binary_name_cache_str
, sizeof(binary_name_cache_str
));
262 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
265 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
) {
267 uptr name_len
= internal_strlen(binary_name_cache_str
);
268 name_len
= (name_len
< buf_len
- 1) ? name_len
: buf_len
- 1;
271 internal_memcpy(buf
, binary_name_cache_str
, name_len
);
272 buf
[name_len
] = '\0';
276 void PrintCmdline() {
277 char **argv
= GetArgv();
279 Printf("\nCommand: ");
280 for (uptr i
= 0; argv
[i
]; ++i
)
281 Printf("%s ", argv
[i
]);
286 static const int kMaxMallocFreeHooks
= 5;
287 struct MallocFreeHook
{
288 void (*malloc_hook
)(const void *, uptr
);
289 void (*free_hook
)(const void *);
292 static MallocFreeHook MFHooks
[kMaxMallocFreeHooks
];
294 void RunMallocHooks(const void *ptr
, uptr size
) {
295 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
296 auto hook
= MFHooks
[i
].malloc_hook
;
302 void RunFreeHooks(const void *ptr
) {
303 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
304 auto hook
= MFHooks
[i
].free_hook
;
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
;
323 } // namespace __sanitizer
325 using namespace __sanitizer
; // NOLINT
328 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary
,
329 const char *error_summary
) {
330 Printf("%s\n", error_summary
);
333 SANITIZER_INTERFACE_ATTRIBUTE
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
);
339 SANITIZER_INTERFACE_ATTRIBUTE
340 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook
)(const void *,
342 void (*free_hook
)(const void *)) {
343 return InstallMallocFreeHooks(malloc_hook
, free_hook
);