Bug Summary

File:compiler-rt/lib/tsan/rtl/tsan_rtl.h
Warning:line 954, column 3
Called C++ object pointer is uninitialized

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name tsan_rtl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -target-feature +sse4.2 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/tsan -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/tsan -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/.. -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-format-pedantic -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/tsan -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp

1//===-- tsan_rtl.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 a part of ThreadSanitizer (TSan), a race detector.
10//
11// Main file (entry points) for the TSan run-time.
12//===----------------------------------------------------------------------===//
13
14#include "tsan_rtl.h"
15
16#include "sanitizer_common/sanitizer_atomic.h"
17#include "sanitizer_common/sanitizer_common.h"
18#include "sanitizer_common/sanitizer_file.h"
19#include "sanitizer_common/sanitizer_libc.h"
20#include "sanitizer_common/sanitizer_placement_new.h"
21#include "sanitizer_common/sanitizer_stackdepot.h"
22#include "sanitizer_common/sanitizer_symbolizer.h"
23#include "tsan_defs.h"
24#include "tsan_interface.h"
25#include "tsan_mman.h"
26#include "tsan_platform.h"
27#include "tsan_suppressions.h"
28#include "tsan_symbolize.h"
29#include "ubsan/ubsan_init.h"
30
31volatile int __tsan_resumed = 0;
32
33extern "C" void __tsan_resume() {
34 __tsan_resumed = 1;
35}
36
37namespace __tsan {
38
39#if !SANITIZER_GO0 && !SANITIZER_MAC0
40__attribute__((tls_model("initial-exec")))
41THREADLOCAL__thread char cur_thread_placeholder[sizeof(ThreadState)] ALIGNED(64)__attribute__((aligned(64)));
42#endif
43static char ctx_placeholder[sizeof(Context)] ALIGNED(64)__attribute__((aligned(64)));
44Context *ctx;
45
46// Can be overriden by a front-end.
47#ifdef TSAN_EXTERNAL_HOOKS
48bool OnFinalize(bool failed);
49void OnInitialize();
50#else
51#include <dlfcn.h>
52SANITIZER_WEAK_CXX_DEFAULT_IMPLextern "C++" __attribute__((visibility("default"))) __attribute__
((weak)) __attribute__((noinline))
53bool OnFinalize(bool failed) {
54#if !SANITIZER_GO0
55 if (auto *ptr = dlsym(RTLD_DEFAULT((void *) 0), "__tsan_on_finalize"))
56 return reinterpret_cast<decltype(&__tsan_on_finalize)>(ptr)(failed);
57#endif
58 return failed;
59}
60SANITIZER_WEAK_CXX_DEFAULT_IMPLextern "C++" __attribute__((visibility("default"))) __attribute__
((weak)) __attribute__((noinline))
61void OnInitialize() {
62#if !SANITIZER_GO0
63 if (auto *ptr = dlsym(RTLD_DEFAULT((void *) 0), "__tsan_on_initialize")) {
64 return reinterpret_cast<decltype(&__tsan_on_initialize)>(ptr)();
65 }
66#endif
67}
68#endif
69
70static ThreadContextBase *CreateThreadContext(Tid tid) {
71 // Map thread trace when context is created.
72 char name[50];
73 internal_snprintf(name, sizeof(name), "trace %u", tid);
74 MapThreadTrace(GetThreadTrace(tid), TraceSize() * sizeof(Event), name);
75 const uptr hdr = GetThreadTraceHeader(tid);
76 internal_snprintf(name, sizeof(name), "trace header %u", tid);
77 MapThreadTrace(hdr, sizeof(Trace), name);
78 new((void*)hdr) Trace();
79 // We are going to use only a small part of the trace with the default
80 // value of history_size. However, the constructor writes to the whole trace.
81 // Release the unused part.
82 uptr hdr_end = hdr + sizeof(Trace);
83 hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
84 hdr_end = RoundUp(hdr_end, GetPageSizeCached());
85 if (hdr_end < hdr + sizeof(Trace)) {
86 ReleaseMemoryPagesToOS(hdr_end, hdr + sizeof(Trace));
87 uptr unused = hdr + sizeof(Trace) - hdr_end;
88 if (hdr_end != (uptr)MmapFixedNoAccess(hdr_end, unused)) {
89 Report("ThreadSanitizer: failed to mprotect [0x%zx-0x%zx) \n", hdr_end,
90 unused);
91 CHECK("unable to mprotect" && 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)(("unable to mprotect"
&& 0)); __sanitizer::u64 v2 = (__sanitizer::u64)(0);
if (__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 91, "(" "(\"unable to mprotect\" && 0)" ") " "!=" " ("
"0" ")", v1, v2); } while (false)
;
92 }
93 }
94 return New<ThreadContext>(tid);
95}
96
97#if !SANITIZER_GO0
98static const u32 kThreadQuarantineSize = 16;
99#else
100static const u32 kThreadQuarantineSize = 64;
101#endif
102
103Context::Context()
104 : initialized(),
105 report_mtx(MutexTypeReport),
106 nreported(),
107 nmissed_expected(),
108 thread_registry(CreateThreadContext, kMaxTid, kThreadQuarantineSize,
109 kMaxTidReuse),
110 racy_mtx(MutexTypeRacy),
111 racy_stacks(),
112 racy_addresses(),
113 fired_suppressions_mtx(MutexTypeFired),
114 clock_alloc(LINKER_INITIALIZED, "clock allocator") {
115 fired_suppressions.reserve(8);
116}
117
118// The objects are allocated in TLS, so one may rely on zero-initialization.
119ThreadState::ThreadState(Context *ctx, Tid tid, int unique_id, u64 epoch,
120 unsigned reuse_count, uptr stk_addr, uptr stk_size,
121 uptr tls_addr, uptr tls_size)
122 : fast_state(tid, epoch)
123 // Do not touch these, rely on zero initialization,
124 // they may be accessed before the ctor.
125 // , ignore_reads_and_writes()
126 // , ignore_interceptors()
127 ,
128 clock(tid, reuse_count)
129#if !SANITIZER_GO0
130 ,
131 jmp_bufs()
132#endif
133 ,
134 tid(tid),
135 unique_id(unique_id),
136 stk_addr(stk_addr),
137 stk_size(stk_size),
138 tls_addr(tls_addr),
139 tls_size(tls_size)
140#if !SANITIZER_GO0
141 ,
142 last_sleep_clock(tid)
143#endif
144{
145}
146
147#if !SANITIZER_GO0
148static void MemoryProfiler(Context *ctx, fd_t fd, int i) {
149 uptr n_threads;
150 uptr n_running_threads;
151 ctx->thread_registry.GetNumberOfThreads(&n_threads, &n_running_threads);
152 InternalMmapVector<char> buf(4096);
153 WriteMemoryProfile(buf.data(), buf.size(), n_threads, n_running_threads);
154 WriteToFile(fd, buf.data(), internal_strlen(buf.data()));
155}
156
157static void *BackgroundThread(void *arg) {
158 // This is a non-initialized non-user thread, nothing to see here.
159 // We don't use ScopedIgnoreInterceptors, because we want ignores to be
160 // enabled even when the thread function exits (e.g. during pthread thread
161 // shutdown code).
162 cur_thread_init();
163 cur_thread()->ignore_interceptors++;
164 const u64 kMs2Ns = 1000 * 1000;
165
166 fd_t mprof_fd = kInvalidFd((fd_t)-1);
167 if (flags()->profile_memory && flags()->profile_memory[0]) {
168 if (internal_strcmp(flags()->profile_memory, "stdout") == 0) {
169 mprof_fd = 1;
170 } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
171 mprof_fd = 2;
172 } else {
173 InternalScopedString filename;
174 filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
175 fd_t fd = OpenFile(filename.data(), WrOnly);
176 if (fd == kInvalidFd((fd_t)-1)) {
177 Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
178 filename.data());
179 } else {
180 mprof_fd = fd;
181 }
182 }
183 }
184
185 u64 last_flush = NanoTime();
186 uptr last_rss = 0;
187 for (int i = 0;
188 atomic_load(&ctx->stop_background_thread, memory_order_relaxed) == 0;
189 i++) {
190 SleepForMillis(100);
191 u64 now = NanoTime();
192
193 // Flush memory if requested.
194 if (flags()->flush_memory_ms > 0) {
195 if (last_flush + flags()->flush_memory_ms * kMs2Ns < now) {
196 VPrintf(1, "ThreadSanitizer: periodic memory flush\n")do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: periodic memory flush\n"
); } while (0)
;
197 FlushShadowMemory();
198 last_flush = NanoTime();
199 }
200 }
201 // GetRSS can be expensive on huge programs, so don't do it every 100ms.
202 if (flags()->memory_limit_mb > 0) {
203 uptr rss = GetRSS();
204 uptr limit = uptr(flags()->memory_limit_mb) << 20;
205 VPrintf(1, "ThreadSanitizer: memory flush check"do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: memory flush check"
" RSS=%llu LAST=%llu LIMIT=%llu\n", (u64)rss >> 20, (u64
)last_rss >> 20, (u64)limit >> 20); } while (0)
206 " RSS=%llu LAST=%llu LIMIT=%llu\n",do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: memory flush check"
" RSS=%llu LAST=%llu LIMIT=%llu\n", (u64)rss >> 20, (u64
)last_rss >> 20, (u64)limit >> 20); } while (0)
207 (u64)rss >> 20, (u64)last_rss >> 20, (u64)limit >> 20)do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: memory flush check"
" RSS=%llu LAST=%llu LIMIT=%llu\n", (u64)rss >> 20, (u64
)last_rss >> 20, (u64)limit >> 20); } while (0)
;
208 if (2 * rss > limit + last_rss) {
209 VPrintf(1, "ThreadSanitizer: flushing memory due to RSS\n")do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: flushing memory due to RSS\n"
); } while (0)
;
210 FlushShadowMemory();
211 rss = GetRSS();
212 VPrintf(1, "ThreadSanitizer: memory flushed RSS=%llu\n", (u64)rss>>20)do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: memory flushed RSS=%llu\n"
, (u64)rss>>20); } while (0)
;
213 }
214 last_rss = rss;
215 }
216
217 // Write memory profile if requested.
218 if (mprof_fd != kInvalidFd((fd_t)-1))
219 MemoryProfiler(ctx, mprof_fd, i);
220
221 // Flush symbolizer cache if requested.
222 if (flags()->flush_symbolizer_ms > 0) {
223 u64 last = atomic_load(&ctx->last_symbolize_time_ns,
224 memory_order_relaxed);
225 if (last != 0 && last + flags()->flush_symbolizer_ms * kMs2Ns < now) {
226 Lock l(&ctx->report_mtx);
227 ScopedErrorReportLock l2;
228 SymbolizeFlush();
229 atomic_store(&ctx->last_symbolize_time_ns, 0, memory_order_relaxed);
230 }
231 }
232 }
233 return nullptr;
234}
235
236static void StartBackgroundThread() {
237 ctx->background_thread = internal_start_thread(&BackgroundThread, 0);
238}
239
240#ifndef __mips__
241static void StopBackgroundThread() {
242 atomic_store(&ctx->stop_background_thread, 1, memory_order_relaxed);
243 internal_join_thread(ctx->background_thread);
244 ctx->background_thread = 0;
245}
246#endif
247#endif
248
249void DontNeedShadowFor(uptr addr, uptr size) {
250 ReleaseMemoryPagesToOS(reinterpret_cast<uptr>(MemToShadow(addr)),
251 reinterpret_cast<uptr>(MemToShadow(addr + size)));
252}
253
254#if !SANITIZER_GO0
255void UnmapShadow(ThreadState *thr, uptr addr, uptr size) {
256 if (size == 0) return;
257 DontNeedShadowFor(addr, size);
258 ScopedGlobalProcessor sgp;
259 ctx->metamap.ResetRange(thr->proc(), addr, size);
260}
261#endif
262
263void MapShadow(uptr addr, uptr size) {
264 // Global data is not 64K aligned, but there are no adjacent mappings,
265 // so we can get away with unaligned mapping.
266 // CHECK_EQ(addr, addr & ~((64 << 10) - 1)); // windows wants 64K alignment
267 const uptr kPageSize = GetPageSizeCached();
268 uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
269 uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
270 if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
271 "shadow"))
272 Die();
273
274 // Meta shadow is 2:1, so tread carefully.
275 static bool data_mapped = false;
276 static uptr mapped_meta_end = 0;
277 uptr meta_begin = (uptr)MemToMeta(addr);
278 uptr meta_end = (uptr)MemToMeta(addr + size);
279 meta_begin = RoundDownTo(meta_begin, 64 << 10);
280 meta_end = RoundUpTo(meta_end, 64 << 10);
281 if (!data_mapped) {
282 // First call maps data+bss.
283 data_mapped = true;
284 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
285 "meta shadow"))
286 Die();
287 } else {
288 // Mapping continous heap.
289 // Windows wants 64K alignment.
290 meta_begin = RoundDownTo(meta_begin, 64 << 10);
291 meta_end = RoundUpTo(meta_end, 64 << 10);
292 if (meta_end <= mapped_meta_end)
293 return;
294 if (meta_begin < mapped_meta_end)
295 meta_begin = mapped_meta_end;
296 if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
297 "meta shadow"))
298 Die();
299 mapped_meta_end = meta_end;
300 }
301 VPrintf(2, "mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n", addr,do { if ((uptr)Verbosity() >= (2)) Printf("mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n"
, addr, addr + size, meta_begin, meta_end); } while (0)
302 addr + size, meta_begin, meta_end)do { if ((uptr)Verbosity() >= (2)) Printf("mapped meta shadow for (0x%zx-0x%zx) at (0x%zx-0x%zx)\n"
, addr, addr + size, meta_begin, meta_end); } while (0)
;
303}
304
305void MapThreadTrace(uptr addr, uptr size, const char *name) {
306 DPrintf("#0: Mapping trace at %p-%p(0x%zx)\n", addr, addr + size, size);
307 CHECK_GE(addr, TraceMemBeg())do { __sanitizer::u64 v1 = (__sanitizer::u64)((addr)); __sanitizer
::u64 v2 = (__sanitizer::u64)((TraceMemBeg())); if (__builtin_expect
(!!(!(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 307, "(" "(addr)" ") " ">=" " (" "(TraceMemBeg())" ")", v1
, v2); } while (false)
;
308 CHECK_LE(addr + size, TraceMemEnd())do { __sanitizer::u64 v1 = (__sanitizer::u64)((addr + size));
__sanitizer::u64 v2 = (__sanitizer::u64)((TraceMemEnd())); if
(__builtin_expect(!!(!(v1 <= v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 308, "(" "(addr + size)" ") " "<=" " (" "(TraceMemEnd())"
")", v1, v2); } while (false)
;
309 CHECK_EQ(addr, addr & ~((64 << 10) - 1))do { __sanitizer::u64 v1 = (__sanitizer::u64)((addr)); __sanitizer
::u64 v2 = (__sanitizer::u64)((addr & ~((64 << 10) -
1))); if (__builtin_expect(!!(!(v1 == v2)), 0)) __sanitizer::
CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 309, "(" "(addr)" ") " "==" " (" "(addr & ~((64 << 10) - 1))"
")", v1, v2); } while (false)
; // windows wants 64K alignment
310 if (!MmapFixedSuperNoReserve(addr, size, name)) {
311 Printf("FATAL: ThreadSanitizer can not mmap thread trace (0x%zx/0x%zx)\n",
312 addr, size);
313 Die();
314 }
315}
316
317#if !SANITIZER_GO0
318static void OnStackUnwind(const SignalContext &sig, const void *,
319 BufferedStackTrace *stack) {
320 stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
321 common_flags()->fast_unwind_on_fatal);
322}
323
324static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
325 HandleDeadlySignal(siginfo, context, GetTid(), &OnStackUnwind, nullptr);
326}
327#endif
328
329void CheckUnwind() {
330 // There is high probability that interceptors will check-fail as well,
331 // on the other hand there is no sense in processing interceptors
332 // since we are going to die soon.
333 ScopedIgnoreInterceptors ignore;
334#if !SANITIZER_GO0
335 cur_thread()->ignore_sync++;
336 cur_thread()->ignore_reads_and_writes++;
337#endif
338 PrintCurrentStackSlow(StackTrace::GetCurrentPc());
339}
340
341bool is_initialized;
342
343void Initialize(ThreadState *thr) {
344 // Thread safe because done before all threads exist.
345 if (is_initialized)
346 return;
347 is_initialized = true;
348 // We are not ready to handle interceptors yet.
349 ScopedIgnoreInterceptors ignore;
350 SanitizerToolName = "ThreadSanitizer";
351 // Install tool-specific callbacks in sanitizer_common.
352 SetCheckUnwindCallback(CheckUnwind);
353
354 ctx = new(ctx_placeholder) Context;
355 const char *env_name = SANITIZER_GO0 ? "GORACE" : "TSAN_OPTIONS";
356 const char *options = GetEnv(env_name);
357 CacheBinaryName();
358 CheckASLR();
359 InitializeFlags(&ctx->flags, options, env_name);
360 AvoidCVE_2016_2143();
361 __sanitizer::InitializePlatformEarly();
362 __tsan::InitializePlatformEarly();
363
364#if !SANITIZER_GO0
365 // Re-exec ourselves if we need to set additional env or command line args.
366 MaybeReexec();
367
368 InitializeAllocator();
369 ReplaceSystemMalloc();
370#endif
371 if (common_flags()->detect_deadlocks)
372 ctx->dd = DDetector::Create(flags());
373 Processor *proc = ProcCreate();
374 ProcWire(proc, thr);
375 InitializeInterceptors();
376 InitializePlatform();
377 InitializeDynamicAnnotations();
378#if !SANITIZER_GO0
379 InitializeShadowMemory();
380 InitializeAllocatorLate();
381 InstallDeadlySignalHandlers(TsanOnDeadlySignal);
382#endif
383 // Setup correct file descriptor for error reports.
384 __sanitizer_set_report_path(common_flags()->log_path);
385 InitializeSuppressions();
386#if !SANITIZER_GO0
387 InitializeLibIgnore();
388 Symbolizer::GetOrInit()->AddHooks(EnterSymbolizer, ExitSymbolizer);
389#endif
390
391 VPrintf(1, "***** Running under ThreadSanitizer v2 (pid %d) *****\n",do { if ((uptr)Verbosity() >= (1)) Printf("***** Running under ThreadSanitizer v2 (pid %d) *****\n"
, (int)internal_getpid()); } while (0)
392 (int)internal_getpid())do { if ((uptr)Verbosity() >= (1)) Printf("***** Running under ThreadSanitizer v2 (pid %d) *****\n"
, (int)internal_getpid()); } while (0)
;
393
394 // Initialize thread 0.
395 Tid tid = ThreadCreate(thr, 0, 0, true);
396 CHECK_EQ(tid, kMainTid)do { __sanitizer::u64 v1 = (__sanitizer::u64)((tid)); __sanitizer
::u64 v2 = (__sanitizer::u64)((kMainTid)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 396, "(" "(tid)" ") " "==" " (" "(kMainTid)" ")", v1, v2); }
while (false)
;
397 ThreadStart(thr, tid, GetTid(), ThreadType::Regular);
398#if TSAN_CONTAINS_UBSAN1
399 __ubsan::InitAsPlugin();
400#endif
401 ctx->initialized = true;
402
403#if !SANITIZER_GO0
404 Symbolizer::LateInitialize();
405#endif
406
407 if (flags()->stop_on_start) {
408 Printf("ThreadSanitizer is suspended at startup (pid %d)."
409 " Call __tsan_resume().\n",
410 (int)internal_getpid());
411 while (__tsan_resumed == 0) {}
412 }
413
414 OnInitialize();
415}
416
417void MaybeSpawnBackgroundThread() {
418 // On MIPS, TSan initialization is run before
419 // __pthread_initialize_minimal_internal() is finished, so we can not spawn
420 // new threads.
421#if !SANITIZER_GO0 && !defined(__mips__)
422 static atomic_uint32_t bg_thread = {};
423 if (atomic_load(&bg_thread, memory_order_relaxed) == 0 &&
424 atomic_exchange(&bg_thread, 1, memory_order_relaxed) == 0) {
425 StartBackgroundThread();
426 SetSandboxingCallback(StopBackgroundThread);
427 }
428#endif
429}
430
431
432int Finalize(ThreadState *thr) {
433 bool failed = false;
434
435 if (common_flags()->print_module_map == 1)
436 DumpProcessMap();
437
438 if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
439 SleepForMillis(flags()->atexit_sleep_ms);
440
441 // Wait for pending reports.
442 ctx->report_mtx.Lock();
443 { ScopedErrorReportLock l; }
444 ctx->report_mtx.Unlock();
445
446#if !SANITIZER_GO0
447 if (Verbosity()) AllocatorPrintStats();
448#endif
449
450 ThreadFinalize(thr);
451
452 if (ctx->nreported) {
453 failed = true;
454#if !SANITIZER_GO0
455 Printf("ThreadSanitizer: reported %d warnings\n", ctx->nreported);
456#else
457 Printf("Found %d data race(s)\n", ctx->nreported);
458#endif
459 }
460
461 if (ctx->nmissed_expected) {
462 failed = true;
463 Printf("ThreadSanitizer: missed %d expected races\n",
464 ctx->nmissed_expected);
465 }
466
467 if (common_flags()->print_suppressions)
468 PrintMatchedSuppressions();
469
470 failed = OnFinalize(failed);
471
472 return failed ? common_flags()->exitcode : 0;
473}
474
475#if !SANITIZER_GO0
476void ForkBefore(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS__attribute__((no_thread_safety_analysis)) {
477 ctx->thread_registry.Lock();
478 ctx->report_mtx.Lock();
479 ScopedErrorReportLock::Lock();
480 // Suppress all reports in the pthread_atfork callbacks.
481 // Reports will deadlock on the report_mtx.
482 // We could ignore sync operations as well,
483 // but so far it's unclear if it will do more good or harm.
484 // Unnecessarily ignoring things can lead to false positives later.
485 thr->suppress_reports++;
486 // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
487 // we'll assert in CheckNoLocks() unless we ignore interceptors.
488 thr->ignore_interceptors++;
489}
490
491void ForkParentAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS__attribute__((no_thread_safety_analysis)) {
492 thr->suppress_reports--; // Enabled in ForkBefore.
493 thr->ignore_interceptors--;
494 ScopedErrorReportLock::Unlock();
495 ctx->report_mtx.Unlock();
496 ctx->thread_registry.Unlock();
497}
498
499void ForkChildAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS__attribute__((no_thread_safety_analysis)) {
500 thr->suppress_reports--; // Enabled in ForkBefore.
501 thr->ignore_interceptors--;
502 ScopedErrorReportLock::Unlock();
503 ctx->report_mtx.Unlock();
504 ctx->thread_registry.Unlock();
505
506 uptr nthread = 0;
507 ctx->thread_registry.GetNumberOfThreads(0, 0, &nthread /* alive threads */);
508 VPrintf(1, "ThreadSanitizer: forked new process with pid %d,"do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: forked new process with pid %d,"
" parent had %d threads\n", (int)internal_getpid(), (int)nthread
); } while (0)
509 " parent had %d threads\n", (int)internal_getpid(), (int)nthread)do { if ((uptr)Verbosity() >= (1)) Printf("ThreadSanitizer: forked new process with pid %d,"
" parent had %d threads\n", (int)internal_getpid(), (int)nthread
); } while (0)
;
510 if (nthread == 1) {
511 StartBackgroundThread();
512 } else {
513 // We've just forked a multi-threaded process. We cannot reasonably function
514 // after that (some mutexes may be locked before fork). So just enable
515 // ignores for everything in the hope that we will exec soon.
516 ctx->after_multithreaded_fork = true;
517 thr->ignore_interceptors++;
518 ThreadIgnoreBegin(thr, pc);
519 ThreadIgnoreSyncBegin(thr, pc);
520 }
521}
522#endif
523
524#if SANITIZER_GO0
525NOINLINE__attribute__((noinline))
526void GrowShadowStack(ThreadState *thr) {
527 const int sz = thr->shadow_stack_end - thr->shadow_stack;
528 const int newsz = 2 * sz;
529 auto *newstack = (uptr *)Alloc(newsz * sizeof(uptr));
530 internal_memcpy(newstack, thr->shadow_stack, sz * sizeof(uptr));
531 Free(thr->shadow_stack);
532 thr->shadow_stack = newstack;
533 thr->shadow_stack_pos = newstack + sz;
534 thr->shadow_stack_end = newstack + newsz;
535}
536#endif
537
538StackID CurrentStackId(ThreadState *thr, uptr pc) {
539 if (!thr->is_inited) // May happen during bootstrap.
540 return kInvalidStackID;
541 if (pc != 0) {
542#if !SANITIZER_GO0
543 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
544#else
545 if (thr->shadow_stack_pos == thr->shadow_stack_end)
546 GrowShadowStack(thr);
547#endif
548 thr->shadow_stack_pos[0] = pc;
549 thr->shadow_stack_pos++;
550 }
551 StackID id = StackDepotPut(
552 StackTrace(thr->shadow_stack, thr->shadow_stack_pos - thr->shadow_stack));
553 if (pc != 0)
554 thr->shadow_stack_pos--;
555 return id;
556}
557
558namespace v3 {
559
560ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used)) bool TryTraceMemoryAccess(ThreadState *thr, uptr pc,
561 uptr addr, uptr size,
562 AccessType typ) {
563 DCHECK(size == 1 || size == 2 || size == 4 || size == 8);
564 if (!kCollectHistory)
565 return true;
566 EventAccess *ev;
567 if (UNLIKELY(!TraceAcquire(thr, &ev))__builtin_expect(!!(!TraceAcquire(thr, &ev)), 0))
568 return false;
569 u64 size_log = size == 1 ? 0 : size == 2 ? 1 : size == 4 ? 2 : 3;
570 uptr pc_delta = pc - thr->trace_prev_pc + (1 << (EventAccess::kPCBits - 1));
571 thr->trace_prev_pc = pc;
572 if (LIKELY(pc_delta < (1 << EventAccess::kPCBits))__builtin_expect(!!(pc_delta < (1 << EventAccess::kPCBits
)), 1)
) {
573 ev->is_access = 1;
574 ev->is_read = !!(typ & kAccessRead);
575 ev->is_atomic = !!(typ & kAccessAtomic);
576 ev->size_log = size_log;
577 ev->pc_delta = pc_delta;
578 DCHECK_EQ(ev->pc_delta, pc_delta);
579 ev->addr = CompressAddr(addr);
580 TraceRelease(thr, ev);
581 return true;
582 }
583 auto *evex = reinterpret_cast<EventAccessExt *>(ev);
584 evex->is_access = 0;
585 evex->is_func = 0;
586 evex->type = EventType::kAccessExt;
587 evex->is_read = !!(typ & kAccessRead);
588 evex->is_atomic = !!(typ & kAccessAtomic);
589 evex->size_log = size_log;
590 evex->addr = CompressAddr(addr);
591 evex->pc = pc;
592 TraceRelease(thr, evex);
593 return true;
594}
595
596ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used)) bool TryTraceMemoryAccessRange(ThreadState *thr, uptr pc,
597 uptr addr, uptr size,
598 AccessType typ) {
599 if (!kCollectHistory)
600 return true;
601 EventAccessRange *ev;
602 if (UNLIKELY(!TraceAcquire(thr, &ev))__builtin_expect(!!(!TraceAcquire(thr, &ev)), 0))
603 return false;
604 thr->trace_prev_pc = pc;
605 ev->is_access = 0;
606 ev->is_func = 0;
607 ev->type = EventType::kAccessRange;
608 ev->is_read = !!(typ & kAccessRead);
609 ev->is_free = !!(typ & kAccessFree);
610 ev->size_lo = size;
611 ev->pc = CompressAddr(pc);
612 ev->addr = CompressAddr(addr);
613 ev->size_hi = size >> EventAccessRange::kSizeLoBits;
614 TraceRelease(thr, ev);
615 return true;
616}
617
618void TraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
619 AccessType typ) {
620 if (LIKELY(TryTraceMemoryAccessRange(thr, pc, addr, size, typ))__builtin_expect(!!(TryTraceMemoryAccessRange(thr, pc, addr, size
, typ)), 1)
)
621 return;
622 TraceSwitchPart(thr);
623 UNUSED__attribute__((unused)) bool res = TryTraceMemoryAccessRange(thr, pc, addr, size, typ);
624 DCHECK(res);
625}
626
627void TraceFunc(ThreadState *thr, uptr pc) {
628 if (LIKELY(TryTraceFunc(thr, pc))__builtin_expect(!!(TryTraceFunc(thr, pc)), 1))
629 return;
630 TraceSwitchPart(thr);
631 UNUSED__attribute__((unused)) bool res = TryTraceFunc(thr, pc);
632 DCHECK(res);
633}
634
635void TraceMutexLock(ThreadState *thr, EventType type, uptr pc, uptr addr,
636 StackID stk) {
637 DCHECK(type == EventType::kLock || type == EventType::kRLock);
638 if (!kCollectHistory)
639 return;
640 EventLock ev;
641 ev.is_access = 0;
642 ev.is_func = 0;
643 ev.type = type;
644 ev.pc = CompressAddr(pc);
645 ev.stack_lo = stk;
646 ev.stack_hi = stk >> EventLock::kStackIDLoBits;
647 ev._ = 0;
648 ev.addr = CompressAddr(addr);
649 TraceEvent(thr, ev);
650}
651
652void TraceMutexUnlock(ThreadState *thr, uptr addr) {
653 if (!kCollectHistory
0.1
'kCollectHistory' is true
0.1
'kCollectHistory' is true
)
1
Taking false branch
654 return;
655 EventUnlock ev;
656 ev.is_access = 0;
657 ev.is_func = 0;
658 ev.type = EventType::kUnlock;
659 ev._ = 0;
660 ev.addr = CompressAddr(addr);
661 TraceEvent(thr, ev);
2
Calling 'TraceEvent<__tsan::v3::EventUnlock>'
662}
663
664void TraceTime(ThreadState *thr) {
665 if (!kCollectHistory)
666 return;
667 EventTime ev;
668 ev.is_access = 0;
669 ev.is_func = 0;
670 ev.type = EventType::kTime;
671 ev.sid = static_cast<u64>(thr->sid);
672 ev.epoch = static_cast<u64>(thr->epoch);
673 ev._ = 0;
674 TraceEvent(thr, ev);
675}
676
677NOINLINE__attribute__((noinline))
678void TraceSwitchPart(ThreadState *thr) {
679 Trace *trace = &thr->tctx->trace;
680 Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
681 DCHECK_EQ(reinterpret_cast<uptr>(pos + 1) & TracePart::kAlignment, 0);
682 auto *part = trace->parts.Back();
683 DPrintf("TraceSwitchPart part=%p pos=%p\n", part, pos);
684 if (part) {
685 // We can get here when we still have space in the current trace part.
686 // The fast-path check in TraceAcquire has false positives in the middle of
687 // the part. Check if we are indeed at the end of the current part or not,
688 // and fill any gaps with NopEvent's.
689 Event *end = &part->events[TracePart::kSize];
690 DCHECK_GE(pos, &part->events[0]);
691 DCHECK_LE(pos, end);
692 if (pos + 1 < end) {
693 if ((reinterpret_cast<uptr>(pos) & TracePart::kAlignment) ==
694 TracePart::kAlignment)
695 *pos++ = NopEvent;
696 *pos++ = NopEvent;
697 DCHECK_LE(pos + 2, end);
698 atomic_store_relaxed(&thr->trace_pos, reinterpret_cast<uptr>(pos));
699 // Ensure we setup trace so that the next TraceAcquire
700 // won't detect trace part end.
701 Event *ev;
702 CHECK(TraceAcquire(thr, &ev))do { __sanitizer::u64 v1 = (__sanitizer::u64)((TraceAcquire(thr
, &ev))); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if
(__builtin_expect(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed
("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 702, "(" "(TraceAcquire(thr, &ev))" ") " "!=" " (" "0" ")"
, v1, v2); } while (false)
;
703 return;
704 }
705 // We are indeed at the end.
706 for (; pos < end; pos++) *pos = NopEvent;
707 }
708#if !SANITIZER_GO0
709 if (ctx->after_multithreaded_fork) {
710 // We just need to survive till exec.
711 CHECK(part)do { __sanitizer::u64 v1 = (__sanitizer::u64)((part)); __sanitizer
::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1
!= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 711, "(" "(part)" ") " "!=" " (" "0" ")", v1, v2); } while (
false)
;
712 atomic_store_relaxed(&thr->trace_pos,
713 reinterpret_cast<uptr>(&part->events[0]));
714 return;
715 }
716#endif
717 part = new (MmapOrDie(sizeof(TracePart), "TracePart")) TracePart();
718 part->trace = trace;
719 thr->trace_prev_pc = 0;
720 {
721 Lock lock(&trace->mtx);
722 trace->parts.PushBack(part);
723 atomic_store_relaxed(&thr->trace_pos,
724 reinterpret_cast<uptr>(&part->events[0]));
725 }
726 // Make this part self-sufficient by restoring the current stack
727 // and mutex set in the beginning of the trace.
728 TraceTime(thr);
729 for (uptr *pos = &thr->shadow_stack[0]; pos < thr->shadow_stack_pos; pos++)
730 CHECK(TryTraceFunc(thr, *pos))do { __sanitizer::u64 v1 = (__sanitizer::u64)((TryTraceFunc(thr
, *pos))); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 730, "(" "(TryTraceFunc(thr, *pos))" ") " "!=" " (" "0" ")"
, v1, v2); } while (false)
;
731 for (uptr i = 0; i < thr->mset.Size(); i++) {
732 MutexSet::Desc d = thr->mset.Get(i);
733 TraceMutexLock(thr, d.write ? EventType::kLock : EventType::kRLock, 0,
734 d.addr, d.stack_id);
735 }
736}
737
738} // namespace v3
739
740void TraceSwitch(ThreadState *thr) {
741#if !SANITIZER_GO0
742 if (ctx->after_multithreaded_fork)
743 return;
744#endif
745 thr->nomalloc++;
746 Trace *thr_trace = ThreadTrace(thr->tid);
747 Lock l(&thr_trace->mtx);
748 unsigned trace = (thr->fast_state.epoch() / kTracePartSize) % TraceParts();
749 TraceHeader *hdr = &thr_trace->headers[trace];
750 hdr->epoch0 = thr->fast_state.epoch();
751 ObtainCurrentStack(thr, 0, &hdr->stack0);
752 hdr->mset0 = thr->mset;
753 thr->nomalloc--;
754}
755
756Trace *ThreadTrace(Tid tid) { return (Trace *)GetThreadTraceHeader(tid); }
757
758uptr TraceTopPC(ThreadState *thr) {
759 Event *events = (Event*)GetThreadTrace(thr->tid);
760 uptr pc = events[thr->fast_state.GetTracePos()];
761 return pc;
762}
763
764uptr TraceSize() {
765 return (uptr)(1ull << (kTracePartSizeBits + flags()->history_size + 1));
766}
767
768uptr TraceParts() {
769 return TraceSize() / kTracePartSize;
770}
771
772#if !SANITIZER_GO0
773extern "C" void __tsan_trace_switch() {
774 TraceSwitch(cur_thread());
775}
776
777extern "C" void __tsan_report_race() {
778 ReportRace(cur_thread());
779}
780#endif
781
782ALWAYS_INLINEinline __attribute__((always_inline))
783Shadow LoadShadow(u64 *p) {
784 u64 raw = atomic_load((atomic_uint64_t*)p, memory_order_relaxed);
785 return Shadow(raw);
786}
787
788ALWAYS_INLINEinline __attribute__((always_inline))
789void StoreShadow(u64 *sp, u64 s) {
790 atomic_store((atomic_uint64_t*)sp, s, memory_order_relaxed);
791}
792
793ALWAYS_INLINEinline __attribute__((always_inline))
794void StoreIfNotYetStored(u64 *sp, u64 *s) {
795 StoreShadow(sp, *s);
796 *s = 0;
797}
798
799ALWAYS_INLINEinline __attribute__((always_inline))
800void HandleRace(ThreadState *thr, u64 *shadow_mem,
801 Shadow cur, Shadow old) {
802 thr->racy_state[0] = cur.raw();
803 thr->racy_state[1] = old.raw();
804 thr->racy_shadow_addr = shadow_mem;
805#if !SANITIZER_GO0
806 HACKY_CALL(__tsan_report_race)__asm__ __volatile__("sub $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"1024" ";" ".hidden " "__tsan_report_race" "_thunk;" "call "
"__tsan_report_race" "_thunk;" "add $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"-1024" ";" ::: "memory", "cc");
;
807#else
808 ReportRace(thr);
809#endif
810}
811
812static inline bool HappensBefore(Shadow old, ThreadState *thr) {
813 return thr->clock.get(old.TidWithIgnore()) >= old.epoch();
814}
815
816ALWAYS_INLINEinline __attribute__((always_inline))
817void MemoryAccessImpl1(ThreadState *thr, uptr addr,
818 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
819 u64 *shadow_mem, Shadow cur) {
820
821 // This potentially can live in an MMX/SSE scratch register.
822 // The required intrinsics are:
823 // __m128i _mm_move_epi64(__m128i*);
824 // _mm_storel_epi64(u64*, __m128i);
825 u64 store_word = cur.raw();
826 bool stored = false;
827
828 // scan all the shadow values and dispatch to 4 categories:
829 // same, replace, candidate and race (see comments below).
830 // we consider only 3 cases regarding access sizes:
831 // equal, intersect and not intersect. initially I considered
832 // larger and smaller as well, it allowed to replace some
833 // 'candidates' with 'same' or 'replace', but I think
834 // it's just not worth it (performance- and complexity-wise).
835
836 Shadow old(0);
837
838 // It release mode we manually unroll the loop,
839 // because empirically gcc generates better code this way.
840 // However, we can't afford unrolling in debug mode, because the function
841 // consumes almost 4K of stack. Gtest gives only 4K of stack to death test
842 // threads, which is not enough for the unrolled loop.
843#if SANITIZER_DEBUG0
844 for (int idx = 0; idx < 4; idx++) {
845# include "tsan_update_shadow_word.inc"
846 }
847#else
848 int idx = 0;
849# include "tsan_update_shadow_word.inc"
850 idx = 1;
851 if (stored) {
852# include "tsan_update_shadow_word.inc"
853 } else {
854# include "tsan_update_shadow_word.inc"
855 }
856 idx = 2;
857 if (stored) {
858# include "tsan_update_shadow_word.inc"
859 } else {
860# include "tsan_update_shadow_word.inc"
861 }
862 idx = 3;
863 if (stored) {
864# include "tsan_update_shadow_word.inc"
865 } else {
866# include "tsan_update_shadow_word.inc"
867 }
868#endif
869
870 // we did not find any races and had already stored
871 // the current access info, so we are done
872 if (LIKELY(stored)__builtin_expect(!!(stored), 1))
873 return;
874 // choose a random candidate slot and replace it
875 StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
876 return;
877 RACE:
878 HandleRace(thr, shadow_mem, cur, old);
879 return;
880}
881
882void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
883 AccessType typ) {
884 DCHECK(!(typ & kAccessAtomic));
885 const bool kAccessIsWrite = !(typ & kAccessRead);
886 const bool kIsAtomic = false;
887 while (size) {
888 int size1 = 1;
889 int kAccessSizeLog = kSizeLog1;
890 if (size >= 8 && (addr & ~7) == ((addr + 7) & ~7)) {
891 size1 = 8;
892 kAccessSizeLog = kSizeLog8;
893 } else if (size >= 4 && (addr & ~7) == ((addr + 3) & ~7)) {
894 size1 = 4;
895 kAccessSizeLog = kSizeLog4;
896 } else if (size >= 2 && (addr & ~7) == ((addr + 1) & ~7)) {
897 size1 = 2;
898 kAccessSizeLog = kSizeLog2;
899 }
900 MemoryAccess(thr, pc, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic);
901 addr += size1;
902 size -= size1;
903 }
904}
905
906ALWAYS_INLINEinline __attribute__((always_inline))
907bool ContainsSameAccessSlow(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
908 Shadow cur(a);
909 for (uptr i = 0; i < kShadowCnt; i++) {
910 Shadow old(LoadShadow(&s[i]));
911 if (Shadow::Addr0AndSizeAreEqual(cur, old) &&
912 old.TidWithIgnore() == cur.TidWithIgnore() &&
913 old.epoch() > sync_epoch &&
914 old.IsAtomic() == cur.IsAtomic() &&
915 old.IsRead() <= cur.IsRead())
916 return true;
917 }
918 return false;
919}
920
921#if TSAN_VECTORIZE1
922# define SHUF(v0, v1, i0, i1, i2, i3)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(v0)), (__v4sf)(__m128)(_mm_castsi128_ps(v1
)), (int)((i0)*1 + (i1)*4 + (i2)*16 + (i3)*64))))
\
923 _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(v0), \((__m128)__builtin_ia32_shufps((__v4sf)(__m128)(_mm_castsi128_ps
(v0)), (__v4sf)(__m128)(_mm_castsi128_ps(v1)), (int)((i0)*1 +
(i1)*4 + (i2)*16 + (i3)*64)))
924 _mm_castsi128_ps(v1), \((__m128)__builtin_ia32_shufps((__v4sf)(__m128)(_mm_castsi128_ps
(v0)), (__v4sf)(__m128)(_mm_castsi128_ps(v1)), (int)((i0)*1 +
(i1)*4 + (i2)*16 + (i3)*64)))
925 (i0)*1 + (i1)*4 + (i2)*16 + (i3)*64)((__m128)__builtin_ia32_shufps((__v4sf)(__m128)(_mm_castsi128_ps
(v0)), (__v4sf)(__m128)(_mm_castsi128_ps(v1)), (int)((i0)*1 +
(i1)*4 + (i2)*16 + (i3)*64)))
)
926ALWAYS_INLINEinline __attribute__((always_inline))
927bool ContainsSameAccessFast(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
928 // This is an optimized version of ContainsSameAccessSlow.
929 // load current access into access[0:63]
930 const m128 access = _mm_cvtsi64_si128(a);
931 // duplicate high part of access in addr0:
932 // addr0[0:31] = access[32:63]
933 // addr0[32:63] = access[32:63]
934 // addr0[64:95] = access[32:63]
935 // addr0[96:127] = access[32:63]
936 const m128 addr0 = SHUF(access, access, 1, 1, 1, 1)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(access)), (__v4sf)(__m128)(_mm_castsi128_ps
(access)), (int)((1)*1 + (1)*4 + (1)*16 + (1)*64))))
;
937 // load 4 shadow slots
938 const m128 shadow0 = _mm_load_si128((__m128i*)s);
939 const m128 shadow1 = _mm_load_si128((__m128i*)s + 1);
940 // load high parts of 4 shadow slots into addr_vect:
941 // addr_vect[0:31] = shadow0[32:63]
942 // addr_vect[32:63] = shadow0[96:127]
943 // addr_vect[64:95] = shadow1[32:63]
944 // addr_vect[96:127] = shadow1[96:127]
945 m128 addr_vect = SHUF(shadow0, shadow1, 1, 3, 1, 3)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(shadow0)), (__v4sf)(__m128)(_mm_castsi128_ps
(shadow1)), (int)((1)*1 + (3)*4 + (1)*16 + (3)*64))))
;
946 if (!is_write) {
947 // set IsRead bit in addr_vect
948 const m128 rw_mask1 = _mm_cvtsi64_si128(1<<15);
949 const m128 rw_mask = SHUF(rw_mask1, rw_mask1, 0, 0, 0, 0)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(rw_mask1)), (__v4sf)(__m128)(_mm_castsi128_ps
(rw_mask1)), (int)((0)*1 + (0)*4 + (0)*16 + (0)*64))))
;
950 addr_vect = _mm_or_si128(addr_vect, rw_mask);
951 }
952 // addr0 == addr_vect?
953 const m128 addr_res = _mm_cmpeq_epi32(addr0, addr_vect);
954 // epoch1[0:63] = sync_epoch
955 const m128 epoch1 = _mm_cvtsi64_si128(sync_epoch);
956 // epoch[0:31] = sync_epoch[0:31]
957 // epoch[32:63] = sync_epoch[0:31]
958 // epoch[64:95] = sync_epoch[0:31]
959 // epoch[96:127] = sync_epoch[0:31]
960 const m128 epoch = SHUF(epoch1, epoch1, 0, 0, 0, 0)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(epoch1)), (__v4sf)(__m128)(_mm_castsi128_ps
(epoch1)), (int)((0)*1 + (0)*4 + (0)*16 + (0)*64))))
;
961 // load low parts of shadow cell epochs into epoch_vect:
962 // epoch_vect[0:31] = shadow0[0:31]
963 // epoch_vect[32:63] = shadow0[64:95]
964 // epoch_vect[64:95] = shadow1[0:31]
965 // epoch_vect[96:127] = shadow1[64:95]
966 const m128 epoch_vect = SHUF(shadow0, shadow1, 0, 2, 0, 2)_mm_castps_si128(((__m128)__builtin_ia32_shufps((__v4sf)(__m128
)(_mm_castsi128_ps(shadow0)), (__v4sf)(__m128)(_mm_castsi128_ps
(shadow1)), (int)((0)*1 + (2)*4 + (0)*16 + (2)*64))))
;
967 // epoch_vect >= sync_epoch?
968 const m128 epoch_res = _mm_cmpgt_epi32(epoch_vect, epoch);
969 // addr_res & epoch_res
970 const m128 res = _mm_and_si128(addr_res, epoch_res);
971 // mask[0] = res[7]
972 // mask[1] = res[15]
973 // ...
974 // mask[15] = res[127]
975 const int mask = _mm_movemask_epi8(res);
976 return mask != 0;
977}
978#endif
979
980ALWAYS_INLINEinline __attribute__((always_inline))
981bool ContainsSameAccess(u64 *s, u64 a, u64 sync_epoch, bool is_write) {
982#if TSAN_VECTORIZE1
983 bool res = ContainsSameAccessFast(s, a, sync_epoch, is_write);
984 // NOTE: this check can fail if the shadow is concurrently mutated
985 // by other threads. But it still can be useful if you modify
986 // ContainsSameAccessFast and want to ensure that it's not completely broken.
987 // DCHECK_EQ(res, ContainsSameAccessSlow(s, a, sync_epoch, is_write));
988 return res;
989#else
990 return ContainsSameAccessSlow(s, a, sync_epoch, is_write);
991#endif
992}
993
994ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used))
995void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
996 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic) {
997 RawShadow *shadow_mem = MemToShadow(addr);
998 DPrintf2("#%d: MemoryAccess: @%p %p size=%d"
999 " is_write=%d shadow_mem=%p {%zx, %zx, %zx, %zx}\n",
1000 (int)thr->fast_state.tid(), (void*)pc, (void*)addr,
1001 (int)(1 << kAccessSizeLog), kAccessIsWrite, shadow_mem,
1002 (uptr)shadow_mem[0], (uptr)shadow_mem[1],
1003 (uptr)shadow_mem[2], (uptr)shadow_mem[3]);
1004#if SANITIZER_DEBUG0
1005 if (!IsAppMem(addr)) {
1006 Printf("Access to non app mem %zx\n", addr);
1007 DCHECK(IsAppMem(addr));
1008 }
1009 if (!IsShadowMem(shadow_mem)) {
1010 Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
1011 DCHECK(IsShadowMem(shadow_mem));
1012 }
1013#endif
1014
1015 if (!SANITIZER_GO0 && !kAccessIsWrite && *shadow_mem == kShadowRodata) {
1016 // Access to .rodata section, no races here.
1017 // Measurements show that it can be 10-20% of all memory accesses.
1018 return;
1019 }
1020
1021 FastState fast_state = thr->fast_state;
1022 if (UNLIKELY(fast_state.GetIgnoreBit())__builtin_expect(!!(fast_state.GetIgnoreBit()), 0)) {
1023 return;
1024 }
1025
1026 Shadow cur(fast_state);
1027 cur.SetAddr0AndSizeLog(addr & 7, kAccessSizeLog);
1028 cur.SetWrite(kAccessIsWrite);
1029 cur.SetAtomic(kIsAtomic);
1030
1031 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),__builtin_expect(!!(ContainsSameAccess(shadow_mem, cur.raw(),
thr->fast_synch_epoch, kAccessIsWrite)), 1)
1032 thr->fast_synch_epoch, kAccessIsWrite))__builtin_expect(!!(ContainsSameAccess(shadow_mem, cur.raw(),
thr->fast_synch_epoch, kAccessIsWrite)), 1)
) {
1033 return;
1034 }
1035
1036 if (kCollectHistory) {
1037 fast_state.IncrementEpoch();
1038 thr->fast_state = fast_state;
1039 TraceAddEvent(thr, fast_state, EventTypeMop, pc);
1040 cur.IncrementEpoch();
1041 }
1042
1043 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
1044 shadow_mem, cur);
1045}
1046
1047// Called by MemoryAccessRange in tsan_rtl_thread.cpp
1048ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used))
1049void MemoryAccessImpl(ThreadState *thr, uptr addr,
1050 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
1051 u64 *shadow_mem, Shadow cur) {
1052 if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),__builtin_expect(!!(ContainsSameAccess(shadow_mem, cur.raw(),
thr->fast_synch_epoch, kAccessIsWrite)), 1)
1053 thr->fast_synch_epoch, kAccessIsWrite))__builtin_expect(!!(ContainsSameAccess(shadow_mem, cur.raw(),
thr->fast_synch_epoch, kAccessIsWrite)), 1)
) {
1054 return;
1055 }
1056
1057 MemoryAccessImpl1(thr, addr, kAccessSizeLog, kAccessIsWrite, kIsAtomic,
1058 shadow_mem, cur);
1059}
1060
1061static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
1062 u64 val) {
1063 (void)thr;
1064 (void)pc;
1065 if (size == 0)
1066 return;
1067 // FIXME: fix me.
1068 uptr offset = addr % kShadowCell;
1069 if (offset) {
1070 offset = kShadowCell - offset;
1071 if (size <= offset)
1072 return;
1073 addr += offset;
1074 size -= offset;
1075 }
1076 DCHECK_EQ(addr % 8, 0);
1077 // If a user passes some insane arguments (memset(0)),
1078 // let it just crash as usual.
1079 if (!IsAppMem(addr) || !IsAppMem(addr + size - 1))
1080 return;
1081 // Don't want to touch lots of shadow memory.
1082 // If a program maps 10MB stack, there is no need reset the whole range.
1083 size = (size + (kShadowCell - 1)) & ~(kShadowCell - 1);
1084 // UnmapOrDie/MmapFixedNoReserve does not work on Windows.
1085 if (SANITIZER_WINDOWS0 || size < common_flags()->clear_shadow_mmap_threshold) {
1086 RawShadow *p = MemToShadow(addr);
1087 CHECK(IsShadowMem(p))do { __sanitizer::u64 v1 = (__sanitizer::u64)((IsShadowMem(p)
)); __sanitizer::u64 v2 = (__sanitizer::u64)(0); if (__builtin_expect
(!!(!(v1 != v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1087, "(" "(IsShadowMem(p))" ") " "!=" " (" "0" ")", v1, v2
); } while (false)
;
1088 CHECK(IsShadowMem(p + size * kShadowCnt / kShadowCell - 1))do { __sanitizer::u64 v1 = (__sanitizer::u64)((IsShadowMem(p +
size * kShadowCnt / kShadowCell - 1))); __sanitizer::u64 v2 =
(__sanitizer::u64)(0); if (__builtin_expect(!!(!(v1 != v2)),
0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1088, "(" "(IsShadowMem(p + size * kShadowCnt / kShadowCell - 1))"
") " "!=" " (" "0" ")", v1, v2); } while (false)
;
1089 // FIXME: may overwrite a part outside the region
1090 for (uptr i = 0; i < size / kShadowCell * kShadowCnt;) {
1091 p[i++] = val;
1092 for (uptr j = 1; j < kShadowCnt; j++)
1093 p[i++] = 0;
1094 }
1095 } else {
1096 // The region is big, reset only beginning and end.
1097 const uptr kPageSize = GetPageSizeCached();
1098 RawShadow *begin = MemToShadow(addr);
1099 RawShadow *end = begin + size / kShadowCell * kShadowCnt;
1100 RawShadow *p = begin;
1101 // Set at least first kPageSize/2 to page boundary.
1102 while ((p < begin + kPageSize / kShadowSize / 2) || ((uptr)p % kPageSize)) {
1103 *p++ = val;
1104 for (uptr j = 1; j < kShadowCnt; j++)
1105 *p++ = 0;
1106 }
1107 // Reset middle part.
1108 RawShadow *p1 = p;
1109 p = RoundDown(end, kPageSize);
1110 if (!MmapFixedSuperNoReserve((uptr)p1, (uptr)p - (uptr)p1))
1111 Die();
1112 // Set the ending.
1113 while (p < end) {
1114 *p++ = val;
1115 for (uptr j = 1; j < kShadowCnt; j++)
1116 *p++ = 0;
1117 }
1118 }
1119}
1120
1121void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1122 MemoryRangeSet(thr, pc, addr, size, 0);
1123}
1124
1125void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1126 // Processing more than 1k (4k of shadow) is expensive,
1127 // can cause excessive memory consumption (user does not necessary touch
1128 // the whole range) and most likely unnecessary.
1129 if (size > 1024)
1130 size = 1024;
1131 CHECK_EQ(thr->is_freeing, false)do { __sanitizer::u64 v1 = (__sanitizer::u64)((thr->is_freeing
)); __sanitizer::u64 v2 = (__sanitizer::u64)((false)); if (__builtin_expect
(!!(!(v1 == v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1131, "(" "(thr->is_freeing)" ") " "==" " (" "(false)" ")"
, v1, v2); } while (false)
;
1132 thr->is_freeing = true;
1133 MemoryAccessRange(thr, pc, addr, size, true);
1134 thr->is_freeing = false;
1135 if (kCollectHistory) {
1136 thr->fast_state.IncrementEpoch();
1137 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
1138 }
1139 Shadow s(thr->fast_state);
1140 s.ClearIgnoreBit();
1141 s.MarkAsFreed();
1142 s.SetWrite(true);
1143 s.SetAddr0AndSizeLog(0, 3);
1144 MemoryRangeSet(thr, pc, addr, size, s.raw());
1145}
1146
1147void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size) {
1148 if (kCollectHistory) {
1149 thr->fast_state.IncrementEpoch();
1150 TraceAddEvent(thr, thr->fast_state, EventTypeMop, pc);
1151 }
1152 Shadow s(thr->fast_state);
1153 s.ClearIgnoreBit();
1154 s.SetWrite(true);
1155 s.SetAddr0AndSizeLog(0, 3);
1156 MemoryRangeSet(thr, pc, addr, size, s.raw());
1157}
1158
1159void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
1160 uptr size) {
1161 if (thr->ignore_reads_and_writes == 0)
1162 MemoryRangeImitateWrite(thr, pc, addr, size);
1163 else
1164 MemoryResetRange(thr, pc, addr, size);
1165}
1166
1167ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used))
1168void FuncEntry(ThreadState *thr, uptr pc) {
1169 DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
1170 if (kCollectHistory) {
1171 thr->fast_state.IncrementEpoch();
1172 TraceAddEvent(thr, thr->fast_state, EventTypeFuncEnter, pc);
1173 }
1174
1175 // Shadow stack maintenance can be replaced with
1176 // stack unwinding during trace switch (which presumably must be faster).
1177 DCHECK_GE(thr->shadow_stack_pos, thr->shadow_stack);
1178#if !SANITIZER_GO0
1179 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1180#else
1181 if (thr->shadow_stack_pos == thr->shadow_stack_end)
1182 GrowShadowStack(thr);
1183#endif
1184 thr->shadow_stack_pos[0] = pc;
1185 thr->shadow_stack_pos++;
1186}
1187
1188ALWAYS_INLINEinline __attribute__((always_inline)) USED__attribute__((used))
1189void FuncExit(ThreadState *thr) {
1190 DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
1191 if (kCollectHistory) {
1192 thr->fast_state.IncrementEpoch();
1193 TraceAddEvent(thr, thr->fast_state, EventTypeFuncExit, 0);
1194 }
1195
1196 DCHECK_GT(thr->shadow_stack_pos, thr->shadow_stack);
1197#if !SANITIZER_GO0
1198 DCHECK_LT(thr->shadow_stack_pos, thr->shadow_stack_end);
1199#endif
1200 thr->shadow_stack_pos--;
1201}
1202
1203void ThreadIgnoreBegin(ThreadState *thr, uptr pc) {
1204 DPrintf("#%d: ThreadIgnoreBegin\n", thr->tid);
1205 thr->ignore_reads_and_writes++;
1206 CHECK_GT(thr->ignore_reads_and_writes, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((thr->ignore_reads_and_writes
)); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1206, "(" "(thr->ignore_reads_and_writes)" ") " ">" " ("
"(0)" ")", v1, v2); } while (false)
;
1207 thr->fast_state.SetIgnoreBit();
1208#if !SANITIZER_GO0
1209 if (pc && !ctx->after_multithreaded_fork)
1210 thr->mop_ignore_set.Add(CurrentStackId(thr, pc));
1211#endif
1212}
1213
1214void ThreadIgnoreEnd(ThreadState *thr) {
1215 DPrintf("#%d: ThreadIgnoreEnd\n", thr->tid);
1216 CHECK_GT(thr->ignore_reads_and_writes, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((thr->ignore_reads_and_writes
)); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1216, "(" "(thr->ignore_reads_and_writes)" ") " ">" " ("
"(0)" ")", v1, v2); } while (false)
;
1217 thr->ignore_reads_and_writes--;
1218 if (thr->ignore_reads_and_writes == 0) {
1219 thr->fast_state.ClearIgnoreBit();
1220#if !SANITIZER_GO0
1221 thr->mop_ignore_set.Reset();
1222#endif
1223 }
1224}
1225
1226#if !SANITIZER_GO0
1227extern "C" SANITIZER_INTERFACE_ATTRIBUTE__attribute__((visibility("default")))
1228uptr __tsan_testonly_shadow_stack_current_size() {
1229 ThreadState *thr = cur_thread();
1230 return thr->shadow_stack_pos - thr->shadow_stack;
1231}
1232#endif
1233
1234void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc) {
1235 DPrintf("#%d: ThreadIgnoreSyncBegin\n", thr->tid);
1236 thr->ignore_sync++;
1237 CHECK_GT(thr->ignore_sync, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((thr->ignore_sync
)); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1237, "(" "(thr->ignore_sync)" ") " ">" " (" "(0)" ")"
, v1, v2); } while (false)
;
1238#if !SANITIZER_GO0
1239 if (pc && !ctx->after_multithreaded_fork)
1240 thr->sync_ignore_set.Add(CurrentStackId(thr, pc));
1241#endif
1242}
1243
1244void ThreadIgnoreSyncEnd(ThreadState *thr) {
1245 DPrintf("#%d: ThreadIgnoreSyncEnd\n", thr->tid);
1246 CHECK_GT(thr->ignore_sync, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((thr->ignore_sync
)); __sanitizer::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect
(!!(!(v1 > v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp"
, 1246, "(" "(thr->ignore_sync)" ") " ">" " (" "(0)" ")"
, v1, v2); } while (false)
;
1247 thr->ignore_sync--;
1248#if !SANITIZER_GO0
1249 if (thr->ignore_sync == 0)
1250 thr->sync_ignore_set.Reset();
1251#endif
1252}
1253
1254bool MD5Hash::operator==(const MD5Hash &other) const {
1255 return hash[0] == other.hash[0] && hash[1] == other.hash[1];
1256}
1257
1258#if SANITIZER_DEBUG0
1259void build_consistency_debug() {}
1260#else
1261void build_consistency_release() {}
1262#endif
1263
1264} // namespace __tsan
1265
1266#if SANITIZER_CHECK_DEADLOCKS(0 && !0 && 1)
1267namespace __sanitizer {
1268using namespace __tsan;
1269MutexMeta mutex_meta[] = {
1270 {MutexInvalid, "Invalid", {}},
1271 {MutexThreadRegistry, "ThreadRegistry", {}},
1272 {MutexTypeTrace, "Trace", {MutexLeaf}},
1273 {MutexTypeReport, "Report", {MutexTypeSyncVar}},
1274 {MutexTypeSyncVar, "SyncVar", {}},
1275 {MutexTypeAnnotations, "Annotations", {}},
1276 {MutexTypeAtExit, "AtExit", {MutexTypeSyncVar}},
1277 {MutexTypeFired, "Fired", {MutexLeaf}},
1278 {MutexTypeRacy, "Racy", {MutexLeaf}},
1279 {MutexTypeGlobalProc, "GlobalProc", {}},
1280 {},
1281};
1282
1283void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
1284} // namespace __sanitizer
1285#endif
1286
1287#if !SANITIZER_GO0
1288// Must be included in this file to make sure everything is inlined.
1289# include "tsan_interface.inc"
1290#endif

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.h

1//===-- tsan_rtl.h ----------------------------------------------*- C++ -*-===//
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 a part of ThreadSanitizer (TSan), a race detector.
10//
11// Main internal TSan header file.
12//
13// Ground rules:
14// - C++ run-time should not be used (static CTORs, RTTI, exceptions, static
15// function-scope locals)
16// - All functions/classes/etc reside in namespace __tsan, except for those
17// declared in tsan_interface.h.
18// - Platform-specific files should be used instead of ifdefs (*).
19// - No system headers included in header files (*).
20// - Platform specific headres included only into platform-specific files (*).
21//
22// (*) Except when inlining is critical for performance.
23//===----------------------------------------------------------------------===//
24
25#ifndef TSAN_RTL_H
26#define TSAN_RTL_H
27
28#include "sanitizer_common/sanitizer_allocator.h"
29#include "sanitizer_common/sanitizer_allocator_internal.h"
30#include "sanitizer_common/sanitizer_asm.h"
31#include "sanitizer_common/sanitizer_common.h"
32#include "sanitizer_common/sanitizer_deadlock_detector_interface.h"
33#include "sanitizer_common/sanitizer_libignore.h"
34#include "sanitizer_common/sanitizer_suppressions.h"
35#include "sanitizer_common/sanitizer_thread_registry.h"
36#include "sanitizer_common/sanitizer_vector.h"
37#include "tsan_clock.h"
38#include "tsan_defs.h"
39#include "tsan_flags.h"
40#include "tsan_mman.h"
41#include "tsan_sync.h"
42#include "tsan_trace.h"
43#include "tsan_report.h"
44#include "tsan_platform.h"
45#include "tsan_mutexset.h"
46#include "tsan_ignoreset.h"
47#include "tsan_stack_trace.h"
48
49#if SANITIZER_WORDSIZE64 != 64
50# error "ThreadSanitizer is supported only on 64-bit platforms"
51#endif
52
53namespace __tsan {
54
55#if !SANITIZER_GO0
56struct MapUnmapCallback;
57#if defined(__mips64) || defined(__aarch64__) || defined(__powerpc__)
58
59struct AP32 {
60 static const uptr kSpaceBeg = 0;
61 static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE(1ULL << 47);
62 static const uptr kMetadataSize = 0;
63 typedef __sanitizer::CompactSizeClassMap SizeClassMap;
64 static const uptr kRegionSizeLog = 20;
65 using AddressSpaceView = LocalAddressSpaceView;
66 typedef __tsan::MapUnmapCallback MapUnmapCallback;
67 static const uptr kFlags = 0;
68};
69typedef SizeClassAllocator32<AP32> PrimaryAllocator;
70#else
71struct AP64 { // Allocator64 parameters. Deliberately using a short name.
72# if defined(__s390x__)
73 typedef MappingS390x Mapping;
74# else
75 typedef Mapping48AddressSpace Mapping;
76# endif
77 static const uptr kSpaceBeg = Mapping::kHeapMemBeg;
78 static const uptr kSpaceSize = Mapping::kHeapMemEnd - Mapping::kHeapMemBeg;
79 static const uptr kMetadataSize = 0;
80 typedef DefaultSizeClassMap SizeClassMap;
81 typedef __tsan::MapUnmapCallback MapUnmapCallback;
82 static const uptr kFlags = 0;
83 using AddressSpaceView = LocalAddressSpaceView;
84};
85typedef SizeClassAllocator64<AP64> PrimaryAllocator;
86#endif
87typedef CombinedAllocator<PrimaryAllocator> Allocator;
88typedef Allocator::AllocatorCache AllocatorCache;
89Allocator *allocator();
90#endif
91
92const RawShadow kShadowRodata = (RawShadow)-1; // .rodata shadow marker
93
94// FastState (from most significant bit):
95// ignore : 1
96// tid : kTidBits
97// unused : -
98// history_size : 3
99// epoch : kClkBits
100class FastState {
101 public:
102 FastState(u64 tid, u64 epoch) {
103 x_ = tid << kTidShift;
104 x_ |= epoch;
105 DCHECK_EQ(tid, this->tid());
106 DCHECK_EQ(epoch, this->epoch());
107 DCHECK_EQ(GetIgnoreBit(), false);
108 }
109
110 explicit FastState(u64 x)
111 : x_(x) {
112 }
113
114 u64 raw() const {
115 return x_;
116 }
117
118 u64 tid() const {
119 u64 res = (x_ & ~kIgnoreBit) >> kTidShift;
120 return res;
121 }
122
123 u64 TidWithIgnore() const {
124 u64 res = x_ >> kTidShift;
125 return res;
126 }
127
128 u64 epoch() const {
129 u64 res = x_ & ((1ull << kClkBits) - 1);
130 return res;
131 }
132
133 void IncrementEpoch() {
134 u64 old_epoch = epoch();
135 x_ += 1;
136 DCHECK_EQ(old_epoch + 1, epoch());
137 (void)old_epoch;
138 }
139
140 void SetIgnoreBit() { x_ |= kIgnoreBit; }
141 void ClearIgnoreBit() { x_ &= ~kIgnoreBit; }
142 bool GetIgnoreBit() const { return (s64)x_ < 0; }
143
144 void SetHistorySize(int hs) {
145 CHECK_GE(hs, 0)do { __sanitizer::u64 v1 = (__sanitizer::u64)((hs)); __sanitizer
::u64 v2 = (__sanitizer::u64)((0)); if (__builtin_expect(!!(!
(v1 >= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.h"
, 145, "(" "(hs)" ") " ">=" " (" "(0)" ")", v1, v2); } while
(false)
;
146 CHECK_LE(hs, 7)do { __sanitizer::u64 v1 = (__sanitizer::u64)((hs)); __sanitizer
::u64 v2 = (__sanitizer::u64)((7)); if (__builtin_expect(!!(!
(v1 <= v2)), 0)) __sanitizer::CheckFailed("/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/tsan/rtl/tsan_rtl.h"
, 146, "(" "(hs)" ") " "<=" " (" "(7)" ")", v1, v2); } while
(false)
;
147 x_ = (x_ & ~(kHistoryMask << kHistoryShift)) | (u64(hs) << kHistoryShift);
148 }
149
150 ALWAYS_INLINEinline __attribute__((always_inline))
151 int GetHistorySize() const {
152 return (int)((x_ >> kHistoryShift) & kHistoryMask);
153 }
154
155 void ClearHistorySize() {
156 SetHistorySize(0);
157 }
158
159 ALWAYS_INLINEinline __attribute__((always_inline))
160 u64 GetTracePos() const {
161 const int hs = GetHistorySize();
162 // When hs == 0, the trace consists of 2 parts.
163 const u64 mask = (1ull << (kTracePartSizeBits + hs + 1)) - 1;
164 return epoch() & mask;
165 }
166
167 private:
168 friend class Shadow;
169 static const int kTidShift = 64 - kTidBits - 1;
170 static const u64 kIgnoreBit = 1ull << 63;
171 static const u64 kFreedBit = 1ull << 63;
172 static const u64 kHistoryShift = kClkBits;
173 static const u64 kHistoryMask = 7;
174 u64 x_;
175};
176
177// Shadow (from most significant bit):
178// freed : 1
179// tid : kTidBits
180// is_atomic : 1
181// is_read : 1
182// size_log : 2
183// addr0 : 3
184// epoch : kClkBits
185class Shadow : public FastState {
186 public:
187 explicit Shadow(u64 x)
188 : FastState(x) {
189 }
190
191 explicit Shadow(const FastState &s)
192 : FastState(s.x_) {
193 ClearHistorySize();
194 }
195
196 void SetAddr0AndSizeLog(u64 addr0, unsigned kAccessSizeLog) {
197 DCHECK_EQ((x_ >> kClkBits) & 31, 0);
198 DCHECK_LE(addr0, 7);
199 DCHECK_LE(kAccessSizeLog, 3);
200 x_ |= ((kAccessSizeLog << 3) | addr0) << kClkBits;
201 DCHECK_EQ(kAccessSizeLog, size_log());
202 DCHECK_EQ(addr0, this->addr0());
203 }
204
205 void SetWrite(unsigned kAccessIsWrite) {
206 DCHECK_EQ(x_ & kReadBit, 0);
207 if (!kAccessIsWrite)
208 x_ |= kReadBit;
209 DCHECK_EQ(kAccessIsWrite, IsWrite());
210 }
211
212 void SetAtomic(bool kIsAtomic) {
213 DCHECK(!IsAtomic());
214 if (kIsAtomic)
215 x_ |= kAtomicBit;
216 DCHECK_EQ(IsAtomic(), kIsAtomic);
217 }
218
219 bool IsAtomic() const {
220 return x_ & kAtomicBit;
221 }
222
223 bool IsZero() const {
224 return x_ == 0;
225 }
226
227 static inline bool TidsAreEqual(const Shadow s1, const Shadow s2) {
228 u64 shifted_xor = (s1.x_ ^ s2.x_) >> kTidShift;
229 DCHECK_EQ(shifted_xor == 0, s1.TidWithIgnore() == s2.TidWithIgnore());
230 return shifted_xor == 0;
231 }
232
233 static ALWAYS_INLINEinline __attribute__((always_inline))
234 bool Addr0AndSizeAreEqual(const Shadow s1, const Shadow s2) {
235 u64 masked_xor = ((s1.x_ ^ s2.x_) >> kClkBits) & 31;
236 return masked_xor == 0;
237 }
238
239 static ALWAYS_INLINEinline __attribute__((always_inline)) bool TwoRangesIntersect(Shadow s1, Shadow s2,
240 unsigned kS2AccessSize) {
241 bool res = false;
242 u64 diff = s1.addr0() - s2.addr0();
243 if ((s64)diff < 0) { // s1.addr0 < s2.addr0
244 // if (s1.addr0() + size1) > s2.addr0()) return true;
245 if (s1.size() > -diff)
246 res = true;
247 } else {
248 // if (s2.addr0() + kS2AccessSize > s1.addr0()) return true;
249 if (kS2AccessSize > diff)
250 res = true;
251 }
252 DCHECK_EQ(res, TwoRangesIntersectSlow(s1, s2));
253 DCHECK_EQ(res, TwoRangesIntersectSlow(s2, s1));
254 return res;
255 }
256
257 u64 ALWAYS_INLINEinline __attribute__((always_inline)) addr0() const { return (x_ >> kClkBits) & 7; }
258 u64 ALWAYS_INLINEinline __attribute__((always_inline)) size() const { return 1ull << size_log(); }
259 bool ALWAYS_INLINEinline __attribute__((always_inline)) IsWrite() const { return !IsRead(); }
260 bool ALWAYS_INLINEinline __attribute__((always_inline)) IsRead() const { return x_ & kReadBit; }
261
262 // The idea behind the freed bit is as follows.
263 // When the memory is freed (or otherwise unaccessible) we write to the shadow
264 // values with tid/epoch related to the free and the freed bit set.
265 // During memory accesses processing the freed bit is considered
266 // as msb of tid. So any access races with shadow with freed bit set
267 // (it is as if write from a thread with which we never synchronized before).
268 // This allows us to detect accesses to freed memory w/o additional
269 // overheads in memory access processing and at the same time restore
270 // tid/epoch of free.
271 void MarkAsFreed() {
272 x_ |= kFreedBit;
273 }
274
275 bool IsFreed() const {
276 return x_ & kFreedBit;
277 }
278
279 bool GetFreedAndReset() {
280 bool res = x_ & kFreedBit;
281 x_ &= ~kFreedBit;
282 return res;
283 }
284
285 bool ALWAYS_INLINEinline __attribute__((always_inline)) IsBothReadsOrAtomic(bool kIsWrite, bool kIsAtomic) const {
286 bool v = x_ & ((u64(kIsWrite ^ 1) << kReadShift)
287 | (u64(kIsAtomic) << kAtomicShift));
288 DCHECK_EQ(v, (!IsWrite() && !kIsWrite) || (IsAtomic() && kIsAtomic));
289 return v;
290 }
291
292 bool ALWAYS_INLINEinline __attribute__((always_inline)) IsRWNotWeaker(bool kIsWrite, bool kIsAtomic) const {
293 bool v = ((x_ >> kReadShift) & 3)
294 <= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
295 DCHECK_EQ(v, (IsAtomic() < kIsAtomic) ||
296 (IsAtomic() == kIsAtomic && !IsWrite() <= !kIsWrite));
297 return v;
298 }
299
300 bool ALWAYS_INLINEinline __attribute__((always_inline)) IsRWWeakerOrEqual(bool kIsWrite, bool kIsAtomic) const {
301 bool v = ((x_ >> kReadShift) & 3)
302 >= u64((kIsWrite ^ 1) | (kIsAtomic << 1));
303 DCHECK_EQ(v, (IsAtomic() > kIsAtomic) ||
304 (IsAtomic() == kIsAtomic && !IsWrite() >= !kIsWrite));
305 return v;
306 }
307
308 private:
309 static const u64 kReadShift = 5 + kClkBits;
310 static const u64 kReadBit = 1ull << kReadShift;
311 static const u64 kAtomicShift = 6 + kClkBits;
312 static const u64 kAtomicBit = 1ull << kAtomicShift;
313
314 u64 size_log() const { return (x_ >> (3 + kClkBits)) & 3; }
315
316 static bool TwoRangesIntersectSlow(const Shadow s1, const Shadow s2) {
317 if (s1.addr0() == s2.addr0()) return true;
318 if (s1.addr0() < s2.addr0() && s1.addr0() + s1.size() > s2.addr0())
319 return true;
320 if (s2.addr0() < s1.addr0() && s2.addr0() + s2.size() > s1.addr0())
321 return true;
322 return false;
323 }
324};
325
326struct ThreadSignalContext;
327
328struct JmpBuf {
329 uptr sp;
330 int int_signal_send;
331 bool in_blocking_func;
332 uptr in_signal_handler;
333 uptr *shadow_stack_pos;
334};
335
336// A Processor represents a physical thread, or a P for Go.
337// It is used to store internal resources like allocate cache, and does not
338// participate in race-detection logic (invisible to end user).
339// In C++ it is tied to an OS thread just like ThreadState, however ideally
340// it should be tied to a CPU (this way we will have fewer allocator caches).
341// In Go it is tied to a P, so there are significantly fewer Processor's than
342// ThreadState's (which are tied to Gs).
343// A ThreadState must be wired with a Processor to handle events.
344struct Processor {
345 ThreadState *thr; // currently wired thread, or nullptr
346#if !SANITIZER_GO0
347 AllocatorCache alloc_cache;
348 InternalAllocatorCache internal_alloc_cache;
349#endif
350 DenseSlabAllocCache block_cache;
351 DenseSlabAllocCache sync_cache;
352 DenseSlabAllocCache clock_cache;
353 DDPhysicalThread *dd_pt;
354};
355
356#if !SANITIZER_GO0
357// ScopedGlobalProcessor temporary setups a global processor for the current
358// thread, if it does not have one. Intended for interceptors that can run
359// at the very thread end, when we already destroyed the thread processor.
360struct ScopedGlobalProcessor {
361 ScopedGlobalProcessor();
362 ~ScopedGlobalProcessor();
363};
364#endif
365
366// This struct is stored in TLS.
367struct ThreadState {
368 FastState fast_state;
369 // Synch epoch represents the threads's epoch before the last synchronization
370 // action. It allows to reduce number of shadow state updates.
371 // For example, fast_synch_epoch=100, last write to addr X was at epoch=150,
372 // if we are processing write to X from the same thread at epoch=200,
373 // we do nothing, because both writes happen in the same 'synch epoch'.
374 // That is, if another memory access does not race with the former write,
375 // it does not race with the latter as well.
376 // QUESTION: can we can squeeze this into ThreadState::Fast?
377 // E.g. ThreadState::Fast is a 44-bit, 32 are taken by synch_epoch and 12 are
378 // taken by epoch between synchs.
379 // This way we can save one load from tls.
380 u64 fast_synch_epoch;
381 // Technically `current` should be a separate THREADLOCAL variable;
382 // but it is placed here in order to share cache line with previous fields.
383 ThreadState* current;
384 // This is a slow path flag. On fast path, fast_state.GetIgnoreBit() is read.
385 // We do not distinguish beteween ignoring reads and writes
386 // for better performance.
387 int ignore_reads_and_writes;
388 atomic_sint32_t pending_signals;
389 int ignore_sync;
390 int suppress_reports;
391 // Go does not support ignores.
392#if !SANITIZER_GO0
393 IgnoreSet mop_ignore_set;
394 IgnoreSet sync_ignore_set;
395#endif
396 // C/C++ uses fixed size shadow stack embed into Trace.
397 // Go uses malloc-allocated shadow stack with dynamic size.
398 uptr *shadow_stack;
399 uptr *shadow_stack_end;
400 uptr *shadow_stack_pos;
401 RawShadow *racy_shadow_addr;
402 RawShadow racy_state[2];
403 MutexSet mset;
404 ThreadClock clock;
405#if !SANITIZER_GO0
406 Vector<JmpBuf> jmp_bufs;
407 int ignore_interceptors;
408#endif
409 const Tid tid;
410 const int unique_id;
411 bool in_symbolizer;
412 bool in_ignored_lib;
413 bool is_inited;
414 bool is_dead;
415 bool is_freeing;
416 bool is_vptr_access;
417 const uptr stk_addr;
418 const uptr stk_size;
419 const uptr tls_addr;
420 const uptr tls_size;
421 ThreadContext *tctx;
422
423 DDLogicalThread *dd_lt;
424
425 // Current wired Processor, or nullptr. Required to handle any events.
426 Processor *proc1;
427#if !SANITIZER_GO0
428 Processor *proc() { return proc1; }
429#else
430 Processor *proc();
431#endif
432
433 atomic_uintptr_t in_signal_handler;
434 ThreadSignalContext *signal_ctx;
435
436#if !SANITIZER_GO0
437 StackID last_sleep_stack_id;
438 ThreadClock last_sleep_clock;
439#endif
440
441 // Set in regions of runtime that must be signal-safe and fork-safe.
442 // If set, malloc must not be called.
443 int nomalloc;
444
445 const ReportDesc *current_report;
446
447 // Current position in tctx->trace.Back()->events (Event*).
448 atomic_uintptr_t trace_pos;
449 // PC of the last memory access, used to compute PC deltas in the trace.
450 uptr trace_prev_pc;
451 Sid sid;
452 Epoch epoch;
453
454 explicit ThreadState(Context *ctx, Tid tid, int unique_id, u64 epoch,
455 unsigned reuse_count, uptr stk_addr, uptr stk_size,
456 uptr tls_addr, uptr tls_size);
457};
458
459#if !SANITIZER_GO0
460#if SANITIZER_MAC0 || SANITIZER_ANDROID0
461ThreadState *cur_thread();
462void set_cur_thread(ThreadState *thr);
463void cur_thread_finalize();
464inline void cur_thread_init() { }
465#else
466__attribute__((tls_model("initial-exec")))
467extern THREADLOCAL__thread char cur_thread_placeholder[];
468inline ThreadState *cur_thread() {
469 return reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current;
470}
471inline void cur_thread_init() {
472 ThreadState *thr = reinterpret_cast<ThreadState *>(cur_thread_placeholder);
473 if (UNLIKELY(!thr->current)__builtin_expect(!!(!thr->current), 0))
474 thr->current = thr;
475}
476inline void set_cur_thread(ThreadState *thr) {
477 reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current = thr;
478}
479inline void cur_thread_finalize() { }
480#endif // SANITIZER_MAC || SANITIZER_ANDROID
481#endif // SANITIZER_GO
482
483class ThreadContext final : public ThreadContextBase {
484 public:
485 explicit ThreadContext(Tid tid);
486 ~ThreadContext();
487 ThreadState *thr;
488 StackID creation_stack_id;
489 SyncClock sync;
490 // Epoch at which the thread had started.
491 // If we see an event from the thread stamped by an older epoch,
492 // the event is from a dead thread that shared tid with this thread.
493 u64 epoch0;
494 u64 epoch1;
495
496 v3::Trace trace;
497
498 // Override superclass callbacks.
499 void OnDead() override;
500 void OnJoined(void *arg) override;
501 void OnFinished() override;
502 void OnStarted(void *arg) override;
503 void OnCreated(void *arg) override;
504 void OnReset() override;
505 void OnDetached(void *arg) override;
506};
507
508struct RacyStacks {
509 MD5Hash hash[2];
510 bool operator==(const RacyStacks &other) const {
511 if (hash[0] == other.hash[0] && hash[1] == other.hash[1])
512 return true;
513 if (hash[0] == other.hash[1] && hash[1] == other.hash[0])
514 return true;
515 return false;
516 }
517};
518
519struct RacyAddress {
520 uptr addr_min;
521 uptr addr_max;
522};
523
524struct FiredSuppression {
525 ReportType type;
526 uptr pc_or_addr;
527 Suppression *supp;
528};
529
530struct Context {
531 Context();
532
533 bool initialized;
534#if !SANITIZER_GO0
535 bool after_multithreaded_fork;
536#endif
537
538 MetaMap metamap;
539
540 Mutex report_mtx;
541 int nreported;
542 int nmissed_expected;
543 atomic_uint64_t last_symbolize_time_ns;
544
545 void *background_thread;
546 atomic_uint32_t stop_background_thread;
547
548 ThreadRegistry thread_registry;
549
550 Mutex racy_mtx;
551 Vector<RacyStacks> racy_stacks;
552 Vector<RacyAddress> racy_addresses;
553 // Number of fired suppressions may be large enough.
554 Mutex fired_suppressions_mtx;
555 InternalMmapVector<FiredSuppression> fired_suppressions;
556 DDetector *dd;
557
558 ClockAlloc clock_alloc;
559
560 Flags flags;
561
562 Mutex slot_mtx;
563};
564
565extern Context *ctx; // The one and the only global runtime context.
566
567ALWAYS_INLINEinline __attribute__((always_inline)) Flags *flags() {
568 return &ctx->flags;
569}
570
571struct ScopedIgnoreInterceptors {
572 ScopedIgnoreInterceptors() {
573#if !SANITIZER_GO0
574 cur_thread()->ignore_interceptors++;
575#endif
576 }
577
578 ~ScopedIgnoreInterceptors() {
579#if !SANITIZER_GO0
580 cur_thread()->ignore_interceptors--;
581#endif
582 }
583};
584
585const char *GetObjectTypeFromTag(uptr tag);
586const char *GetReportHeaderFromTag(uptr tag);
587uptr TagFromShadowStackFrame(uptr pc);
588
589class ScopedReportBase {
590 public:
591 void AddMemoryAccess(uptr addr, uptr external_tag, Shadow s, StackTrace stack,
592 const MutexSet *mset);
593 void AddStack(StackTrace stack, bool suppressable = false);
594 void AddThread(const ThreadContext *tctx, bool suppressable = false);
595 void AddThread(Tid unique_tid, bool suppressable = false);
596 void AddUniqueTid(Tid unique_tid);
597 void AddMutex(const SyncVar *s);
598 u64 AddMutex(u64 id);
599 void AddLocation(uptr addr, uptr size);
600 void AddSleep(StackID stack_id);
601 void SetCount(int count);
602
603 const ReportDesc *GetReport() const;
604
605 protected:
606 ScopedReportBase(ReportType typ, uptr tag);
607 ~ScopedReportBase();
608
609 private:
610 ReportDesc *rep_;
611 // Symbolizer makes lots of intercepted calls. If we try to process them,
612 // at best it will cause deadlocks on internal mutexes.
613 ScopedIgnoreInterceptors ignore_interceptors_;
614
615 void AddDeadMutex(u64 id);
616
617 ScopedReportBase(const ScopedReportBase &) = delete;
618 void operator=(const ScopedReportBase &) = delete;
619};
620
621class ScopedReport : public ScopedReportBase {
622 public:
623 explicit ScopedReport(ReportType typ, uptr tag = kExternalTagNone);
624 ~ScopedReport();
625
626 private:
627 ScopedErrorReportLock lock_;
628};
629
630bool ShouldReport(ThreadState *thr, ReportType typ);
631ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack);
632void RestoreStack(Tid tid, const u64 epoch, VarSizeStackTrace *stk,
633 MutexSet *mset, uptr *tag = nullptr);
634
635// The stack could look like:
636// <start> | <main> | <foo> | tag | <bar>
637// This will extract the tag and keep:
638// <start> | <main> | <foo> | <bar>
639template<typename StackTraceTy>
640void ExtractTagFromStack(StackTraceTy *stack, uptr *tag = nullptr) {
641 if (stack->size < 2) return;
642 uptr possible_tag_pc = stack->trace[stack->size - 2];
643 uptr possible_tag = TagFromShadowStackFrame(possible_tag_pc);
644 if (possible_tag == kExternalTagNone) return;
645 stack->trace_buffer[stack->size - 2] = stack->trace_buffer[stack->size - 1];
646 stack->size -= 1;
647 if (tag) *tag = possible_tag;
648}
649
650template<typename StackTraceTy>
651void ObtainCurrentStack(ThreadState *thr, uptr toppc, StackTraceTy *stack,
652 uptr *tag = nullptr) {
653 uptr size = thr->shadow_stack_pos - thr->shadow_stack;
654 uptr start = 0;
655 if (size + !!toppc > kStackTraceMax) {
656 start = size + !!toppc - kStackTraceMax;
657 size = kStackTraceMax - !!toppc;
658 }
659 stack->Init(&thr->shadow_stack[start], size, toppc);
660 ExtractTagFromStack(stack, tag);
661}
662
663#define GET_STACK_TRACE_FATAL(thr, pc)VarSizeStackTrace stack; ObtainCurrentStack(thr, pc, &stack
); stack.ReverseOrder();
\
664 VarSizeStackTrace stack; \
665 ObtainCurrentStack(thr, pc, &stack); \
666 stack.ReverseOrder();
667
668void MapShadow(uptr addr, uptr size);
669void MapThreadTrace(uptr addr, uptr size, const char *name);
670void DontNeedShadowFor(uptr addr, uptr size);
671void UnmapShadow(ThreadState *thr, uptr addr, uptr size);
672void InitializeShadowMemory();
673void InitializeInterceptors();
674void InitializeLibIgnore();
675void InitializeDynamicAnnotations();
676
677void ForkBefore(ThreadState *thr, uptr pc);
678void ForkParentAfter(ThreadState *thr, uptr pc);
679void ForkChildAfter(ThreadState *thr, uptr pc);
680
681void ReportRace(ThreadState *thr);
682bool OutputReport(ThreadState *thr, const ScopedReport &srep);
683bool IsFiredSuppression(Context *ctx, ReportType type, StackTrace trace);
684bool IsExpectedReport(uptr addr, uptr size);
685
686#if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 1
687# define DPrintf Printf
688#else
689# define DPrintf(...)
690#endif
691
692#if defined(TSAN_DEBUG_OUTPUT) && TSAN_DEBUG_OUTPUT >= 2
693# define DPrintf2 Printf
694#else
695# define DPrintf2(...)
696#endif
697
698StackID CurrentStackId(ThreadState *thr, uptr pc);
699ReportStack *SymbolizeStackId(StackID stack_id);
700void PrintCurrentStack(ThreadState *thr, uptr pc);
701void PrintCurrentStackSlow(uptr pc); // uses libunwind
702MBlock *JavaHeapBlock(uptr addr, uptr *start);
703
704void Initialize(ThreadState *thr);
705void MaybeSpawnBackgroundThread();
706int Finalize(ThreadState *thr);
707
708void OnUserAlloc(ThreadState *thr, uptr pc, uptr p, uptr sz, bool write);
709void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write);
710
711void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
712 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic);
713void MemoryAccessImpl(ThreadState *thr, uptr addr,
714 int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
715 u64 *shadow_mem, Shadow cur);
716void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
717 uptr size, bool is_write);
718void UnalignedMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
719 AccessType typ);
720
721const int kSizeLog1 = 0;
722const int kSizeLog2 = 1;
723const int kSizeLog4 = 2;
724const int kSizeLog8 = 3;
725
726ALWAYS_INLINEinline __attribute__((always_inline))
727void MemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
728 AccessType typ) {
729 int size_log;
730 switch (size) {
731 case 1:
732 size_log = kSizeLog1;
733 break;
734 case 2:
735 size_log = kSizeLog2;
736 break;
737 case 4:
738 size_log = kSizeLog4;
739 break;
740 default:
741 DCHECK_EQ(size, 8);
742 size_log = kSizeLog8;
743 break;
744 }
745 bool is_write = !(typ & kAccessRead);
746 bool is_atomic = typ & kAccessAtomic;
747 if (typ & kAccessVptr)
748 thr->is_vptr_access = true;
749 if (typ & kAccessFree)
750 thr->is_freeing = true;
751 MemoryAccess(thr, pc, addr, size_log, is_write, is_atomic);
752 if (typ & kAccessVptr)
753 thr->is_vptr_access = false;
754 if (typ & kAccessFree)
755 thr->is_freeing = false;
756}
757
758void MemoryResetRange(ThreadState *thr, uptr pc, uptr addr, uptr size);
759void MemoryRangeFreed(ThreadState *thr, uptr pc, uptr addr, uptr size);
760void MemoryRangeImitateWrite(ThreadState *thr, uptr pc, uptr addr, uptr size);
761void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
762 uptr size);
763
764void ThreadIgnoreBegin(ThreadState *thr, uptr pc);
765void ThreadIgnoreEnd(ThreadState *thr);
766void ThreadIgnoreSyncBegin(ThreadState *thr, uptr pc);
767void ThreadIgnoreSyncEnd(ThreadState *thr);
768
769void FuncEntry(ThreadState *thr, uptr pc);
770void FuncExit(ThreadState *thr);
771
772Tid ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached);
773void ThreadStart(ThreadState *thr, Tid tid, tid_t os_id,
774 ThreadType thread_type);
775void ThreadFinish(ThreadState *thr);
776Tid ThreadConsumeTid(ThreadState *thr, uptr pc, uptr uid);
777void ThreadJoin(ThreadState *thr, uptr pc, Tid tid);
778void ThreadDetach(ThreadState *thr, uptr pc, Tid tid);
779void ThreadFinalize(ThreadState *thr);
780void ThreadSetName(ThreadState *thr, const char *name);
781int ThreadCount(ThreadState *thr);
782void ProcessPendingSignalsImpl(ThreadState *thr);
783void ThreadNotJoined(ThreadState *thr, uptr pc, Tid tid, uptr uid);
784
785Processor *ProcCreate();
786void ProcDestroy(Processor *proc);
787void ProcWire(Processor *proc, ThreadState *thr);
788void ProcUnwire(Processor *proc, ThreadState *thr);
789
790// Note: the parameter is called flagz, because flags is already taken
791// by the global function that returns flags.
792void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
793void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
794void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
795void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0,
796 int rec = 1);
797int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
798void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
799void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz = 0);
800void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr);
801void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr);
802void MutexRepair(ThreadState *thr, uptr pc, uptr addr); // call on EOWNERDEAD
803void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr);
804
805void Acquire(ThreadState *thr, uptr pc, uptr addr);
806// AcquireGlobal synchronizes the current thread with all other threads.
807// In terms of happens-before relation, it draws a HB edge from all threads
808// (where they happen to execute right now) to the current thread. We use it to
809// handle Go finalizers. Namely, finalizer goroutine executes AcquireGlobal
810// right before executing finalizers. This provides a coarse, but simple
811// approximation of the actual required synchronization.
812void AcquireGlobal(ThreadState *thr);
813void Release(ThreadState *thr, uptr pc, uptr addr);
814void ReleaseStoreAcquire(ThreadState *thr, uptr pc, uptr addr);
815void ReleaseStore(ThreadState *thr, uptr pc, uptr addr);
816void AfterSleep(ThreadState *thr, uptr pc);
817void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
818void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
819void ReleaseStoreAcquireImpl(ThreadState *thr, uptr pc, SyncClock *c);
820void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c);
821void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c);
822
823// The hacky call uses custom calling convention and an assembly thunk.
824// It is considerably faster that a normal call for the caller
825// if it is not executed (it is intended for slow paths from hot functions).
826// The trick is that the call preserves all registers and the compiler
827// does not treat it as a call.
828// If it does not work for you, use normal call.
829#if !SANITIZER_DEBUG0 && defined(__x86_64__1) && !SANITIZER_MAC0
830// The caller may not create the stack frame for itself at all,
831// so we create a reserve stack frame for it (1024b must be enough).
832#define HACKY_CALL(f)__asm__ __volatile__("sub $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"1024" ";" ".hidden " "f" "_thunk;" "call " "f" "_thunk;" "add $1024, %%rsp;"
".cfi_adjust_cfa_offset " "-1024" ";" ::: "memory", "cc");
\
833 __asm__ __volatile__("sub $1024, %%rsp;" \
834 CFI_INL_ADJUST_CFA_OFFSET(1024)".cfi_adjust_cfa_offset " "1024" ";" \
835 ".hidden " #f "_thunk;" \
836 "call " #f "_thunk;" \
837 "add $1024, %%rsp;" \
838 CFI_INL_ADJUST_CFA_OFFSET(-1024)".cfi_adjust_cfa_offset " "-1024" ";" \
839 ::: "memory", "cc");
840#else
841#define HACKY_CALL(f)__asm__ __volatile__("sub $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"1024" ";" ".hidden " "f" "_thunk;" "call " "f" "_thunk;" "add $1024, %%rsp;"
".cfi_adjust_cfa_offset " "-1024" ";" ::: "memory", "cc");
f()
842#endif
843
844void TraceSwitch(ThreadState *thr);
845uptr TraceTopPC(ThreadState *thr);
846uptr TraceSize();
847uptr TraceParts();
848Trace *ThreadTrace(Tid tid);
849
850extern "C" void __tsan_trace_switch();
851void ALWAYS_INLINEinline __attribute__((always_inline)) TraceAddEvent(ThreadState *thr, FastState fs,
852 EventType typ, u64 addr) {
853 if (!kCollectHistory)
854 return;
855 DCHECK_GE((int)typ, 0);
856 DCHECK_LE((int)typ, 7);
857 DCHECK_EQ(GetLsb(addr, kEventPCBits), addr);
858 u64 pos = fs.GetTracePos();
859 if (UNLIKELY((pos % kTracePartSize) == 0)__builtin_expect(!!((pos % kTracePartSize) == 0), 0)) {
860#if !SANITIZER_GO0
861 HACKY_CALL(__tsan_trace_switch)__asm__ __volatile__("sub $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"1024" ";" ".hidden " "__tsan_trace_switch" "_thunk;" "call "
"__tsan_trace_switch" "_thunk;" "add $1024, %%rsp;" ".cfi_adjust_cfa_offset "
"-1024" ";" ::: "memory", "cc");
;
862#else
863 TraceSwitch(thr);
864#endif
865 }
866 Event *trace = (Event*)GetThreadTrace(fs.tid());
867 Event *evp = &trace[pos];
868 Event ev = (u64)addr | ((u64)typ << kEventPCBits);
869 *evp = ev;
870}
871
872#if !SANITIZER_GO0
873uptr ALWAYS_INLINEinline __attribute__((always_inline)) HeapEnd() {
874 return HeapMemEnd() + PrimaryAllocator::AdditionalSize();
875}
876#endif
877
878ThreadState *FiberCreate(ThreadState *thr, uptr pc, unsigned flags);
879void FiberDestroy(ThreadState *thr, uptr pc, ThreadState *fiber);
880void FiberSwitch(ThreadState *thr, uptr pc, ThreadState *fiber, unsigned flags);
881
882// These need to match __tsan_switch_to_fiber_* flags defined in
883// tsan_interface.h. See documentation there as well.
884enum FiberSwitchFlags {
885 FiberSwitchFlagNoSync = 1 << 0, // __tsan_switch_to_fiber_no_sync
886};
887
888ALWAYS_INLINEinline __attribute__((always_inline)) void ProcessPendingSignals(ThreadState *thr) {
889 if (UNLIKELY(atomic_load_relaxed(&thr->pending_signals))__builtin_expect(!!(atomic_load_relaxed(&thr->pending_signals
)), 0)
)
890 ProcessPendingSignalsImpl(thr);
891}
892
893extern bool is_initialized;
894
895ALWAYS_INLINEinline __attribute__((always_inline))
896void LazyInitialize(ThreadState *thr) {
897 // If we can use .preinit_array, assume that __tsan_init
898 // called from .preinit_array initializes runtime before
899 // any instrumented code.
900#if !SANITIZER_CAN_USE_PREINIT_ARRAY1
901 if (UNLIKELY(!is_initialized)__builtin_expect(!!(!is_initialized), 0))
902 Initialize(thr);
903#endif
904}
905
906namespace v3 {
907
908void TraceSwitchPart(ThreadState *thr);
909bool RestoreStack(Tid tid, EventType type, Sid sid, Epoch epoch, uptr addr,
910 uptr size, AccessType typ, VarSizeStackTrace *pstk,
911 MutexSet *pmset, uptr *ptag);
912
913template <typename EventT>
914ALWAYS_INLINEinline __attribute__((always_inline)) WARN_UNUSED_RESULT__attribute__((warn_unused_result)) bool TraceAcquire(ThreadState *thr,
915 EventT **ev) {
916 Event *pos = reinterpret_cast<Event *>(atomic_load_relaxed(&thr->trace_pos));
917#if SANITIZER_DEBUG0
918 // TraceSwitch acquires these mutexes,
919 // so we lock them here to detect deadlocks more reliably.
920 { Lock lock(&ctx->slot_mtx); }
921 { Lock lock(&thr->tctx->trace.mtx); }
922 TracePart *current = thr->tctx->trace.parts.Back();
923 if (current) {
924 DCHECK_GE(pos, &current->events[0]);
925 DCHECK_LE(pos, &current->events[TracePart::kSize]);
926 } else {
927 DCHECK_EQ(pos, nullptr);
928 }
929#endif
930 // TracePart is allocated with mmap and is at least 4K aligned.
931 // So the following check is a faster way to check for part end.
932 // It may have false positives in the middle of the trace,
933 // they are filtered out in TraceSwitch.
934 if (UNLIKELY(((uptr)(pos + 1) & TracePart::kAlignment) == 0)__builtin_expect(!!(((uptr)(pos + 1) & TracePart::kAlignment
) == 0), 0)
)
5
Assuming the condition is true
6
Taking true branch
11
Assuming the condition is true
12
Taking true branch
935 return false;
7
Returning without writing to '*ev'
13
Returning without writing to '*ev'
936 *ev = reinterpret_cast<EventT *>(pos);
937 return true;
938}
939
940template <typename EventT>
941ALWAYS_INLINEinline __attribute__((always_inline)) void TraceRelease(ThreadState *thr, EventT *evp) {
942 DCHECK_LE(evp + 1, &thr->tctx->trace.parts.Back()->events[TracePart::kSize]);
943 atomic_store_relaxed(&thr->trace_pos, (uptr)(evp + 1));
944}
945
946template <typename EventT>
947void TraceEvent(ThreadState *thr, EventT ev) {
948 EventT *evp;
3
'evp' declared without an initial value
949 if (!TraceAcquire(thr, &evp)) {
4
Calling 'TraceAcquire<__tsan::v3::EventUnlock>'
8
Returning from 'TraceAcquire<__tsan::v3::EventUnlock>'
9
Taking true branch
950 TraceSwitchPart(thr);
951 UNUSED__attribute__((unused)) bool res = TraceAcquire(thr, &evp);
10
Calling 'TraceAcquire<__tsan::v3::EventUnlock>'
14
Returning from 'TraceAcquire<__tsan::v3::EventUnlock>'
952 DCHECK(res);
953 }
954 *evp = ev;
15
Called C++ object pointer is uninitialized
955 TraceRelease(thr, evp);
956}
957
958ALWAYS_INLINEinline __attribute__((always_inline)) WARN_UNUSED_RESULT__attribute__((warn_unused_result)) bool TryTraceFunc(ThreadState *thr,
959 uptr pc = 0) {
960 if (!kCollectHistory)
961 return true;
962 EventFunc *ev;
963 if (UNLIKELY(!TraceAcquire(thr, &ev))__builtin_expect(!!(!TraceAcquire(thr, &ev)), 0))
964 return false;
965 ev->is_access = 0;
966 ev->is_func = 1;
967 ev->pc = pc;
968 TraceRelease(thr, ev);
969 return true;
970}
971
972WARN_UNUSED_RESULT__attribute__((warn_unused_result))
973bool TryTraceMemoryAccess(ThreadState *thr, uptr pc, uptr addr, uptr size,
974 AccessType typ);
975WARN_UNUSED_RESULT__attribute__((warn_unused_result))
976bool TryTraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
977 AccessType typ);
978void TraceMemoryAccessRange(ThreadState *thr, uptr pc, uptr addr, uptr size,
979 AccessType typ);
980void TraceFunc(ThreadState *thr, uptr pc = 0);
981void TraceMutexLock(ThreadState *thr, EventType type, uptr pc, uptr addr,
982 StackID stk);
983void TraceMutexUnlock(ThreadState *thr, uptr addr);
984void TraceTime(ThreadState *thr);
985
986} // namespace v3
987
988} // namespace __tsan
989
990#endif // TSAN_RTL_H