1 //===-- sanitizer_common.h --------------------------------------*- C++ -*-===//
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 run-time libraries of sanitizers.
11 // It declares common functions and classes that are used in both runtimes.
12 // Implementation of some functions are provided in sanitizer_common, while
13 // others must be defined by run-time library itself.
14 //===----------------------------------------------------------------------===//
15 #ifndef SANITIZER_COMMON_H
16 #define SANITIZER_COMMON_H
18 #include "sanitizer_flags.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_libc.h"
21 #include "sanitizer_list.h"
22 #include "sanitizer_mutex.h"
24 #if defined(_MSC_VER) && !defined(__clang__)
25 extern "C" void _ReadWriteBarrier();
26 #pragma intrinsic(_ReadWriteBarrier)
29 namespace __sanitizer
{
32 struct BufferedStackTrace
;
37 const uptr kWordSize
= SANITIZER_WORDSIZE
/ 8;
38 const uptr kWordSizeInBits
= 8 * kWordSize
;
40 const uptr kCacheLineSize
= SANITIZER_CACHE_LINE_SIZE
;
42 const uptr kMaxPathLength
= 4096;
44 const uptr kMaxThreadStackSize
= 1 << 30; // 1Gb
46 const uptr kErrorMessageBufferSize
= 1 << 16;
48 // Denotes fake PC values that come from JIT/JAVA/etc.
49 // For such PC values __tsan_symbolize_external_ex() will be called.
50 const u64 kExternalPCBit
= 1ULL << 60;
52 extern const char *SanitizerToolName
; // Can be changed by the tool.
54 extern atomic_uint32_t current_verbosity
;
55 inline void SetVerbosity(int verbosity
) {
56 atomic_store(¤t_verbosity
, verbosity
, memory_order_relaxed
);
58 inline int Verbosity() {
59 return atomic_load(¤t_verbosity
, memory_order_relaxed
);
63 inline uptr
GetPageSize() {
64 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
67 inline uptr
GetPageSizeCached() {
72 extern uptr PageSizeCached
;
73 inline uptr
GetPageSizeCached() {
75 PageSizeCached
= GetPageSize();
76 return PageSizeCached
;
79 uptr
GetMmapGranularity();
80 uptr
GetMaxVirtualAddress();
81 uptr
GetMaxUserVirtualAddress();
84 int TgKill(pid_t pid
, tid_t tid
, int sig
);
86 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
88 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
89 uptr
*tls_addr
, uptr
*tls_size
);
92 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
= false);
93 inline void *MmapOrDieQuietly(uptr size
, const char *mem_type
) {
94 return MmapOrDie(size
, mem_type
, /*raw_report*/ true);
96 void UnmapOrDie(void *addr
, uptr size
);
97 // Behaves just like MmapOrDie, but tolerates out of memory condition, in that
98 // case returns nullptr.
99 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
);
100 bool MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
= nullptr)
102 bool MmapFixedSuperNoReserve(uptr fixed_addr
, uptr size
,
103 const char *name
= nullptr) WARN_UNUSED_RESULT
;
104 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
);
105 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
, const char *name
= nullptr);
106 // Behaves just like MmapFixedOrDie, but tolerates out of memory condition, in
107 // that case returns nullptr.
108 void *MmapFixedOrDieOnFatalError(uptr fixed_addr
, uptr size
,
109 const char *name
= nullptr);
110 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
= nullptr);
111 void *MmapNoAccess(uptr size
);
112 // Map aligned chunk of address space; size and alignment are powers of two.
113 // Dies on all but out of memory errors, in the latter case returns nullptr.
114 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
115 const char *mem_type
);
116 // Disallow access to a memory range. Use MmapFixedNoAccess to allocate an
117 // unaccessible memory.
118 bool MprotectNoAccess(uptr addr
, uptr size
);
119 bool MprotectReadOnly(uptr addr
, uptr size
);
120 bool MprotectReadWrite(uptr addr
, uptr size
);
122 void MprotectMallocZones(void *addr
, int prot
);
124 #if SANITIZER_WINDOWS
125 // Zero previously mmap'd memory. Currently used only on Windows.
126 bool ZeroMmapFixedRegion(uptr fixed_addr
, uptr size
) WARN_UNUSED_RESULT
;
130 // Unmap memory. Currently only used on Linux.
131 void UnmapFromTo(uptr from
, uptr to
);
134 // Maps shadow_size_bytes of shadow memory and returns shadow address. It will
135 // be aligned to the mmap granularity * 2^shadow_scale, or to
136 // 2^min_shadow_base_alignment if that is larger. The returned address will
137 // have max(2^min_shadow_base_alignment, mmap granularity) on the left, and
138 // shadow_size_bytes bytes on the right, which on linux is mapped no access.
139 // The high_mem_end may be updated if the original shadow size doesn't fit.
140 uptr
MapDynamicShadow(uptr shadow_size_bytes
, uptr shadow_scale
,
141 uptr min_shadow_base_alignment
, uptr
&high_mem_end
);
143 // Let S = max(shadow_size, num_aliases * alias_size, ring_buffer_size).
144 // Reserves 2*S bytes of address space to the right of the returned address and
145 // ring_buffer_size bytes to the left. The returned address is aligned to 2*S.
146 // Also creates num_aliases regions of accessible memory starting at offset S
147 // from the returned address. Each region has size alias_size and is backed by
148 // the same physical memory.
149 uptr
MapDynamicShadowAndAliases(uptr shadow_size
, uptr alias_size
,
150 uptr num_aliases
, uptr ring_buffer_size
);
152 // Reserve memory range [beg, end]. If madvise_shadow is true then apply
153 // madvise (e.g. hugepages, core dumping) requested by options.
154 void ReserveShadowMemoryRange(uptr beg
, uptr end
, const char *name
,
155 bool madvise_shadow
= true);
157 // Protect size bytes of memory starting at addr. Also try to protect
158 // several pages at the start of the address space as specified by
159 // zero_base_shadow_start, at most up to the size or zero_base_max_shadow_start.
160 void ProtectGap(uptr addr
, uptr size
, uptr zero_base_shadow_start
,
161 uptr zero_base_max_shadow_start
);
163 // Find an available address space.
164 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
165 uptr
*largest_gap_found
, uptr
*max_occupied_addr
);
167 // Used to check if we can map shadow memory to a fixed location.
168 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
);
169 // Releases memory pages entirely within the [beg, end] address range. Noop if
170 // the provided range does not contain at least one entire page.
171 void ReleaseMemoryPagesToOS(uptr beg
, uptr end
);
172 void IncreaseTotalMmap(uptr size
);
173 void DecreaseTotalMmap(uptr size
);
175 void SetShadowRegionHugePageMode(uptr addr
, uptr length
);
176 bool DontDumpShadowMemory(uptr addr
, uptr length
);
177 // Check if the built VMA size matches the runtime one.
179 void RunMallocHooks(void *ptr
, uptr size
);
180 void RunFreeHooks(void *ptr
);
182 class ReservedAddressRange
{
184 uptr
Init(uptr size
, const char *name
= nullptr, uptr fixed_addr
= 0);
185 uptr
InitAligned(uptr size
, uptr align
, const char *name
= nullptr);
186 uptr
Map(uptr fixed_addr
, uptr size
, const char *name
= nullptr);
187 uptr
MapOrDie(uptr fixed_addr
, uptr size
, const char *name
= nullptr);
188 void Unmap(uptr addr
, uptr size
);
189 void *base() const { return base_
; }
190 uptr
size() const { return size_
; }
199 typedef void (*fill_profile_f
)(uptr start
, uptr rss
, bool file
,
200 /*out*/ uptr
*stats
);
202 // Parse the contents of /proc/self/smaps and generate a memory profile.
203 // |cb| is a tool-specific callback that fills the |stats| array.
204 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
);
205 void ParseUnixMemoryProfile(fill_profile_f cb
, uptr
*stats
, char *smaps
,
208 // Simple low-level (mmap-based) allocator for internal use. Doesn't have
209 // constructor, so all instances of LowLevelAllocator should be
210 // linker initialized.
212 // NOTE: Users should instead use the singleton provided via
213 // `GetGlobalLowLevelAllocator()` rather than create a new one. This way, the
214 // number of mmap fragments can be reduced and use the same contiguous mmap
215 // provided by this singleton.
216 class LowLevelAllocator
{
218 // Requires an external lock.
219 void *Allocate(uptr size
);
222 char *allocated_end_
;
223 char *allocated_current_
;
225 // Set the min alignment of LowLevelAllocator to at least alignment.
226 void SetLowLevelAllocateMinAlignment(uptr alignment
);
227 typedef void (*LowLevelAllocateCallback
)(uptr ptr
, uptr size
);
228 // Allows to register tool-specific callbacks for LowLevelAllocator.
229 // Passing NULL removes the callback.
230 void SetLowLevelAllocateCallback(LowLevelAllocateCallback callback
);
232 LowLevelAllocator
&GetGlobalLowLevelAllocator();
235 void CatastrophicErrorWrite(const char *buffer
, uptr length
);
236 void RawWrite(const char *buffer
);
237 bool ColorizeReports();
238 void RemoveANSIEscapeSequencesFromString(char *buffer
);
239 void Printf(const char *format
, ...) FORMAT(1, 2);
240 void Report(const char *format
, ...) FORMAT(1, 2);
241 void SetPrintfAndReportCallback(void (*callback
)(const char *));
242 #define VReport(level, ...) \
244 if ((uptr)Verbosity() >= (level)) Report(__VA_ARGS__); \
246 #define VPrintf(level, ...) \
248 if ((uptr)Verbosity() >= (level)) Printf(__VA_ARGS__); \
251 // Lock sanitizer error reporting and protects against nested errors.
252 class ScopedErrorReportLock
{
254 ScopedErrorReportLock() SANITIZER_ACQUIRE(mutex_
) { Lock(); }
255 ~ScopedErrorReportLock() SANITIZER_RELEASE(mutex_
) { Unlock(); }
257 static void Lock() SANITIZER_ACQUIRE(mutex_
);
258 static void Unlock() SANITIZER_RELEASE(mutex_
);
259 static void CheckLocked() SANITIZER_CHECK_LOCKED(mutex_
);
262 static atomic_uintptr_t reporting_thread_
;
263 static StaticSpinMutex mutex_
;
266 extern uptr stoptheworld_tracer_pid
;
267 extern uptr stoptheworld_tracer_ppid
;
269 bool IsAccessibleMemoryRange(uptr beg
, uptr size
);
271 // Error report formatting.
272 const char *StripPathPrefix(const char *filepath
,
273 const char *strip_file_prefix
);
274 // Strip the directories from the module name.
275 const char *StripModuleName(const char *module
);
278 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
);
279 uptr
ReadBinaryNameCached(/*out*/char *buf
, uptr buf_len
);
280 uptr
ReadBinaryDir(/*out*/ char *buf
, uptr buf_len
);
281 uptr
ReadLongProcessName(/*out*/ char *buf
, uptr buf_len
);
282 const char *GetProcessName();
283 void UpdateProcessName();
284 void CacheBinaryName();
285 void DisableCoreDumperIfNecessary();
286 void DumpProcessMap();
287 const char *GetEnv(const char *name
);
288 bool SetEnv(const char *name
, const char *value
);
293 void CheckMPROTECT();
297 bool StackSizeIsUnlimited();
298 void SetStackSizeLimitInBytes(uptr limit
);
299 bool AddressSpaceIsUnlimited();
300 void SetAddressSpaceUnlimited();
301 void AdjustStackSize(void *attr
);
302 void PlatformPrepareForSandboxing(void *args
);
303 void SetSandboxingCallback(void (*f
)());
305 void InitializeCoverage(bool enabled
, const char *coverage_dir
);
311 void WaitForDebugger(unsigned seconds
, const char *label
);
312 void SleepForSeconds(unsigned seconds
);
313 void SleepForMillis(unsigned millis
);
315 u64
MonotonicNanoTime();
316 int Atexit(void (*function
)(void));
317 bool TemplateMatch(const char *templ
, const char *str
);
320 void NORETURN
Abort();
323 CheckFailed(const char *file
, int line
, const char *cond
, u64 v1
, u64 v2
);
324 void NORETURN
ReportMmapFailureAndDie(uptr size
, const char *mem_type
,
325 const char *mmap_type
, error_t err
,
326 bool raw_report
= false);
327 void NORETURN
ReportMunmapFailureAndDie(void *ptr
, uptr size
, error_t err
,
328 bool raw_report
= false);
330 // Returns true if the platform-specific error reported is an OOM error.
331 bool ErrorIsOOM(error_t err
);
333 // This reports an error in the form:
335 // `ERROR: {{SanitizerToolName}}: out of memory: {{err_msg}}`
337 // Downstream tools that read sanitizer output will know that errors starting
338 // in this format are specifically OOM errors.
339 #define ERROR_OOM(err_msg, ...) \
340 Report("ERROR: %s: out of memory: " err_msg, SanitizerToolName, __VA_ARGS__)
342 // Specific tools may override behavior of "Die" function to do tool-specific
344 typedef void (*DieCallbackType
)(void);
346 // It's possible to add several callbacks that would be run when "Die" is
347 // called. The callbacks will be run in the opposite order. The tools are
348 // strongly recommended to setup all callbacks during initialization, when there
349 // is only a single thread.
350 bool AddDieCallback(DieCallbackType callback
);
351 bool RemoveDieCallback(DieCallbackType callback
);
353 void SetUserDieCallback(DieCallbackType callback
);
355 void SetCheckUnwindCallback(void (*callback
)());
357 // Functions related to signal handling.
358 typedef void (*SignalHandlerType
)(int, void *, void *);
359 HandleSignalMode
GetHandleSignalMode(int signum
);
360 void InstallDeadlySignalHandlers(SignalHandlerType handler
);
363 // Each sanitizer uses slightly different implementation of stack unwinding.
364 typedef void (*UnwindSignalStackCallbackType
)(const SignalContext
&sig
,
365 const void *callback_context
,
366 BufferedStackTrace
*stack
);
367 // Print deadly signal report and die.
368 void HandleDeadlySignal(void *siginfo
, void *context
, u32 tid
,
369 UnwindSignalStackCallbackType unwind
,
370 const void *unwind_context
);
372 // Part of HandleDeadlySignal, exposed for asan.
373 void StartReportDeadlySignal();
374 // Part of HandleDeadlySignal, exposed for asan.
375 void ReportDeadlySignal(const SignalContext
&sig
, u32 tid
,
376 UnwindSignalStackCallbackType unwind
,
377 const void *unwind_context
);
379 // Alternative signal stack (POSIX-only).
380 void SetAlternateSignalStack();
381 void UnsetAlternateSignalStack();
383 // Construct a one-line string:
384 // SUMMARY: SanitizerToolName: error_message
385 // and pass it to __sanitizer_report_error_summary.
386 // If alt_tool_name is provided, it's used in place of SanitizerToolName.
387 void ReportErrorSummary(const char *error_message
,
388 const char *alt_tool_name
= nullptr);
389 // Same as above, but construct error_message as:
390 // error_type file:line[:column][ function]
391 void ReportErrorSummary(const char *error_type
, const AddressInfo
&info
,
392 const char *alt_tool_name
= nullptr);
393 // Same as above, but obtains AddressInfo by symbolizing top stack trace frame.
394 void ReportErrorSummary(const char *error_type
, const StackTrace
*trace
,
395 const char *alt_tool_name
= nullptr);
397 void ReportMmapWriteExec(int prot
, int mflags
);
400 #if SANITIZER_WINDOWS && !defined(__clang__) && !defined(__GNUC__)
402 unsigned char _BitScanForward(unsigned long *index
, unsigned long mask
);
403 unsigned char _BitScanReverse(unsigned long *index
, unsigned long mask
);
405 unsigned char _BitScanForward64(unsigned long *index
, unsigned __int64 mask
);
406 unsigned char _BitScanReverse64(unsigned long *index
, unsigned __int64 mask
);
411 inline uptr
MostSignificantSetBitIndex(uptr x
) {
414 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
416 up
= SANITIZER_WORDSIZE
- 1 - __builtin_clzll(x
);
418 up
= SANITIZER_WORDSIZE
- 1 - __builtin_clzl(x
);
420 #elif defined(_WIN64)
421 _BitScanReverse64(&up
, x
);
423 _BitScanReverse(&up
, x
);
428 inline uptr
LeastSignificantSetBitIndex(uptr x
) {
431 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
433 up
= __builtin_ctzll(x
);
435 up
= __builtin_ctzl(x
);
437 #elif defined(_WIN64)
438 _BitScanForward64(&up
, x
);
440 _BitScanForward(&up
, x
);
445 inline constexpr bool IsPowerOfTwo(uptr x
) { return (x
& (x
- 1)) == 0; }
447 inline uptr
RoundUpToPowerOfTwo(uptr size
) {
449 if (IsPowerOfTwo(size
)) return size
;
451 uptr up
= MostSignificantSetBitIndex(size
);
452 CHECK_LT(size
, (1ULL << (up
+ 1)));
453 CHECK_GT(size
, (1ULL << up
));
454 return 1ULL << (up
+ 1);
457 inline constexpr uptr
RoundUpTo(uptr size
, uptr boundary
) {
458 RAW_CHECK(IsPowerOfTwo(boundary
));
459 return (size
+ boundary
- 1) & ~(boundary
- 1);
462 inline constexpr uptr
RoundDownTo(uptr x
, uptr boundary
) {
463 return x
& ~(boundary
- 1);
466 inline constexpr bool IsAligned(uptr a
, uptr alignment
) {
467 return (a
& (alignment
- 1)) == 0;
470 inline uptr
Log2(uptr x
) {
471 CHECK(IsPowerOfTwo(x
));
472 return LeastSignificantSetBitIndex(x
);
475 // Don't use std::min, std::max or std::swap, to minimize dependency
478 constexpr T
Min(T a
, T b
) {
479 return a
< b
? a
: b
;
482 constexpr T
Max(T a
, T b
) {
483 return a
> b
? a
: b
;
486 constexpr T
Abs(T a
) {
487 return a
< 0 ? -a
: a
;
489 template<class T
> void Swap(T
& a
, T
& b
) {
496 inline bool IsSpace(int c
) {
497 return (c
== ' ') || (c
== '\n') || (c
== '\t') ||
498 (c
== '\f') || (c
== '\r') || (c
== '\v');
500 inline bool IsDigit(int c
) {
501 return (c
>= '0') && (c
<= '9');
503 inline int ToLower(int c
) {
504 return (c
>= 'A' && c
<= 'Z') ? (c
+ 'a' - 'A') : c
;
507 // A low-level vector based on mmap. May incur a significant memory overhead for
509 // WARNING: The current implementation supports only POD types.
511 class InternalMmapVectorNoCtor
{
513 using value_type
= T
;
514 void Initialize(uptr initial_capacity
) {
518 reserve(initial_capacity
);
520 void Destroy() { UnmapOrDie(data_
, capacity_bytes_
); }
521 T
&operator[](uptr i
) {
525 const T
&operator[](uptr i
) const {
529 void push_back(const T
&element
) {
530 if (UNLIKELY(size_
>= capacity())) {
531 CHECK_EQ(size_
, capacity());
532 uptr new_capacity
= RoundUpToPowerOfTwo(size_
+ 1);
533 Realloc(new_capacity
);
535 internal_memcpy(&data_
[size_
++], &element
, sizeof(T
));
539 return data_
[size_
- 1];
548 const T
*data() const {
554 uptr
capacity() const { return capacity_bytes_
/ sizeof(T
); }
555 void reserve(uptr new_size
) {
556 // Never downsize internal buffer.
557 if (new_size
> capacity())
560 void resize(uptr new_size
) {
561 if (new_size
> size_
) {
563 internal_memset(&data_
[size_
], 0, sizeof(T
) * (new_size
- size_
));
568 void clear() { size_
= 0; }
569 bool empty() const { return size() == 0; }
571 const T
*begin() const {
577 const T
*end() const {
578 return data() + size();
581 return data() + size();
584 void swap(InternalMmapVectorNoCtor
&other
) {
585 Swap(data_
, other
.data_
);
586 Swap(capacity_bytes_
, other
.capacity_bytes_
);
587 Swap(size_
, other
.size_
);
591 NOINLINE
void Realloc(uptr new_capacity
) {
592 CHECK_GT(new_capacity
, 0);
593 CHECK_LE(size_
, new_capacity
);
594 uptr new_capacity_bytes
=
595 RoundUpTo(new_capacity
* sizeof(T
), GetPageSizeCached());
596 T
*new_data
= (T
*)MmapOrDie(new_capacity_bytes
, "InternalMmapVector");
597 internal_memcpy(new_data
, data_
, size_
* sizeof(T
));
598 UnmapOrDie(data_
, capacity_bytes_
);
600 capacity_bytes_
= new_capacity_bytes
;
604 uptr capacity_bytes_
;
608 template <typename T
>
609 bool operator==(const InternalMmapVectorNoCtor
<T
> &lhs
,
610 const InternalMmapVectorNoCtor
<T
> &rhs
) {
611 if (lhs
.size() != rhs
.size()) return false;
612 return internal_memcmp(lhs
.data(), rhs
.data(), lhs
.size() * sizeof(T
)) == 0;
615 template <typename T
>
616 bool operator!=(const InternalMmapVectorNoCtor
<T
> &lhs
,
617 const InternalMmapVectorNoCtor
<T
> &rhs
) {
618 return !(lhs
== rhs
);
622 class InternalMmapVector
: public InternalMmapVectorNoCtor
<T
> {
624 InternalMmapVector() { InternalMmapVectorNoCtor
<T
>::Initialize(0); }
625 explicit InternalMmapVector(uptr cnt
) {
626 InternalMmapVectorNoCtor
<T
>::Initialize(cnt
);
629 ~InternalMmapVector() { InternalMmapVectorNoCtor
<T
>::Destroy(); }
630 // Disallow copies and moves.
631 InternalMmapVector(const InternalMmapVector
&) = delete;
632 InternalMmapVector
&operator=(const InternalMmapVector
&) = delete;
633 InternalMmapVector(InternalMmapVector
&&) = delete;
634 InternalMmapVector
&operator=(InternalMmapVector
&&) = delete;
637 class InternalScopedString
{
639 InternalScopedString() : buffer_(1) { buffer_
[0] = '\0'; }
641 uptr
length() const { return buffer_
.size() - 1; }
646 void Append(const char *str
);
647 void AppendF(const char *format
, ...) FORMAT(2, 3);
648 const char *data() const { return buffer_
.data(); }
649 char *data() { return buffer_
.data(); }
652 InternalMmapVector
<char> buffer_
;
657 bool operator()(const T
&a
, const T
&b
) const { return a
< b
; }
660 // HeapSort for arrays and InternalMmapVector.
661 template <class T
, class Compare
= CompareLess
<T
>>
662 void Sort(T
*v
, uptr size
, Compare comp
= {}) {
665 // Stage 1: insert elements to the heap.
666 for (uptr i
= 1; i
< size
; i
++) {
668 for (j
= i
; j
> 0; j
= p
) {
670 if (comp(v
[p
], v
[j
]))
676 // Stage 2: swap largest element with the last one,
677 // and sink the new top.
678 for (uptr i
= size
- 1; i
> 0; i
--) {
681 for (j
= 0; j
< i
; j
= max_ind
) {
682 uptr left
= 2 * j
+ 1;
683 uptr right
= 2 * j
+ 2;
685 if (left
< i
&& comp(v
[max_ind
], v
[left
]))
687 if (right
< i
&& comp(v
[max_ind
], v
[right
]))
690 Swap(v
[j
], v
[max_ind
]);
697 // Works like std::lower_bound: finds the first element that is not less
699 template <class Container
, class T
,
700 class Compare
= CompareLess
<typename
Container::value_type
>>
701 uptr
InternalLowerBound(const Container
&v
, const T
&val
, Compare comp
= {}) {
703 uptr last
= v
.size();
704 while (last
> first
) {
705 uptr mid
= (first
+ last
) / 2;
706 if (comp(v
[mid
], val
))
724 kModuleArchLoongArch64
,
729 // Sorts and removes duplicates from the container.
730 template <class Container
,
731 class Compare
= CompareLess
<typename
Container::value_type
>>
732 void SortAndDedup(Container
&v
, Compare comp
= {}) {
733 Sort(v
.data(), v
.size(), comp
);
734 uptr size
= v
.size();
738 for (uptr i
= 1; i
< size
; ++i
) {
739 if (comp(v
[last
], v
[i
])) {
744 CHECK(!comp(v
[i
], v
[last
]));
750 constexpr uptr kDefaultFileMaxSize
= FIRST_32_SECOND_64(1 << 26, 1 << 28);
752 // Opens the file 'file_name" and reads up to 'max_len' bytes.
753 // The resulting buffer is mmaped and stored in '*buff'.
754 // Returns true if file was successfully opened and read.
755 bool ReadFileToVector(const char *file_name
,
756 InternalMmapVectorNoCtor
<char> *buff
,
757 uptr max_len
= kDefaultFileMaxSize
,
758 error_t
*errno_p
= nullptr);
760 // Opens the file 'file_name" and reads up to 'max_len' bytes.
761 // This function is less I/O efficient than ReadFileToVector as it may reread
762 // file multiple times to avoid mmap during read attempts. It's used to read
763 // procmap, so short reads with mmap in between can produce inconsistent result.
764 // The resulting buffer is mmaped and stored in '*buff'.
765 // The size of the mmaped region is stored in '*buff_size'.
766 // The total number of read bytes is stored in '*read_len'.
767 // Returns true if file was successfully opened and read.
768 bool ReadFileToBuffer(const char *file_name
, char **buff
, uptr
*buff_size
,
769 uptr
*read_len
, uptr max_len
= kDefaultFileMaxSize
,
770 error_t
*errno_p
= nullptr);
772 int GetModuleAndOffsetForPc(uptr pc
, char *module_name
, uptr module_name_len
,
775 // When adding a new architecture, don't forget to also update
776 // script/asan_symbolize.py and sanitizer_symbolizer_libcdep.cpp.
777 inline const char *ModuleArchToString(ModuleArch arch
) {
779 case kModuleArchUnknown
:
781 case kModuleArchI386
:
783 case kModuleArchX86_64
:
785 case kModuleArchX86_64H
:
787 case kModuleArchARMV6
:
789 case kModuleArchARMV7
:
791 case kModuleArchARMV7S
:
793 case kModuleArchARMV7K
:
795 case kModuleArchARM64
:
797 case kModuleArchLoongArch64
:
798 return "loongarch64";
799 case kModuleArchRISCV64
:
801 case kModuleArchHexagon
:
804 CHECK(0 && "Invalid module arch");
809 const uptr kModuleUUIDSize
= 16;
811 const uptr kModuleUUIDSize
= 32;
813 const uptr kMaxSegName
= 16;
815 // Represents a binary loaded into virtual memory (e.g. this can be an
816 // executable or a shared object).
820 : full_name_(nullptr),
823 arch_(kModuleArchUnknown
),
825 instrumented_(false) {
826 internal_memset(uuid_
, 0, kModuleUUIDSize
);
829 void set(const char *module_name
, uptr base_address
);
830 void set(const char *module_name
, uptr base_address
, ModuleArch arch
,
831 u8 uuid
[kModuleUUIDSize
], bool instrumented
);
832 void setUuid(const char *uuid
, uptr size
);
834 void addAddressRange(uptr beg
, uptr end
, bool executable
, bool writable
,
835 const char *name
= nullptr);
836 bool containsAddress(uptr address
) const;
838 const char *full_name() const { return full_name_
; }
839 uptr
base_address() const { return base_address_
; }
840 uptr
max_address() const { return max_address_
; }
841 ModuleArch
arch() const { return arch_
; }
842 const u8
*uuid() const { return uuid_
; }
843 uptr
uuid_size() const { return uuid_size_
; }
844 bool instrumented() const { return instrumented_
; }
846 struct AddressRange
{
852 char name
[kMaxSegName
];
854 AddressRange(uptr beg
, uptr end
, bool executable
, bool writable
,
859 executable(executable
),
861 internal_strncpy(this->name
, (name
? name
: ""), ARRAY_SIZE(this->name
));
865 const IntrusiveList
<AddressRange
> &ranges() const { return ranges_
; }
868 char *full_name_
; // Owned.
873 u8 uuid_
[kModuleUUIDSize
];
875 IntrusiveList
<AddressRange
> ranges_
;
878 // List of LoadedModules. OS-dependent implementation is responsible for
879 // filling this information.
880 class ListOfModules
{
882 ListOfModules() : initialized(false) {}
883 ~ListOfModules() { clear(); }
885 void fallbackInit(); // Uses fallback init if available, otherwise clears
886 const LoadedModule
*begin() const { return modules_
.begin(); }
887 LoadedModule
*begin() { return modules_
.begin(); }
888 const LoadedModule
*end() const { return modules_
.end(); }
889 LoadedModule
*end() { return modules_
.end(); }
890 uptr
size() const { return modules_
.size(); }
891 const LoadedModule
&operator[](uptr i
) const {
892 CHECK_LT(i
, modules_
.size());
898 for (auto &module
: modules_
) module
.clear();
902 initialized
? clear() : modules_
.Initialize(kInitialCapacity
);
906 InternalMmapVectorNoCtor
<LoadedModule
> modules_
;
907 // We rarely have more than 16K loaded modules.
908 static const uptr kInitialCapacity
= 1 << 14;
912 // Callback type for iterating over a set of memory ranges.
913 typedef void (*RangeIteratorCallback
)(uptr begin
, uptr end
, void *arg
);
915 enum AndroidApiLevel
{
916 ANDROID_NOT_ANDROID
= 0,
918 ANDROID_LOLLIPOP_MR1
= 22,
919 ANDROID_POST_LOLLIPOP
= 23
922 void WriteToSyslog(const char *buffer
);
924 #if defined(SANITIZER_WINDOWS) && defined(_MSC_VER) && !defined(__clang__)
925 #define SANITIZER_WIN_TRACE 1
927 #define SANITIZER_WIN_TRACE 0
930 #if SANITIZER_APPLE || SANITIZER_WIN_TRACE
931 void LogFullErrorReport(const char *buffer
);
933 inline void LogFullErrorReport(const char *buffer
) {}
936 #if SANITIZER_LINUX || SANITIZER_APPLE
937 void WriteOneLineToSyslog(const char *s
);
938 void LogMessageOnPrintf(const char *str
);
940 inline void WriteOneLineToSyslog(const char *s
) {}
941 inline void LogMessageOnPrintf(const char *str
) {}
944 #if SANITIZER_LINUX || SANITIZER_WIN_TRACE
945 // Initialize Android logging. Any writes before this are silently lost.
946 void AndroidLogInit();
947 void SetAbortMessage(const char *);
949 inline void AndroidLogInit() {}
950 // FIXME: MacOS implementation could use CRSetCrashLogMessage.
951 inline void SetAbortMessage(const char *) {}
954 #if SANITIZER_ANDROID
955 void SanitizerInitializeUnwinder();
956 AndroidApiLevel
AndroidGetApiLevel();
958 inline void AndroidLogWrite(const char *buffer_unused
) {}
959 inline void SanitizerInitializeUnwinder() {}
960 inline AndroidApiLevel
AndroidGetApiLevel() { return ANDROID_NOT_ANDROID
; }
963 inline uptr
GetPthreadDestructorIterations() {
964 #if SANITIZER_ANDROID
965 return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1
) ? 8 : 4;
966 #elif SANITIZER_POSIX
969 // Unused on Windows.
974 void *internal_start_thread(void *(*func
)(void*), void *arg
);
975 void internal_join_thread(void *th
);
976 void MaybeStartBackgroudThread();
978 // Make the compiler think that something is going on there.
979 // Use this inside a loop that looks like memset/memcpy/etc to prevent the
980 // compiler from recognising it and turning it into an actual call to
981 // memset/memcpy/etc.
982 static inline void SanitizerBreakOptimization(void *arg
) {
983 #if defined(_MSC_VER) && !defined(__clang__)
986 __asm__
__volatile__("" : : "r" (arg
) : "memory");
990 struct SignalContext
{
997 bool is_memory_access
;
998 enum WriteFlag
{ Unknown
, Read
, Write
} write_flag
;
1000 // In some cases the kernel cannot provide the true faulting address; `addr`
1001 // will be zero then. This field allows to distinguish between these cases
1002 // and dereferences of null.
1003 bool is_true_faulting_addr
;
1005 // VS2013 doesn't implement unrestricted unions, so we need a trivial default
1007 SignalContext() = default;
1009 // Creates signal context in a platform-specific manner.
1010 // SignalContext is going to keep pointers to siginfo and context without
1012 SignalContext(void *siginfo
, void *context
)
1016 is_memory_access(IsMemoryAccess()),
1017 write_flag(GetWriteFlag()),
1018 is_true_faulting_addr(IsTrueFaultingAddress()) {
1022 static void DumpAllRegisters(void *context
);
1024 // Type of signal e.g. SIGSEGV or EXCEPTION_ACCESS_VIOLATION.
1025 int GetType() const;
1027 // String description of the signal.
1028 const char *Describe() const;
1030 // Returns true if signal is stack overflow.
1031 bool IsStackOverflow() const;
1034 // Platform specific initialization.
1036 uptr
GetAddress() const;
1037 WriteFlag
GetWriteFlag() const;
1038 bool IsMemoryAccess() const;
1039 bool IsTrueFaultingAddress() const;
1042 void InitializePlatformEarly();
1044 template <typename Fn
>
1045 class RunOnDestruction
{
1047 explicit RunOnDestruction(Fn fn
) : fn_(fn
) {}
1048 ~RunOnDestruction() { fn_(); }
1054 // A simple scope guard. Usage:
1055 // auto cleanup = at_scope_exit([]{ do_cleanup; });
1056 template <typename Fn
>
1057 RunOnDestruction
<Fn
> at_scope_exit(Fn fn
) {
1058 return RunOnDestruction
<Fn
>(fn
);
1061 // Linux on 64-bit s390 had a nasty bug that crashes the whole machine
1062 // if a process uses virtual memory over 4TB (as many sanitizers like
1063 // to do). This function will abort the process if running on a kernel
1064 // that looks vulnerable.
1065 #if SANITIZER_LINUX && SANITIZER_S390_64
1066 void AvoidCVE_2016_2143();
1068 inline void AvoidCVE_2016_2143() {}
1071 struct StackDepotStats
{
1076 // The default value for allocator_release_to_os_interval_ms common flag to
1077 // indicate that sanitizer allocator should not attempt to release memory to OS.
1078 const s32 kReleaseToOSIntervalNever
= -1;
1080 void CheckNoDeepBind(const char *filename
, int flag
);
1082 // Returns the requested amount of random data (up to 256 bytes) that can then
1083 // be used to seed a PRNG. Defaults to blocking like the underlying syscall.
1084 bool GetRandom(void *buffer
, uptr length
, bool blocking
= true);
1086 // Returns the number of logical processors on the system.
1087 u32
GetNumberOfCPUs();
1088 extern u32 NumberOfCPUsCached
;
1089 inline u32
GetNumberOfCPUsCached() {
1090 if (!NumberOfCPUsCached
)
1091 NumberOfCPUsCached
= GetNumberOfCPUs();
1092 return NumberOfCPUsCached
;
1095 } // namespace __sanitizer
1097 inline void *operator new(__sanitizer::operator_new_size_type size
,
1098 __sanitizer::LowLevelAllocator
&alloc
) {
1099 return alloc
.Allocate(size
);
1102 #endif // SANITIZER_COMMON_H