1 //===-- sanitizer_common.cpp ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common.h"
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"
23 namespace __sanitizer
{
25 const char *SanitizerToolName
= "SanitizerTool";
27 atomic_uint32_t current_verbosity
;
29 u32 NumberOfCPUsCached
;
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;
38 void NORETURN
ReportMmapFailureAndDie(uptr size
, const char *mem_type
,
39 const char *mmap_type
, error_t err
,
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");
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
);
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
);
61 UNREACHABLE("unable to mmap");
64 typedef bool UptrComparisonFunction(const uptr
&a
, const uptr
&b
);
65 typedef bool U32ComparisonFunction(const u32
&a
, const u32
&b
);
67 const char *StripPathPrefix(const char *filepath
,
68 const char *strip_path_prefix
) {
69 if (!filepath
) return nullptr;
70 if (!strip_path_prefix
) return filepath
;
71 const char *res
= filepath
;
72 if (const char *pos
= internal_strstr(filepath
, strip_path_prefix
))
73 res
= pos
+ internal_strlen(strip_path_prefix
);
74 if (res
[0] == '.' && res
[1] == '/')
79 const char *StripModuleName(const char *module
) {
82 if (SANITIZER_WINDOWS
) {
83 // On Windows, both slash and backslash are possible.
84 // Pick the one that goes last.
85 if (const char *bslash_pos
= internal_strrchr(module
, '\\'))
86 return StripModuleName(bslash_pos
+ 1);
88 if (const char *slash_pos
= internal_strrchr(module
, '/')) {
94 void ReportErrorSummary(const char *error_message
, const char *alt_tool_name
) {
95 if (!common_flags()->print_summary
)
97 InternalScopedString buff
;
98 buff
.append("SUMMARY: %s: %s",
99 alt_tool_name
? alt_tool_name
: SanitizerToolName
, error_message
);
100 __sanitizer_report_error_summary(buff
.data());
103 // Removes the ANSI escape sequences from the input string (in-place).
104 void RemoveANSIEscapeSequencesFromString(char *str
) {
108 // We are going to remove the escape sequences in place.
113 // Skip over ANSI escape sequences with pointer 's'.
114 if (*s
== '\033' && *(s
+ 1) == '[') {
115 s
= internal_strchrnul(s
, 'm');
122 // 's' now points at a character we want to keep. Copy over the buffer
123 // content if the escape sequence has been perviously skipped andadvance
128 // If we have not seen an escape sequence, just advance both pointers.
133 // Null terminate the string.
137 void LoadedModule::set(const char *module_name
, uptr base_address
) {
139 full_name_
= internal_strdup(module_name
);
140 base_address_
= base_address
;
143 void LoadedModule::set(const char *module_name
, uptr base_address
,
144 ModuleArch arch
, u8 uuid
[kModuleUUIDSize
],
146 set(module_name
, base_address
);
148 internal_memcpy(uuid_
, uuid
, sizeof(uuid_
));
149 uuid_size_
= kModuleUUIDSize
;
150 instrumented_
= instrumented
;
153 void LoadedModule::setUuid(const char *uuid
, uptr size
) {
154 if (size
> kModuleUUIDSize
)
155 size
= kModuleUUIDSize
;
156 internal_memcpy(uuid_
, uuid
, size
);
160 void LoadedModule::clear() {
161 InternalFree(full_name_
);
164 full_name_
= nullptr;
165 arch_
= kModuleArchUnknown
;
166 internal_memset(uuid_
, 0, kModuleUUIDSize
);
167 instrumented_
= false;
168 while (!ranges_
.empty()) {
169 AddressRange
*r
= ranges_
.front();
175 void LoadedModule::addAddressRange(uptr beg
, uptr end
, bool executable
,
176 bool writable
, const char *name
) {
177 void *mem
= InternalAlloc(sizeof(AddressRange
));
179 new(mem
) AddressRange(beg
, end
, executable
, writable
, name
);
180 ranges_
.push_back(r
);
181 max_address_
= Max(max_address_
, end
);
184 bool LoadedModule::containsAddress(uptr address
) const {
185 for (const AddressRange
&r
: ranges()) {
186 if (r
.beg
<= address
&& address
< r
.end
)
192 static atomic_uintptr_t g_total_mmaped
;
194 void IncreaseTotalMmap(uptr size
) {
195 if (!common_flags()->mmap_limit_mb
) return;
197 atomic_fetch_add(&g_total_mmaped
, size
, memory_order_relaxed
) + size
;
198 // Since for now mmap_limit_mb is not a user-facing flag, just kill
199 // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
200 RAW_CHECK((total_mmaped
>> 20) < common_flags()->mmap_limit_mb
);
203 void DecreaseTotalMmap(uptr size
) {
204 if (!common_flags()->mmap_limit_mb
) return;
205 atomic_fetch_sub(&g_total_mmaped
, size
, memory_order_relaxed
);
208 bool TemplateMatch(const char *templ
, const char *str
) {
209 if ((!str
) || str
[0] == 0)
212 if (templ
&& templ
[0] == '^') {
216 bool asterisk
= false;
217 while (templ
&& templ
[0]) {
218 if (templ
[0] == '*') {
225 return str
[0] == 0 || asterisk
;
228 char *tpos
= (char*)internal_strchr(templ
, '*');
229 char *tpos1
= (char*)internal_strchr(templ
, '$');
230 if ((!tpos
) || (tpos1
&& tpos1
< tpos
))
234 const char *str0
= str
;
235 const char *spos
= internal_strstr(str
, templ
);
236 str
= spos
+ internal_strlen(templ
);
239 tpos
[0] = tpos
== tpos1
? '$' : '*';
242 if (start
&& spos
!= str0
)
250 static char binary_name_cache_str
[kMaxPathLength
];
251 static char process_name_cache_str
[kMaxPathLength
];
253 const char *GetProcessName() {
254 return process_name_cache_str
;
257 static uptr
ReadProcessName(/*out*/ char *buf
, uptr buf_len
) {
258 ReadLongProcessName(buf
, buf_len
);
259 char *s
= const_cast<char *>(StripModuleName(buf
));
260 uptr len
= internal_strlen(s
);
262 internal_memmove(buf
, s
, len
);
268 void UpdateProcessName() {
269 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
272 // Call once to make sure that binary_name_cache_str is initialized
273 void CacheBinaryName() {
274 if (binary_name_cache_str
[0] != '\0')
276 ReadBinaryName(binary_name_cache_str
, sizeof(binary_name_cache_str
));
277 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
280 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
) {
282 uptr name_len
= internal_strlen(binary_name_cache_str
);
283 name_len
= (name_len
< buf_len
- 1) ? name_len
: buf_len
- 1;
286 internal_memcpy(buf
, binary_name_cache_str
, name_len
);
287 buf
[name_len
] = '\0';
291 uptr
ReadBinaryDir(/*out*/ char *buf
, uptr buf_len
) {
292 ReadBinaryNameCached(buf
, buf_len
);
293 const char *exec_name_pos
= StripModuleName(buf
);
294 uptr name_len
= exec_name_pos
- buf
;
295 buf
[name_len
] = '\0';
300 void PrintCmdline() {
301 char **argv
= GetArgv();
303 Printf("\nCommand: ");
304 for (uptr i
= 0; argv
[i
]; ++i
)
305 Printf("%s ", argv
[i
]);
311 static const int kMaxMallocFreeHooks
= 5;
312 struct MallocFreeHook
{
313 void (*malloc_hook
)(const void *, uptr
);
314 void (*free_hook
)(const void *);
317 static MallocFreeHook MFHooks
[kMaxMallocFreeHooks
];
319 void RunMallocHooks(void *ptr
, uptr size
) {
320 __sanitizer_malloc_hook(ptr
, size
);
321 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
322 auto hook
= MFHooks
[i
].malloc_hook
;
329 void RunFreeHooks(void *ptr
) {
330 __sanitizer_free_hook(ptr
);
331 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
332 auto hook
= MFHooks
[i
].free_hook
;
339 static int InstallMallocFreeHooks(void (*malloc_hook
)(const void *, uptr
),
340 void (*free_hook
)(const void *)) {
341 if (!malloc_hook
|| !free_hook
) return 0;
342 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
343 if (MFHooks
[i
].malloc_hook
== nullptr) {
344 MFHooks
[i
].malloc_hook
= malloc_hook
;
345 MFHooks
[i
].free_hook
= free_hook
;
352 void internal_sleep(unsigned seconds
) {
353 internal_usleep((u64
)seconds
* 1000 * 1000);
355 void SleepForSeconds(unsigned seconds
) {
356 internal_usleep((u64
)seconds
* 1000 * 1000);
358 void SleepForMillis(unsigned millis
) { internal_usleep((u64
)millis
* 1000); }
360 void WaitForDebugger(unsigned seconds
, const char *label
) {
362 Report("Sleeping for %u second(s) %s\n", seconds
, label
);
363 SleepForSeconds(seconds
);
367 } // namespace __sanitizer
369 using namespace __sanitizer
;
372 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary
,
373 const char *error_summary
) {
374 Printf("%s\n", error_summary
);
377 SANITIZER_INTERFACE_ATTRIBUTE
378 int __sanitizer_acquire_crash_state() {
379 static atomic_uint8_t in_crash_state
= {};
380 return !atomic_exchange(&in_crash_state
, 1, memory_order_relaxed
);
383 SANITIZER_INTERFACE_ATTRIBUTE
384 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook
)(const void *,
386 void (*free_hook
)(const void *)) {
387 return InstallMallocFreeHooks(malloc_hook
, free_hook
);
390 // Provide default (no-op) implementation of malloc hooks.
391 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook
, void *ptr
,
397 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook
, void *ptr
) {