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