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 Report("ERROR: %s failed to "
50 "%s 0x%zx (%zd) bytes of %s (error code: %d)\n",
51 SanitizerToolName
, mmap_type
, size
, size
, mem_type
, err
);
55 UNREACHABLE("unable to mmap");
58 typedef bool UptrComparisonFunction(const uptr
&a
, const uptr
&b
);
59 typedef bool U32ComparisonFunction(const u32
&a
, const u32
&b
);
61 const char *StripPathPrefix(const char *filepath
,
62 const char *strip_path_prefix
) {
63 if (!filepath
) return nullptr;
64 if (!strip_path_prefix
) return filepath
;
65 const char *res
= filepath
;
66 if (const char *pos
= internal_strstr(filepath
, strip_path_prefix
))
67 res
= pos
+ internal_strlen(strip_path_prefix
);
68 if (res
[0] == '.' && res
[1] == '/')
73 const char *StripModuleName(const char *module
) {
76 if (SANITIZER_WINDOWS
) {
77 // On Windows, both slash and backslash are possible.
78 // Pick the one that goes last.
79 if (const char *bslash_pos
= internal_strrchr(module
, '\\'))
80 return StripModuleName(bslash_pos
+ 1);
82 if (const char *slash_pos
= internal_strrchr(module
, '/')) {
88 void ReportErrorSummary(const char *error_message
, const char *alt_tool_name
) {
89 if (!common_flags()->print_summary
)
91 InternalScopedString buff
;
92 buff
.append("SUMMARY: %s: %s",
93 alt_tool_name
? alt_tool_name
: SanitizerToolName
, error_message
);
94 __sanitizer_report_error_summary(buff
.data());
97 // Removes the ANSI escape sequences from the input string (in-place).
98 void RemoveANSIEscapeSequencesFromString(char *str
) {
102 // We are going to remove the escape sequences in place.
107 // Skip over ANSI escape sequences with pointer 's'.
108 if (*s
== '\033' && *(s
+ 1) == '[') {
109 s
= internal_strchrnul(s
, 'm');
116 // 's' now points at a character we want to keep. Copy over the buffer
117 // content if the escape sequence has been perviously skipped andadvance
122 // If we have not seen an escape sequence, just advance both pointers.
127 // Null terminate the string.
131 void LoadedModule::set(const char *module_name
, uptr base_address
) {
133 full_name_
= internal_strdup(module_name
);
134 base_address_
= base_address
;
137 void LoadedModule::set(const char *module_name
, uptr base_address
,
138 ModuleArch arch
, u8 uuid
[kModuleUUIDSize
],
140 set(module_name
, base_address
);
142 internal_memcpy(uuid_
, uuid
, sizeof(uuid_
));
143 uuid_size_
= kModuleUUIDSize
;
144 instrumented_
= instrumented
;
147 void LoadedModule::setUuid(const char *uuid
, uptr size
) {
148 if (size
> kModuleUUIDSize
)
149 size
= kModuleUUIDSize
;
150 internal_memcpy(uuid_
, uuid
, size
);
154 void LoadedModule::clear() {
155 InternalFree(full_name_
);
158 full_name_
= nullptr;
159 arch_
= kModuleArchUnknown
;
160 internal_memset(uuid_
, 0, kModuleUUIDSize
);
161 instrumented_
= false;
162 while (!ranges_
.empty()) {
163 AddressRange
*r
= ranges_
.front();
169 void LoadedModule::addAddressRange(uptr beg
, uptr end
, bool executable
,
170 bool writable
, const char *name
) {
171 void *mem
= InternalAlloc(sizeof(AddressRange
));
173 new(mem
) AddressRange(beg
, end
, executable
, writable
, name
);
174 ranges_
.push_back(r
);
175 max_address_
= Max(max_address_
, end
);
178 bool LoadedModule::containsAddress(uptr address
) const {
179 for (const AddressRange
&r
: ranges()) {
180 if (r
.beg
<= address
&& address
< r
.end
)
186 static atomic_uintptr_t g_total_mmaped
;
188 void IncreaseTotalMmap(uptr size
) {
189 if (!common_flags()->mmap_limit_mb
) return;
191 atomic_fetch_add(&g_total_mmaped
, size
, memory_order_relaxed
) + size
;
192 // Since for now mmap_limit_mb is not a user-facing flag, just kill
193 // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
194 RAW_CHECK((total_mmaped
>> 20) < common_flags()->mmap_limit_mb
);
197 void DecreaseTotalMmap(uptr size
) {
198 if (!common_flags()->mmap_limit_mb
) return;
199 atomic_fetch_sub(&g_total_mmaped
, size
, memory_order_relaxed
);
202 bool TemplateMatch(const char *templ
, const char *str
) {
203 if ((!str
) || str
[0] == 0)
206 if (templ
&& templ
[0] == '^') {
210 bool asterisk
= false;
211 while (templ
&& templ
[0]) {
212 if (templ
[0] == '*') {
219 return str
[0] == 0 || asterisk
;
222 char *tpos
= (char*)internal_strchr(templ
, '*');
223 char *tpos1
= (char*)internal_strchr(templ
, '$');
224 if ((!tpos
) || (tpos1
&& tpos1
< tpos
))
228 const char *str0
= str
;
229 const char *spos
= internal_strstr(str
, templ
);
230 str
= spos
+ internal_strlen(templ
);
233 tpos
[0] = tpos
== tpos1
? '$' : '*';
236 if (start
&& spos
!= str0
)
244 static char binary_name_cache_str
[kMaxPathLength
];
245 static char process_name_cache_str
[kMaxPathLength
];
247 const char *GetProcessName() {
248 return process_name_cache_str
;
251 static uptr
ReadProcessName(/*out*/ char *buf
, uptr buf_len
) {
252 ReadLongProcessName(buf
, buf_len
);
253 char *s
= const_cast<char *>(StripModuleName(buf
));
254 uptr len
= internal_strlen(s
);
256 internal_memmove(buf
, s
, len
);
262 void UpdateProcessName() {
263 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
266 // Call once to make sure that binary_name_cache_str is initialized
267 void CacheBinaryName() {
268 if (binary_name_cache_str
[0] != '\0')
270 ReadBinaryName(binary_name_cache_str
, sizeof(binary_name_cache_str
));
271 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
274 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
) {
276 uptr name_len
= internal_strlen(binary_name_cache_str
);
277 name_len
= (name_len
< buf_len
- 1) ? name_len
: buf_len
- 1;
280 internal_memcpy(buf
, binary_name_cache_str
, name_len
);
281 buf
[name_len
] = '\0';
285 uptr
ReadBinaryDir(/*out*/ char *buf
, uptr buf_len
) {
286 ReadBinaryNameCached(buf
, buf_len
);
287 const char *exec_name_pos
= StripModuleName(buf
);
288 uptr name_len
= exec_name_pos
- buf
;
289 buf
[name_len
] = '\0';
294 void PrintCmdline() {
295 char **argv
= GetArgv();
297 Printf("\nCommand: ");
298 for (uptr i
= 0; argv
[i
]; ++i
)
299 Printf("%s ", argv
[i
]);
305 static const int kMaxMallocFreeHooks
= 5;
306 struct MallocFreeHook
{
307 void (*malloc_hook
)(const void *, uptr
);
308 void (*free_hook
)(const void *);
311 static MallocFreeHook MFHooks
[kMaxMallocFreeHooks
];
313 void RunMallocHooks(const void *ptr
, uptr size
) {
314 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
315 auto hook
= MFHooks
[i
].malloc_hook
;
321 void RunFreeHooks(const void *ptr
) {
322 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
323 auto hook
= MFHooks
[i
].free_hook
;
329 static int InstallMallocFreeHooks(void (*malloc_hook
)(const void *, uptr
),
330 void (*free_hook
)(const void *)) {
331 if (!malloc_hook
|| !free_hook
) return 0;
332 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
333 if (MFHooks
[i
].malloc_hook
== nullptr) {
334 MFHooks
[i
].malloc_hook
= malloc_hook
;
335 MFHooks
[i
].free_hook
= free_hook
;
342 void internal_sleep(unsigned seconds
) {
343 internal_usleep((u64
)seconds
* 1000 * 1000);
345 void SleepForSeconds(unsigned seconds
) {
346 internal_usleep((u64
)seconds
* 1000 * 1000);
348 void SleepForMillis(unsigned millis
) { internal_usleep((u64
)millis
* 1000); }
350 } // namespace __sanitizer
352 using namespace __sanitizer
;
355 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary
,
356 const char *error_summary
) {
357 Printf("%s\n", error_summary
);
360 SANITIZER_INTERFACE_ATTRIBUTE
361 int __sanitizer_acquire_crash_state() {
362 static atomic_uint8_t in_crash_state
= {};
363 return !atomic_exchange(&in_crash_state
, 1, memory_order_relaxed
);
366 SANITIZER_INTERFACE_ATTRIBUTE
367 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook
)(const void *,
369 void (*free_hook
)(const void *)) {
370 return InstallMallocFreeHooks(malloc_hook
, free_hook
);