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 #    pragma clang diagnostic push
102 // We avoid global-constructors to be sure that globals are ready when
103 // sanitizers need them. This can happend before global constructors executed.
104 // Here we don't mind if thread is started on later stages.
105 #    pragma clang diagnostic ignored "-Wglobal-constructors"
106 static struct BackgroudThreadStarted {
107   BackgroudThreadStarted() { MaybeStartBackgroudThread(); }
108 } background_thread_strarter UNUSED;
109 #    pragma clang diagnostic pop
110 #  endif
111 #else
112 void MaybeStartBackgroudThread() {}
113 #endif
114 
115 void WriteToSyslog(const char *msg) {
116   InternalScopedString msg_copy;
117   msg_copy.append("%s", msg);
118   const char *p = msg_copy.data();
119 
120   // Print one line at a time.
121   // syslog, at least on Android, has an implicit message length limit.
122   while (char* q = internal_strchr(p, '\n')) {
123     *q = '\0';
124     WriteOneLineToSyslog(p);
125     p = q + 1;
126   }
127   // Print remaining characters, if there are any.
128   // Note that this will add an extra newline at the end.
129   // FIXME: buffer extra output. This would need a thread-local buffer, which
130   // on Android requires plugging into the tools (ex. ASan's) Thread class.
131   if (*p)
132     WriteOneLineToSyslog(p);
133 }
134 
135 static void (*sandboxing_callback)();
136 void SetSandboxingCallback(void (*f)()) {
137   sandboxing_callback = f;
138 }
139 
140 uptr ReservedAddressRange::InitAligned(uptr size, uptr align,
141                                        const char *name) {
142   CHECK(IsPowerOfTwo(align));
143   if (align <= GetPageSizeCached())
144     return Init(size, name);
145   uptr start = Init(size + align, name);
146   start += align - (start & (align - 1));
147   return start;
148 }
149 
150 #if !SANITIZER_FUCHSIA
151 
152 // Reserve memory range [beg, end].
153 // We need to use inclusive range because end+1 may not be representable.
154 void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,
155                               bool madvise_shadow) {
156   CHECK_EQ((beg % GetMmapGranularity()), 0);
157   CHECK_EQ(((end + 1) % GetMmapGranularity()), 0);
158   uptr size = end - beg + 1;
159   DecreaseTotalMmap(size);  // Don't count the shadow against mmap_limit_mb.
160   if (madvise_shadow ? !MmapFixedSuperNoReserve(beg, size, name)
161                      : !MmapFixedNoReserve(beg, size, name)) {
162     Report(
163         "ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
164         "Perhaps you're using ulimit -v\n",
165         size);
166     Abort();
167   }
168   if (madvise_shadow && common_flags()->use_madv_dontdump)
169     DontDumpShadowMemory(beg, size);
170 }
171 
172 void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
173                 uptr zero_base_max_shadow_start) {
174   if (!size)
175     return;
176   void *res = MmapFixedNoAccess(addr, size, "shadow gap");
177   if (addr == (uptr)res)
178     return;
179   // A few pages at the start of the address space can not be protected.
180   // But we really want to protect as much as possible, to prevent this memory
181   // being returned as a result of a non-FIXED mmap().
182   if (addr == zero_base_shadow_start) {
183     uptr step = GetMmapGranularity();
184     while (size > step && addr < zero_base_max_shadow_start) {
185       addr += step;
186       size -= step;
187       void *res = MmapFixedNoAccess(addr, size, "shadow gap");
188       if (addr == (uptr)res)
189         return;
190     }
191   }
192 
193   Report(
194       "ERROR: Failed to protect the shadow gap. "
195       "%s cannot proceed correctly. ABORTING.\n",
196       SanitizerToolName);
197   DumpProcessMap();
198   Die();
199 }
200 
201 #endif  // !SANITIZER_FUCHSIA
202 
203 #if !SANITIZER_WINDOWS && !SANITIZER_GO
204 // Weak default implementation for when sanitizer_stackdepot is not linked in.
205 SANITIZER_WEAK_ATTRIBUTE void StackDepotStopBackgroundThread() {}
206 static void StopStackDepotBackgroundThread() {
207   StackDepotStopBackgroundThread();
208 }
209 #else
210 // SANITIZER_WEAK_ATTRIBUTE is unsupported.
211 static void StopStackDepotBackgroundThread() {}
212 #endif
213 
214 }  // namespace __sanitizer
215 
216 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
217                              __sanitizer_sandbox_arguments *args) {
218   __sanitizer::StopStackDepotBackgroundThread();
219   __sanitizer::PlatformPrepareForSandboxing(args);
220   if (__sanitizer::sandboxing_callback)
221     __sanitizer::sandboxing_callback();
222 }
223