xref: /llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_libcdep.cpp (revision e5c2a46c5e8fc038b9f6c898df9628f9524dc10e)
1 //===-- sanitizer_common_libcdep.cpp --------------------------------------===//
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 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries.
11 //===----------------------------------------------------------------------===//
12 
13 #include "sanitizer_allocator.h"
14 #include "sanitizer_allocator_interface.h"
15 #include "sanitizer_common.h"
16 #include "sanitizer_flags.h"
17 #include "sanitizer_procmaps.h"
18 #include "sanitizer_stackdepot.h"
19 
20 namespace __sanitizer {
21 
22 // Weak default implementation for when sanitizer_stackdepot is not linked in.
23 #if !SANITIZER_GO
24 SANITIZER_WEAK_ATTRIBUTE void StackDepotStopBackgroundThread() {}
25 #endif
26 
27 #if (SANITIZER_LINUX || SANITIZER_NETBSD) && !SANITIZER_GO
28 // Weak default implementation for when sanitizer_stackdepot is not linked in.
29 SANITIZER_WEAK_ATTRIBUTE StackDepotStats StackDepotGetStats() { return {}; }
30 
31 void *BackgroundThread(void *arg) {
32   VPrintf(1, "%s: Started BackgroundThread\n", SanitizerToolName);
33   const uptr hard_rss_limit_mb = common_flags()->hard_rss_limit_mb;
34   const uptr soft_rss_limit_mb = common_flags()->soft_rss_limit_mb;
35   const bool heap_profile = common_flags()->heap_profile;
36   uptr prev_reported_rss = 0;
37   uptr prev_reported_stack_depot_size = 0;
38   bool reached_soft_rss_limit = false;
39   uptr rss_during_last_reported_profile = 0;
40   while (true) {
41     SleepForMillis(100);
42     const uptr current_rss_mb = GetRSS() >> 20;
43     if (Verbosity()) {
44       // If RSS has grown 10% since last time, print some information.
45       if (prev_reported_rss * 11 / 10 < current_rss_mb) {
46         Printf("%s: RSS: %zdMb\n", SanitizerToolName, current_rss_mb);
47         prev_reported_rss = current_rss_mb;
48       }
49       // If stack depot has grown 10% since last time, print it too.
50       StackDepotStats stack_depot_stats = StackDepotGetStats();
51       if (prev_reported_stack_depot_size * 11 / 10 <
52           stack_depot_stats.allocated) {
53         Printf("%s: StackDepot: %zd ids; %zdM allocated\n", SanitizerToolName,
54                stack_depot_stats.n_uniq_ids, stack_depot_stats.allocated >> 20);
55         prev_reported_stack_depot_size = stack_depot_stats.allocated;
56       }
57     }
58     // Check RSS against the limit.
59     if (hard_rss_limit_mb && hard_rss_limit_mb < current_rss_mb) {
60       Report("%s: hard rss limit exhausted (%zdMb vs %zdMb)\n",
61              SanitizerToolName, hard_rss_limit_mb, current_rss_mb);
62       DumpProcessMap();
63       Die();
64     }
65     if (soft_rss_limit_mb) {
66       if (soft_rss_limit_mb < current_rss_mb && !reached_soft_rss_limit) {
67         reached_soft_rss_limit = true;
68         Report("%s: soft rss limit exhausted (%zdMb vs %zdMb)\n",
69                SanitizerToolName, soft_rss_limit_mb, current_rss_mb);
70         SetRssLimitExceeded(true);
71       } else if (soft_rss_limit_mb >= current_rss_mb &&
72                  reached_soft_rss_limit) {
73         reached_soft_rss_limit = false;
74         SetRssLimitExceeded(false);
75       }
76     }
77     if (heap_profile &&
78         current_rss_mb > rss_during_last_reported_profile * 1.1) {
79       Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);
80       __sanitizer_print_memory_profile(90, 20);
81       rss_during_last_reported_profile = current_rss_mb;
82     }
83   }
84 }
85 
86 void MaybeStartBackgroudThread() {
87   // Need to implement/test on other platforms.
88   // Start the background thread if one of the rss limits is given.
89   if (!common_flags()->hard_rss_limit_mb &&
90       !common_flags()->soft_rss_limit_mb &&
91       !common_flags()->heap_profile) return;
92   if (!&real_pthread_create) {
93     VPrintf(1, "%s: real_pthread_create undefined\n", SanitizerToolName);
94     return;  // Can't spawn the thread anyway.
95   }
96 
97   static bool started = false;
98   if (!started) {
99     started = true;
100     internal_start_thread(BackgroundThread, nullptr);
101   }
102 }
103 
104 #  if !SANITIZER_START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
105 #    pragma clang diagnostic push
106 // We avoid global-constructors to be sure that globals are ready when
107 // sanitizers need them. This can happend before global constructors executed.
108 // Here we don't mind if thread is started on later stages.
109 #    pragma clang diagnostic ignored "-Wglobal-constructors"
110 static struct BackgroudThreadStarted {
111   BackgroudThreadStarted() { MaybeStartBackgroudThread(); }
112 } background_thread_strarter UNUSED;
113 #    pragma clang diagnostic pop
114 #  endif
115 #else
116 void MaybeStartBackgroudThread() {}
117 #endif
118 
119 void WriteToSyslog(const char *msg) {
120   InternalScopedString msg_copy;
121   msg_copy.append("%s", msg);
122   const char *p = msg_copy.data();
123 
124   // Print one line at a time.
125   // syslog, at least on Android, has an implicit message length limit.
126   while (char* q = internal_strchr(p, '\n')) {
127     *q = '\0';
128     WriteOneLineToSyslog(p);
129     p = q + 1;
130   }
131   // Print remaining characters, if there are any.
132   // Note that this will add an extra newline at the end.
133   // FIXME: buffer extra output. This would need a thread-local buffer, which
134   // on Android requires plugging into the tools (ex. ASan's) Thread class.
135   if (*p)
136     WriteOneLineToSyslog(p);
137 }
138 
139 static void (*sandboxing_callback)();
140 void SetSandboxingCallback(void (*f)()) {
141   sandboxing_callback = f;
142 }
143 
144 uptr ReservedAddressRange::InitAligned(uptr size, uptr align,
145                                        const char *name) {
146   CHECK(IsPowerOfTwo(align));
147   if (align <= GetPageSizeCached())
148     return Init(size, name);
149   uptr start = Init(size + align, name);
150   start += align - (start & (align - 1));
151   return start;
152 }
153 
154 #if !SANITIZER_FUCHSIA
155 
156 // Reserve memory range [beg, end].
157 // We need to use inclusive range because end+1 may not be representable.
158 void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,
159                               bool madvise_shadow) {
160   CHECK_EQ((beg % GetMmapGranularity()), 0);
161   CHECK_EQ(((end + 1) % GetMmapGranularity()), 0);
162   uptr size = end - beg + 1;
163   DecreaseTotalMmap(size);  // Don't count the shadow against mmap_limit_mb.
164   if (madvise_shadow ? !MmapFixedSuperNoReserve(beg, size, name)
165                      : !MmapFixedNoReserve(beg, size, name)) {
166     Report(
167         "ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
168         "Perhaps you're using ulimit -v\n",
169         size);
170     Abort();
171   }
172   if (madvise_shadow && common_flags()->use_madv_dontdump)
173     DontDumpShadowMemory(beg, size);
174 }
175 
176 void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
177                 uptr zero_base_max_shadow_start) {
178   if (!size)
179     return;
180   void *res = MmapFixedNoAccess(addr, size, "shadow gap");
181   if (addr == (uptr)res)
182     return;
183   // A few pages at the start of the address space can not be protected.
184   // But we really want to protect as much as possible, to prevent this memory
185   // being returned as a result of a non-FIXED mmap().
186   if (addr == zero_base_shadow_start) {
187     uptr step = GetMmapGranularity();
188     while (size > step && addr < zero_base_max_shadow_start) {
189       addr += step;
190       size -= step;
191       void *res = MmapFixedNoAccess(addr, size, "shadow gap");
192       if (addr == (uptr)res)
193         return;
194     }
195   }
196 
197   Report(
198       "ERROR: Failed to protect the shadow gap. "
199       "%s cannot proceed correctly. ABORTING.\n",
200       SanitizerToolName);
201   DumpProcessMap();
202   Die();
203 }
204 
205 #endif  // !SANITIZER_FUCHSIA
206 
207 }  // namespace __sanitizer
208 
209 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
210                              __sanitizer_sandbox_arguments *args) {
211   __sanitizer::StackDepotStopBackgroundThread();
212   __sanitizer::PlatformPrepareForSandboxing(args);
213   if (__sanitizer::sandboxing_callback)
214     __sanitizer::sandboxing_callback();
215 }
216