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"
14 #include "sanitizer_allocator_interface.h"
15 #include "sanitizer_allocator_internal.h"
16 #include "sanitizer_atomic.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_libc.h"
19 #include "sanitizer_placement_new.h"
21 namespace __sanitizer
{
23 const char *SanitizerToolName
= "SanitizerTool";
25 atomic_uint32_t current_verbosity
;
27 u32 NumberOfCPUsCached
;
29 // PID of the tracer task in StopTheWorld. It shares the address space with the
30 // main process, but has a different PID and thus requires special handling.
31 uptr stoptheworld_tracer_pid
= 0;
32 // Cached pid of parent process - if the parent process dies, we want to keep
33 // writing to the same log file.
34 uptr stoptheworld_tracer_ppid
= 0;
36 void NORETURN
ReportMmapFailureAndDie(uptr size
, const char *mem_type
,
37 const char *mmap_type
, error_t err
,
39 static int recursion_count
;
40 if (SANITIZER_RTEMS
|| raw_report
|| recursion_count
) {
41 // If we are on RTEMS or raw report is requested or we went into recursion,
42 // just die. The Report() and CHECK calls below may call mmap recursively
44 RawWrite("ERROR: Failed to mmap\n");
48 Report("ERROR: %s failed to "
49 "%s 0x%zx (%zd) bytes of %s (error code: %d)\n",
50 SanitizerToolName
, mmap_type
, size
, size
, mem_type
, err
);
54 UNREACHABLE("unable to mmap");
57 typedef bool UptrComparisonFunction(const uptr
&a
, const uptr
&b
);
58 typedef bool U32ComparisonFunction(const u32
&a
, const u32
&b
);
60 const char *StripPathPrefix(const char *filepath
,
61 const char *strip_path_prefix
) {
62 if (!filepath
) return nullptr;
63 if (!strip_path_prefix
) return filepath
;
64 const char *res
= filepath
;
65 if (const char *pos
= internal_strstr(filepath
, strip_path_prefix
))
66 res
= pos
+ internal_strlen(strip_path_prefix
);
67 if (res
[0] == '.' && res
[1] == '/')
72 const char *StripModuleName(const char *module
) {
75 if (SANITIZER_WINDOWS
) {
76 // On Windows, both slash and backslash are possible.
77 // Pick the one that goes last.
78 if (const char *bslash_pos
= internal_strrchr(module
, '\\'))
79 return StripModuleName(bslash_pos
+ 1);
81 if (const char *slash_pos
= internal_strrchr(module
, '/')) {
87 void ReportErrorSummary(const char *error_message
, const char *alt_tool_name
) {
88 if (!common_flags()->print_summary
)
90 InternalScopedString
buff(kMaxSummaryLength
);
91 buff
.append("SUMMARY: %s: %s",
92 alt_tool_name
? alt_tool_name
: SanitizerToolName
, error_message
);
93 __sanitizer_report_error_summary(buff
.data());
96 // Removes the ANSI escape sequences from the input string (in-place).
97 void RemoveANSIEscapeSequencesFromString(char *str
) {
101 // We are going to remove the escape sequences in place.
106 // Skip over ANSI escape sequences with pointer 's'.
107 if (*s
== '\033' && *(s
+ 1) == '[') {
108 s
= internal_strchrnul(s
, 'm');
115 // 's' now points at a character we want to keep. Copy over the buffer
116 // content if the escape sequence has been perviously skipped andadvance
121 // If we have not seen an escape sequence, just advance both pointers.
126 // Null terminate the string.
130 void LoadedModule::set(const char *module_name
, uptr base_address
) {
132 full_name_
= internal_strdup(module_name
);
133 base_address_
= base_address
;
136 void LoadedModule::set(const char *module_name
, uptr base_address
,
137 ModuleArch arch
, u8 uuid
[kModuleUUIDSize
],
139 set(module_name
, base_address
);
141 internal_memcpy(uuid_
, uuid
, sizeof(uuid_
));
142 instrumented_
= instrumented
;
145 void LoadedModule::clear() {
146 InternalFree(full_name_
);
148 max_executable_address_
= 0;
149 full_name_
= nullptr;
150 arch_
= kModuleArchUnknown
;
151 internal_memset(uuid_
, 0, kModuleUUIDSize
);
152 instrumented_
= false;
153 while (!ranges_
.empty()) {
154 AddressRange
*r
= ranges_
.front();
160 void LoadedModule::addAddressRange(uptr beg
, uptr end
, bool executable
,
161 bool writable
, const char *name
) {
162 void *mem
= InternalAlloc(sizeof(AddressRange
));
164 new(mem
) AddressRange(beg
, end
, executable
, writable
, name
);
165 ranges_
.push_back(r
);
166 if (executable
&& end
> max_executable_address_
)
167 max_executable_address_
= end
;
170 bool LoadedModule::containsAddress(uptr address
) const {
171 for (const AddressRange
&r
: ranges()) {
172 if (r
.beg
<= address
&& address
< r
.end
)
178 static atomic_uintptr_t g_total_mmaped
;
180 void IncreaseTotalMmap(uptr size
) {
181 if (!common_flags()->mmap_limit_mb
) return;
183 atomic_fetch_add(&g_total_mmaped
, size
, memory_order_relaxed
) + size
;
184 // Since for now mmap_limit_mb is not a user-facing flag, just kill
185 // a program. Use RAW_CHECK to avoid extra mmaps in reporting.
186 RAW_CHECK((total_mmaped
>> 20) < common_flags()->mmap_limit_mb
);
189 void DecreaseTotalMmap(uptr size
) {
190 if (!common_flags()->mmap_limit_mb
) return;
191 atomic_fetch_sub(&g_total_mmaped
, size
, memory_order_relaxed
);
194 bool TemplateMatch(const char *templ
, const char *str
) {
195 if ((!str
) || str
[0] == 0)
198 if (templ
&& templ
[0] == '^') {
202 bool asterisk
= false;
203 while (templ
&& templ
[0]) {
204 if (templ
[0] == '*') {
211 return str
[0] == 0 || asterisk
;
214 char *tpos
= (char*)internal_strchr(templ
, '*');
215 char *tpos1
= (char*)internal_strchr(templ
, '$');
216 if ((!tpos
) || (tpos1
&& tpos1
< tpos
))
220 const char *str0
= str
;
221 const char *spos
= internal_strstr(str
, templ
);
222 str
= spos
+ internal_strlen(templ
);
225 tpos
[0] = tpos
== tpos1
? '$' : '*';
228 if (start
&& spos
!= str0
)
236 static char binary_name_cache_str
[kMaxPathLength
];
237 static char process_name_cache_str
[kMaxPathLength
];
239 const char *GetProcessName() {
240 return process_name_cache_str
;
243 static uptr
ReadProcessName(/*out*/ char *buf
, uptr buf_len
) {
244 ReadLongProcessName(buf
, buf_len
);
245 char *s
= const_cast<char *>(StripModuleName(buf
));
246 uptr len
= internal_strlen(s
);
248 internal_memmove(buf
, s
, len
);
254 void UpdateProcessName() {
255 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
258 // Call once to make sure that binary_name_cache_str is initialized
259 void CacheBinaryName() {
260 if (binary_name_cache_str
[0] != '\0')
262 ReadBinaryName(binary_name_cache_str
, sizeof(binary_name_cache_str
));
263 ReadProcessName(process_name_cache_str
, sizeof(process_name_cache_str
));
266 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
) {
268 uptr name_len
= internal_strlen(binary_name_cache_str
);
269 name_len
= (name_len
< buf_len
- 1) ? name_len
: buf_len
- 1;
272 internal_memcpy(buf
, binary_name_cache_str
, name_len
);
273 buf
[name_len
] = '\0';
277 void PrintCmdline() {
278 char **argv
= GetArgv();
280 Printf("\nCommand: ");
281 for (uptr i
= 0; argv
[i
]; ++i
)
282 Printf("%s ", argv
[i
]);
287 static const int kMaxMallocFreeHooks
= 5;
288 struct MallocFreeHook
{
289 void (*malloc_hook
)(const void *, uptr
);
290 void (*free_hook
)(const void *);
293 static MallocFreeHook MFHooks
[kMaxMallocFreeHooks
];
295 void RunMallocHooks(const void *ptr
, uptr size
) {
296 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
297 auto hook
= MFHooks
[i
].malloc_hook
;
303 void RunFreeHooks(const void *ptr
) {
304 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
305 auto hook
= MFHooks
[i
].free_hook
;
311 static int InstallMallocFreeHooks(void (*malloc_hook
)(const void *, uptr
),
312 void (*free_hook
)(const void *)) {
313 if (!malloc_hook
|| !free_hook
) return 0;
314 for (int i
= 0; i
< kMaxMallocFreeHooks
; i
++) {
315 if (MFHooks
[i
].malloc_hook
== nullptr) {
316 MFHooks
[i
].malloc_hook
= malloc_hook
;
317 MFHooks
[i
].free_hook
= free_hook
;
324 } // namespace __sanitizer
326 using namespace __sanitizer
;
329 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_report_error_summary
,
330 const char *error_summary
) {
331 Printf("%s\n", error_summary
);
334 SANITIZER_INTERFACE_ATTRIBUTE
335 int __sanitizer_acquire_crash_state() {
336 static atomic_uint8_t in_crash_state
= {};
337 return !atomic_exchange(&in_crash_state
, 1, memory_order_relaxed
);
340 SANITIZER_INTERFACE_ATTRIBUTE
341 int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook
)(const void *,
343 void (*free_hook
)(const void *)) {
344 return InstallMallocFreeHooks(malloc_hook
, free_hook
);