sanitizer_common_libcdep.cpp 8.2 KB

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