sanitizer_common_libcdep.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. SetRssLimitExceeded(false);
  67. }
  68. }
  69. if (heap_profile &&
  70. current_rss_mb > rss_during_last_reported_profile * 1.1) {
  71. Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);
  72. __sanitizer_print_memory_profile(90, 20);
  73. rss_during_last_reported_profile = current_rss_mb;
  74. }
  75. }
  76. }
  77. void MaybeStartBackgroudThread() {
  78. // Need to implement/test on other platforms.
  79. // Start the background thread if one of the rss limits is given.
  80. if (!common_flags()->hard_rss_limit_mb &&
  81. !common_flags()->soft_rss_limit_mb &&
  82. !common_flags()->heap_profile) return;
  83. if (!&real_pthread_create) {
  84. VPrintf(1, "%s: real_pthread_create undefined\n", SanitizerToolName);
  85. return; // Can't spawn the thread anyway.
  86. }
  87. static bool started = false;
  88. if (!started) {
  89. started = true;
  90. internal_start_thread(BackgroundThread, nullptr);
  91. }
  92. }
  93. # if !SANITIZER_START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
  94. # ifdef __clang__
  95. # pragma clang diagnostic push
  96. // We avoid global-constructors to be sure that globals are ready when
  97. // sanitizers need them. This can happend before global constructors executed.
  98. // Here we don't mind if thread is started on later stages.
  99. # pragma clang diagnostic ignored "-Wglobal-constructors"
  100. # endif
  101. static struct BackgroudThreadStarted {
  102. BackgroudThreadStarted() { MaybeStartBackgroudThread(); }
  103. } background_thread_strarter UNUSED;
  104. # ifdef __clang__
  105. # pragma clang diagnostic pop
  106. # endif
  107. # endif
  108. #else
  109. void MaybeStartBackgroudThread() {}
  110. #endif
  111. void WriteToSyslog(const char *msg) {
  112. InternalScopedString msg_copy;
  113. msg_copy.append("%s", msg);
  114. const char *p = msg_copy.data();
  115. // Print one line at a time.
  116. // syslog, at least on Android, has an implicit message length limit.
  117. while (char* q = internal_strchr(p, '\n')) {
  118. *q = '\0';
  119. WriteOneLineToSyslog(p);
  120. p = q + 1;
  121. }
  122. // Print remaining characters, if there are any.
  123. // Note that this will add an extra newline at the end.
  124. // FIXME: buffer extra output. This would need a thread-local buffer, which
  125. // on Android requires plugging into the tools (ex. ASan's) Thread class.
  126. if (*p)
  127. WriteOneLineToSyslog(p);
  128. }
  129. static void (*sandboxing_callback)();
  130. void SetSandboxingCallback(void (*f)()) {
  131. sandboxing_callback = f;
  132. }
  133. uptr ReservedAddressRange::InitAligned(uptr size, uptr align,
  134. const char *name) {
  135. CHECK(IsPowerOfTwo(align));
  136. if (align <= GetPageSizeCached())
  137. return Init(size, name);
  138. uptr start = Init(size + align, name);
  139. start += align - (start & (align - 1));
  140. return start;
  141. }
  142. #if !SANITIZER_FUCHSIA
  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. void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
  163. uptr zero_base_max_shadow_start) {
  164. if (!size)
  165. return;
  166. void *res = MmapFixedNoAccess(addr, size, "shadow gap");
  167. if (addr == (uptr)res)
  168. return;
  169. // A few pages at the start of the address space can not be protected.
  170. // But we really want to protect as much as possible, to prevent this memory
  171. // being returned as a result of a non-FIXED mmap().
  172. if (addr == zero_base_shadow_start) {
  173. uptr step = GetMmapGranularity();
  174. while (size > step && addr < zero_base_max_shadow_start) {
  175. addr += step;
  176. size -= step;
  177. void *res = MmapFixedNoAccess(addr, size, "shadow gap");
  178. if (addr == (uptr)res)
  179. return;
  180. }
  181. }
  182. Report(
  183. "ERROR: Failed to protect the shadow gap. "
  184. "%s cannot proceed correctly. ABORTING.\n",
  185. SanitizerToolName);
  186. DumpProcessMap();
  187. Die();
  188. }
  189. #endif // !SANITIZER_FUCHSIA
  190. #if !SANITIZER_WINDOWS && !SANITIZER_GO
  191. // Weak default implementation for when sanitizer_stackdepot is not linked in.
  192. SANITIZER_WEAK_ATTRIBUTE void StackDepotStopBackgroundThread() {}
  193. static void StopStackDepotBackgroundThread() {
  194. StackDepotStopBackgroundThread();
  195. }
  196. #else
  197. // SANITIZER_WEAK_ATTRIBUTE is unsupported.
  198. static void StopStackDepotBackgroundThread() {}
  199. #endif
  200. } // namespace __sanitizer
  201. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
  202. __sanitizer_sandbox_arguments *args) {
  203. __sanitizer::StopStackDepotBackgroundThread();
  204. __sanitizer::PlatformPrepareForSandboxing(args);
  205. if (__sanitizer::sandboxing_callback)
  206. __sanitizer::sandboxing_callback();
  207. }