1 //===-- sanitizer_allocator.h -----------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Specialized memory allocator for ThreadSanitizer, MemorySanitizer, etc.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef SANITIZER_ALLOCATOR_H
14 #define SANITIZER_ALLOCATOR_H
15 
16 #include "sanitizer_common.h"
17 #include "sanitizer_internal_defs.h"
18 #include "sanitizer_lfstack.h"
19 #include "sanitizer_libc.h"
20 #include "sanitizer_list.h"
21 #include "sanitizer_local_address_space_view.h"
22 #include "sanitizer_mutex.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_type_traits.h"
25 
26 namespace __sanitizer {
27 
28 // Allows the tools to name their allocations appropriately.
29 extern const char *PrimaryAllocatorName;
30 extern const char *SecondaryAllocatorName;
31 
32 // Since flags are immutable and allocator behavior can be changed at runtime
33 // (unit tests or ASan on Android are some examples), allocator_may_return_null
34 // flag value is cached here and can be altered later.
35 bool AllocatorMayReturnNull();
36 void SetAllocatorMayReturnNull(bool may_return_null);
37 
38 // Returns true if allocator detected OOM condition. Can be used to avoid memory
39 // hungry operations.
40 bool IsAllocatorOutOfMemory();
41 // Should be called by a particular allocator when OOM is detected.
42 void SetAllocatorOutOfMemory();
43 
44 void PrintHintAllocatorCannotReturnNull();
45 
46 // Allocators call these callbacks on mmap/munmap.
47 struct NoOpMapUnmapCallback {
48   void OnMap(uptr p, uptr size) const { }
49   void OnUnmap(uptr p, uptr size) const { }
50 };
51 
52 // Callback type for iterating over chunks.
53 typedef void (*ForEachChunkCallback)(uptr chunk, void *arg);
54 
55 INLINE u32 Rand(u32 *state) {  // ANSI C linear congruential PRNG.
56   return (*state = *state * 1103515245 + 12345) >> 16;
57 }
58 
59 INLINE u32 RandN(u32 *state, u32 n) { return Rand(state) % n; }  // [0, n)
60 
61 template<typename T>
62 INLINE void RandomShuffle(T *a, u32 n, u32 *rand_state) {
63   if (n <= 1) return;
64   u32 state = *rand_state;
65   for (u32 i = n - 1; i > 0; i--)
66     Swap(a[i], a[RandN(&state, i + 1)]);
67   *rand_state = state;
68 }
69 
70 #include "sanitizer_allocator_size_class_map.h"
71 #include "sanitizer_allocator_stats.h"
72 #include "sanitizer_allocator_primary64.h"
73 #include "sanitizer_allocator_bytemap.h"
74 #include "sanitizer_allocator_primary32.h"
75 #include "sanitizer_allocator_local_cache.h"
76 #include "sanitizer_allocator_secondary.h"
77 #include "sanitizer_allocator_combined.h"
78 
79 } // namespace __sanitizer
80 
81 #endif // SANITIZER_ALLOCATOR_H
82