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 void NORETURN
ReportMunmapFailureAndDie(void *addr
, uptr size
, error_t err
,
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");
75 "ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p (error "
77 SanitizerToolName
, size
, size
, addr
, err
);
81 UNREACHABLE("unable to unmmap");
84 typedef bool UptrComparisonFunction(const uptr
&a
, const uptr
&b
);
85 typedef bool U32ComparisonFunction(const u32
&a
, const u32
&b
);
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] == '/')
99 const char *StripModuleName(const char *module
) {
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);
108 if (const char *slash_pos
= internal_strrchr(module
, '/')) {
109 return slash_pos
+ 1;
114 void ReportErrorSummary(const char *error_message
, const char *alt_tool_name
) {
115 if (!common_flags()->print_summary
)
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());
123 // Removes the ANSI escape sequences from the input string (in-place).
124 void RemoveANSIEscapeSequencesFromString(char *str
) {
128 // We are going to remove the escape sequences in place.
133 // Skip over ANSI escape sequences with pointer 's'.
134 if (*s
== '\033' && *(s
+ 1) == '[') {
135 s
= internal_strchrnul(s
, 'm');
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
148 // If we have not seen an escape sequence, just advance both pointers.
153 // Null terminate the string.
157 void LoadedModule::set(const char *module_name
, uptr base_address
) {
159 full_name_
= internal_strdup(module_name
);
160 base_address_
= base_address
;
163 void LoadedModule::set(const char *module_name
, uptr base_address
,
164 ModuleArch arch
, u8 uuid
[kModuleUUIDSize
],
166 set(module_name
, base_address
);
168 internal_memcpy(uuid_
, uuid
, sizeof(uuid_
));
169 uuid_size_
= kModuleUUIDSize
;
170 instrumented_
= instrumented
;
173 void LoadedModule::setUuid(const char *uuid
, uptr size
) {
174 if (size
> kModuleUUIDSize
)
175 size
= kModuleUUIDSize
;
176 internal_memcpy(uuid_
, uuid
, size
);
180 void LoadedModule::clear() {
181 InternalFree(full_name_
);
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();
195 void LoadedModule::addAddressRange(uptr beg
, uptr end
, bool executable
,
196 bool writable
, const char *name
) {
197 void *mem
= InternalAlloc(sizeof(AddressRange
));
199 new(mem
) AddressRange(beg
, end
, executable
, writable
, name
);
200 ranges_
.push_back(r
);
201 max_address_
= Max(max_address_
, end
);
204 bool LoadedModule::containsAddress(uptr address
) const {
205 for (const AddressRange
&r
: ranges()) {
206 if (r
.beg
<= address
&& address
< r
.end
)
212 static atomic_uintptr_t g_total_mmaped
;
214 void IncreaseTotalMmap(uptr size
) {
215 if (!common_flags()->mmap_limit_mb
) return;
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
);
223 void DecreaseTotalMmap(uptr size
) {
224 if (!common_flags()->mmap_limit_mb
) return;
225 atomic_fetch_sub(&g_total_mmaped
, size
, memory_order_relaxed
);
228 bool TemplateMatch(const char *templ
, const char *str
) {
229 if ((!str
) || str
[0] == 0)
232 if (templ
&& templ
[0] == '^') {
236 bool asterisk
= false;
237 while (templ
&& templ
[0]) {
238 if (templ
[0] == '*') {
245 return str
[0] == 0 || asterisk
;
248 char *tpos
= (char*)internal_strchr(templ
, '*');
249 char *tpos1
= (char*)internal_strchr(templ
, '$');
250 if ((!tpos
) || (tpos1
&& tpos1
< tpos
))
254 const char *str0
= str
;
255 const char *spos
= internal_strstr(str
, templ
);
256 str
= spos
+ internal_strlen(templ
);
259 tpos
[0] = tpos
== tpos1
? '$' : '*';
262 if (start
&& spos
!= str0
)
270 static char binary_name_cache_str
[kMaxPathLength
];
271 static char process_name_cache_str
[kMaxPathLength
];
273 const char *GetProcessName() {
274 return process_name_cache_str
;
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
);
282 internal_memmove(buf
, s
, len
);
288 void UpdateProcessName() {
289 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
292 // Call once to make sure that binary_name_cache_str is initialized
293 void CacheBinaryName() {
294 if (binary_name_cache_str
[0] != '\0')
296 ReadBinaryName(binary_name_cache_str
, sizeof(binary_name_cache_str
));
297 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
300 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
) {
302 uptr name_len
= internal_strlen(binary_name_cache_str
);
303 name_len
= (name_len
< buf_len
- 1) ? name_len
: buf_len
- 1;
306 internal_memcpy(buf
, binary_name_cache_str
, name_len
);
307 buf
[name_len
] = '\0';
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';
320 void PrintCmdline() {
321 char **argv
= GetArgv();
323 Printf("\nCommand: ");
324 for (uptr i
= 0; argv
[i
]; ++i
)
325 Printf("%s ", argv
[i
]);
331 static const int kMaxMallocFreeHooks
= 5;
332 struct MallocFreeHook
{
333 void (*malloc_hook
)(const void *, uptr
);
334 void (*free_hook
)(const void *);
337 static MallocFreeHook MFHooks
[kMaxMallocFreeHooks
];
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
;
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
;
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
;
372 void internal_sleep(unsigned seconds
) {
373 internal_usleep((u64
)seconds
* 1000 * 1000);
375 void SleepForSeconds(unsigned seconds
) {
376 internal_usleep((u64
)seconds
* 1000 * 1000);
378 void SleepForMillis(unsigned millis
) { internal_usleep((u64
)millis
* 1000); }
380 void WaitForDebugger(unsigned seconds
, const char *label
) {
382 Report("Sleeping for %u second(s) %s\n", seconds
, label
);
383 SleepForSeconds(seconds
);
387 } // namespace __sanitizer
389 using namespace __sanitizer
;
392 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary
,
393 const char *error_summary
) {
394 Printf("%s\n", error_summary
);
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
);
403 SANITIZER_INTERFACE_ATTRIBUTE
404 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook
)(const void *,
406 void (*free_hook
)(const void *)) {
407 return InstallMallocFreeHooks(malloc_hook
, free_hook
);
410 // Provide default (no-op) implementation of malloc hooks.
411 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook
, void *ptr
,
417 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook
, void *ptr
) {