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