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