sanitizer_common_libcdep.cpp 7.9 KB

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