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         SetRssLimitExceeded(false);
71       }
72     }
73     if (heap_profile &&
74         current_rss_mb > rss_during_last_reported_profile * 1.1) {
75       Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);
76       __sanitizer_print_memory_profile(90, 20);
77       rss_during_last_reported_profile = current_rss_mb;
78     }
79   }
80 }
81 
82 void MaybeStartBackgroudThread() {
83   // Need to implement/test on other platforms.
84   // Start the background thread if one of the rss limits is given.
85   if (!common_flags()->hard_rss_limit_mb &&
86       !common_flags()->soft_rss_limit_mb &&
87       !common_flags()->heap_profile) return;
88   if (!&real_pthread_create) {
89     VPrintf(1, "%s: real_pthread_create undefined\n", SanitizerToolName);
90     return;  // Can't spawn the thread anyway.
91   }
92 
93   static bool started = false;
94   if (!started) {
95     started = true;
96     internal_start_thread(BackgroundThread, nullptr);
97   }
98 }
99 
100 #  if !SANITIZER_START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
101 #    ifdef __clang__
102 #    pragma clang diagnostic push
103 // We avoid global-constructors to be sure that globals are ready when
104 // sanitizers need them. This can happend before global constructors executed.
105 // Here we don't mind if thread is started on later stages.
106 #    pragma clang diagnostic ignored "-Wglobal-constructors"
107 #    endif
108 static struct BackgroudThreadStarted {
109   BackgroudThreadStarted() { MaybeStartBackgroudThread(); }
110 } background_thread_strarter UNUSED;
111 #    ifdef __clang__
112 #    pragma clang diagnostic pop
113 #    endif
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 #if !SANITIZER_WINDOWS && !SANITIZER_GO
208 // Weak default implementation for when sanitizer_stackdepot is not linked in.
209 SANITIZER_WEAK_ATTRIBUTE void StackDepotStopBackgroundThread() {}
210 static void StopStackDepotBackgroundThread() {
211   StackDepotStopBackgroundThread();
212 }
213 #else
214 // SANITIZER_WEAK_ATTRIBUTE is unsupported.
215 static void StopStackDepotBackgroundThread() {}
216 #endif
217 
218 }  // namespace __sanitizer
219 
220 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
221                              __sanitizer_sandbox_arguments *args) {
222   __sanitizer::StopStackDepotBackgroundThread();
223   __sanitizer::PlatformPrepareForSandboxing(args);
224   if (__sanitizer::sandboxing_callback)
225     __sanitizer::sandboxing_callback();
226 }
227