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