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