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