tsan_interceptors_posix.cpp 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  1. //===-- tsan_interceptors_posix.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. // FIXME: move as many interceptors as possible into
  12. // sanitizer_common/sanitizer_common_interceptors.inc
  13. //===----------------------------------------------------------------------===//
  14. #include "sanitizer_common/sanitizer_atomic.h"
  15. #include "sanitizer_common/sanitizer_errno.h"
  16. #include "sanitizer_common/sanitizer_libc.h"
  17. #include "sanitizer_common/sanitizer_linux.h"
  18. #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
  19. #include "sanitizer_common/sanitizer_platform_limits_posix.h"
  20. #include "sanitizer_common/sanitizer_placement_new.h"
  21. #include "sanitizer_common/sanitizer_posix.h"
  22. #include "sanitizer_common/sanitizer_stacktrace.h"
  23. #include "sanitizer_common/sanitizer_tls_get_addr.h"
  24. #include "interception/interception.h"
  25. #include "tsan_interceptors.h"
  26. #include "tsan_interface.h"
  27. #include "tsan_platform.h"
  28. #include "tsan_suppressions.h"
  29. #include "tsan_rtl.h"
  30. #include "tsan_mman.h"
  31. #include "tsan_fd.h"
  32. #include <stdarg.h>
  33. using namespace __tsan;
  34. #if SANITIZER_FREEBSD || SANITIZER_MAC
  35. #define stdout __stdoutp
  36. #define stderr __stderrp
  37. #endif
  38. #if SANITIZER_NETBSD
  39. #define dirfd(dirp) (*(int *)(dirp))
  40. #define fileno_unlocked(fp) \
  41. (((__sanitizer_FILE *)fp)->_file == -1 \
  42. ? -1 \
  43. : (int)(unsigned short)(((__sanitizer_FILE *)fp)->_file))
  44. #define stdout ((__sanitizer_FILE*)&__sF[1])
  45. #define stderr ((__sanitizer_FILE*)&__sF[2])
  46. #define nanosleep __nanosleep50
  47. #define vfork __vfork14
  48. #endif
  49. #ifdef __mips__
  50. const int kSigCount = 129;
  51. #else
  52. const int kSigCount = 65;
  53. #endif
  54. #ifdef __mips__
  55. struct ucontext_t {
  56. u64 opaque[768 / sizeof(u64) + 1];
  57. };
  58. #else
  59. struct ucontext_t {
  60. // The size is determined by looking at sizeof of real ucontext_t on linux.
  61. u64 opaque[936 / sizeof(u64) + 1];
  62. };
  63. #endif
  64. #if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 || \
  65. defined(__s390x__)
  66. #define PTHREAD_ABI_BASE "GLIBC_2.3.2"
  67. #elif defined(__aarch64__) || SANITIZER_PPC64V2
  68. #define PTHREAD_ABI_BASE "GLIBC_2.17"
  69. #endif
  70. extern "C" int pthread_attr_init(void *attr);
  71. extern "C" int pthread_attr_destroy(void *attr);
  72. DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
  73. extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
  74. extern "C" int pthread_atfork(void (*prepare)(void), void (*parent)(void),
  75. void (*child)(void));
  76. extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
  77. extern "C" int pthread_setspecific(unsigned key, const void *v);
  78. DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
  79. DECLARE_REAL(int, fflush, __sanitizer_FILE *fp)
  80. DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr size)
  81. DECLARE_REAL_AND_INTERCEPTOR(void, free, void *ptr)
  82. extern "C" void *pthread_self();
  83. extern "C" void _exit(int status);
  84. #if !SANITIZER_NETBSD
  85. extern "C" int fileno_unlocked(void *stream);
  86. extern "C" int dirfd(void *dirp);
  87. #endif
  88. #if SANITIZER_NETBSD
  89. extern __sanitizer_FILE __sF[];
  90. #else
  91. extern __sanitizer_FILE *stdout, *stderr;
  92. #endif
  93. #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
  94. const int PTHREAD_MUTEX_RECURSIVE = 1;
  95. const int PTHREAD_MUTEX_RECURSIVE_NP = 1;
  96. #else
  97. const int PTHREAD_MUTEX_RECURSIVE = 2;
  98. const int PTHREAD_MUTEX_RECURSIVE_NP = 2;
  99. #endif
  100. #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
  101. const int EPOLL_CTL_ADD = 1;
  102. #endif
  103. const int SIGILL = 4;
  104. const int SIGTRAP = 5;
  105. const int SIGABRT = 6;
  106. const int SIGFPE = 8;
  107. const int SIGSEGV = 11;
  108. const int SIGPIPE = 13;
  109. const int SIGTERM = 15;
  110. #if defined(__mips__) || SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
  111. const int SIGBUS = 10;
  112. const int SIGSYS = 12;
  113. #else
  114. const int SIGBUS = 7;
  115. const int SIGSYS = 31;
  116. #endif
  117. void *const MAP_FAILED = (void*)-1;
  118. #if SANITIZER_NETBSD
  119. const int PTHREAD_BARRIER_SERIAL_THREAD = 1234567;
  120. #elif !SANITIZER_MAC
  121. const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
  122. #endif
  123. const int MAP_FIXED = 0x10;
  124. typedef long long_t;
  125. typedef __sanitizer::u16 mode_t;
  126. // From /usr/include/unistd.h
  127. # define F_ULOCK 0 /* Unlock a previously locked region. */
  128. # define F_LOCK 1 /* Lock a region for exclusive use. */
  129. # define F_TLOCK 2 /* Test and lock a region for exclusive use. */
  130. # define F_TEST 3 /* Test a region for other processes locks. */
  131. #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD
  132. const int SA_SIGINFO = 0x40;
  133. const int SIG_SETMASK = 3;
  134. #elif defined(__mips__)
  135. const int SA_SIGINFO = 8;
  136. const int SIG_SETMASK = 3;
  137. #else
  138. const int SA_SIGINFO = 4;
  139. const int SIG_SETMASK = 2;
  140. #endif
  141. #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED \
  142. (!cur_thread_init()->is_inited)
  143. namespace __tsan {
  144. struct SignalDesc {
  145. bool armed;
  146. __sanitizer_siginfo siginfo;
  147. ucontext_t ctx;
  148. };
  149. struct ThreadSignalContext {
  150. int int_signal_send;
  151. atomic_uintptr_t in_blocking_func;
  152. SignalDesc pending_signals[kSigCount];
  153. // emptyset and oldset are too big for stack.
  154. __sanitizer_sigset_t emptyset;
  155. __sanitizer_sigset_t oldset;
  156. };
  157. // The sole reason tsan wraps atexit callbacks is to establish synchronization
  158. // between callback setup and callback execution.
  159. struct AtExitCtx {
  160. void (*f)();
  161. void *arg;
  162. };
  163. // InterceptorContext holds all global data required for interceptors.
  164. // It's explicitly constructed in InitializeInterceptors with placement new
  165. // and is never destroyed. This allows usage of members with non-trivial
  166. // constructors and destructors.
  167. struct InterceptorContext {
  168. // The object is 64-byte aligned, because we want hot data to be located
  169. // in a single cache line if possible (it's accessed in every interceptor).
  170. ALIGNED(64) LibIgnore libignore;
  171. __sanitizer_sigaction sigactions[kSigCount];
  172. #if !SANITIZER_MAC && !SANITIZER_NETBSD
  173. unsigned finalize_key;
  174. #endif
  175. Mutex atexit_mu;
  176. Vector<struct AtExitCtx *> AtExitStack;
  177. InterceptorContext() : libignore(LINKER_INITIALIZED), atexit_mu(MutexTypeAtExit), AtExitStack() {}
  178. };
  179. static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)];
  180. InterceptorContext *interceptor_ctx() {
  181. return reinterpret_cast<InterceptorContext*>(&interceptor_placeholder[0]);
  182. }
  183. LibIgnore *libignore() {
  184. return &interceptor_ctx()->libignore;
  185. }
  186. void InitializeLibIgnore() {
  187. const SuppressionContext &supp = *Suppressions();
  188. const uptr n = supp.SuppressionCount();
  189. for (uptr i = 0; i < n; i++) {
  190. const Suppression *s = supp.SuppressionAt(i);
  191. if (0 == internal_strcmp(s->type, kSuppressionLib))
  192. libignore()->AddIgnoredLibrary(s->templ);
  193. }
  194. if (flags()->ignore_noninstrumented_modules)
  195. libignore()->IgnoreNoninstrumentedModules(true);
  196. libignore()->OnLibraryLoaded(0);
  197. }
  198. // The following two hooks can be used by for cooperative scheduling when
  199. // locking.
  200. #ifdef TSAN_EXTERNAL_HOOKS
  201. void OnPotentiallyBlockingRegionBegin();
  202. void OnPotentiallyBlockingRegionEnd();
  203. #else
  204. SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionBegin() {}
  205. SANITIZER_WEAK_CXX_DEFAULT_IMPL void OnPotentiallyBlockingRegionEnd() {}
  206. #endif
  207. } // namespace __tsan
  208. static ThreadSignalContext *SigCtx(ThreadState *thr) {
  209. ThreadSignalContext *ctx = (ThreadSignalContext*)thr->signal_ctx;
  210. if (ctx == 0 && !thr->is_dead) {
  211. ctx = (ThreadSignalContext*)MmapOrDie(sizeof(*ctx), "ThreadSignalContext");
  212. MemoryResetRange(thr, (uptr)&SigCtx, (uptr)ctx, sizeof(*ctx));
  213. thr->signal_ctx = ctx;
  214. }
  215. return ctx;
  216. }
  217. ScopedInterceptor::ScopedInterceptor(ThreadState *thr, const char *fname,
  218. uptr pc)
  219. : thr_(thr), in_ignored_lib_(false), ignoring_(false) {
  220. LazyInitialize(thr);
  221. if (!thr_->is_inited) return;
  222. if (!thr_->ignore_interceptors) FuncEntry(thr, pc);
  223. DPrintf("#%d: intercept %s()\n", thr_->tid, fname);
  224. ignoring_ =
  225. !thr_->in_ignored_lib && (flags()->ignore_interceptors_accesses ||
  226. libignore()->IsIgnored(pc, &in_ignored_lib_));
  227. EnableIgnores();
  228. }
  229. ScopedInterceptor::~ScopedInterceptor() {
  230. if (!thr_->is_inited) return;
  231. DisableIgnores();
  232. if (!thr_->ignore_interceptors) {
  233. ProcessPendingSignals(thr_);
  234. FuncExit(thr_);
  235. CheckedMutex::CheckNoLocks();
  236. }
  237. }
  238. NOINLINE
  239. void ScopedInterceptor::EnableIgnoresImpl() {
  240. ThreadIgnoreBegin(thr_, 0);
  241. if (flags()->ignore_noninstrumented_modules)
  242. thr_->suppress_reports++;
  243. if (in_ignored_lib_) {
  244. DCHECK(!thr_->in_ignored_lib);
  245. thr_->in_ignored_lib = true;
  246. }
  247. }
  248. NOINLINE
  249. void ScopedInterceptor::DisableIgnoresImpl() {
  250. ThreadIgnoreEnd(thr_);
  251. if (flags()->ignore_noninstrumented_modules)
  252. thr_->suppress_reports--;
  253. if (in_ignored_lib_) {
  254. DCHECK(thr_->in_ignored_lib);
  255. thr_->in_ignored_lib = false;
  256. }
  257. }
  258. #define TSAN_INTERCEPT(func) INTERCEPT_FUNCTION(func)
  259. #if SANITIZER_FREEBSD
  260. # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
  261. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
  262. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
  263. #elif SANITIZER_NETBSD
  264. # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION(func)
  265. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func) \
  266. INTERCEPT_FUNCTION(__libc_##func)
  267. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func) \
  268. INTERCEPT_FUNCTION(__libc_thr_##func)
  269. #else
  270. # define TSAN_INTERCEPT_VER(func, ver) INTERCEPT_FUNCTION_VER(func, ver)
  271. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(func)
  272. # define TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(func)
  273. #endif
  274. #define READ_STRING_OF_LEN(thr, pc, s, len, n) \
  275. MemoryAccessRange((thr), (pc), (uptr)(s), \
  276. common_flags()->strict_string_checks ? (len) + 1 : (n), false)
  277. #define READ_STRING(thr, pc, s, n) \
  278. READ_STRING_OF_LEN((thr), (pc), (s), internal_strlen(s), (n))
  279. #define BLOCK_REAL(name) (BlockingCall(thr), REAL(name))
  280. struct BlockingCall {
  281. explicit BlockingCall(ThreadState *thr)
  282. : thr(thr)
  283. , ctx(SigCtx(thr)) {
  284. for (;;) {
  285. atomic_store(&ctx->in_blocking_func, 1, memory_order_relaxed);
  286. if (atomic_load(&thr->pending_signals, memory_order_relaxed) == 0)
  287. break;
  288. atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
  289. ProcessPendingSignals(thr);
  290. }
  291. // When we are in a "blocking call", we process signals asynchronously
  292. // (right when they arrive). In this context we do not expect to be
  293. // executing any user/runtime code. The known interceptor sequence when
  294. // this is not true is: pthread_join -> munmap(stack). It's fine
  295. // to ignore munmap in this case -- we handle stack shadow separately.
  296. thr->ignore_interceptors++;
  297. }
  298. ~BlockingCall() {
  299. thr->ignore_interceptors--;
  300. atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
  301. }
  302. ThreadState *thr;
  303. ThreadSignalContext *ctx;
  304. };
  305. TSAN_INTERCEPTOR(unsigned, sleep, unsigned sec) {
  306. SCOPED_TSAN_INTERCEPTOR(sleep, sec);
  307. unsigned res = BLOCK_REAL(sleep)(sec);
  308. AfterSleep(thr, pc);
  309. return res;
  310. }
  311. TSAN_INTERCEPTOR(int, usleep, long_t usec) {
  312. SCOPED_TSAN_INTERCEPTOR(usleep, usec);
  313. int res = BLOCK_REAL(usleep)(usec);
  314. AfterSleep(thr, pc);
  315. return res;
  316. }
  317. TSAN_INTERCEPTOR(int, nanosleep, void *req, void *rem) {
  318. SCOPED_TSAN_INTERCEPTOR(nanosleep, req, rem);
  319. int res = BLOCK_REAL(nanosleep)(req, rem);
  320. AfterSleep(thr, pc);
  321. return res;
  322. }
  323. TSAN_INTERCEPTOR(int, pause, int fake) {
  324. SCOPED_TSAN_INTERCEPTOR(pause, fake);
  325. return BLOCK_REAL(pause)(fake);
  326. }
  327. static void at_exit_wrapper() {
  328. AtExitCtx *ctx;
  329. {
  330. // Ensure thread-safety.
  331. Lock l(&interceptor_ctx()->atexit_mu);
  332. // Pop AtExitCtx from the top of the stack of callback functions
  333. uptr element = interceptor_ctx()->AtExitStack.Size() - 1;
  334. ctx = interceptor_ctx()->AtExitStack[element];
  335. interceptor_ctx()->AtExitStack.PopBack();
  336. }
  337. Acquire(cur_thread(), (uptr)0, (uptr)ctx);
  338. ((void(*)())ctx->f)();
  339. Free(ctx);
  340. }
  341. static void cxa_at_exit_wrapper(void *arg) {
  342. Acquire(cur_thread(), 0, (uptr)arg);
  343. AtExitCtx *ctx = (AtExitCtx*)arg;
  344. ((void(*)(void *arg))ctx->f)(ctx->arg);
  345. Free(ctx);
  346. }
  347. static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
  348. void *arg, void *dso);
  349. #if !SANITIZER_ANDROID
  350. TSAN_INTERCEPTOR(int, atexit, void (*f)()) {
  351. if (in_symbolizer())
  352. return 0;
  353. // We want to setup the atexit callback even if we are in ignored lib
  354. // or after fork.
  355. SCOPED_INTERCEPTOR_RAW(atexit, f);
  356. return setup_at_exit_wrapper(thr, pc, (void(*)())f, 0, 0);
  357. }
  358. #endif
  359. TSAN_INTERCEPTOR(int, __cxa_atexit, void (*f)(void *a), void *arg, void *dso) {
  360. if (in_symbolizer())
  361. return 0;
  362. SCOPED_TSAN_INTERCEPTOR(__cxa_atexit, f, arg, dso);
  363. return setup_at_exit_wrapper(thr, pc, (void(*)())f, arg, dso);
  364. }
  365. static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
  366. void *arg, void *dso) {
  367. auto *ctx = New<AtExitCtx>();
  368. ctx->f = f;
  369. ctx->arg = arg;
  370. Release(thr, pc, (uptr)ctx);
  371. // Memory allocation in __cxa_atexit will race with free during exit,
  372. // because we do not see synchronization around atexit callback list.
  373. ThreadIgnoreBegin(thr, pc);
  374. int res;
  375. if (!dso) {
  376. // NetBSD does not preserve the 2nd argument if dso is equal to 0
  377. // Store ctx in a local stack-like structure
  378. // Ensure thread-safety.
  379. Lock l(&interceptor_ctx()->atexit_mu);
  380. // __cxa_atexit calls calloc. If we don't ignore interceptors, we will fail
  381. // due to atexit_mu held on exit from the calloc interceptor.
  382. ScopedIgnoreInterceptors ignore;
  383. res = REAL(__cxa_atexit)((void (*)(void *a))at_exit_wrapper, 0, 0);
  384. // Push AtExitCtx on the top of the stack of callback functions
  385. if (!res) {
  386. interceptor_ctx()->AtExitStack.PushBack(ctx);
  387. }
  388. } else {
  389. res = REAL(__cxa_atexit)(cxa_at_exit_wrapper, ctx, dso);
  390. }
  391. ThreadIgnoreEnd(thr);
  392. return res;
  393. }
  394. #if !SANITIZER_MAC && !SANITIZER_NETBSD
  395. static void on_exit_wrapper(int status, void *arg) {
  396. ThreadState *thr = cur_thread();
  397. uptr pc = 0;
  398. Acquire(thr, pc, (uptr)arg);
  399. AtExitCtx *ctx = (AtExitCtx*)arg;
  400. ((void(*)(int status, void *arg))ctx->f)(status, ctx->arg);
  401. Free(ctx);
  402. }
  403. TSAN_INTERCEPTOR(int, on_exit, void(*f)(int, void*), void *arg) {
  404. if (in_symbolizer())
  405. return 0;
  406. SCOPED_TSAN_INTERCEPTOR(on_exit, f, arg);
  407. auto *ctx = New<AtExitCtx>();
  408. ctx->f = (void(*)())f;
  409. ctx->arg = arg;
  410. Release(thr, pc, (uptr)ctx);
  411. // Memory allocation in __cxa_atexit will race with free during exit,
  412. // because we do not see synchronization around atexit callback list.
  413. ThreadIgnoreBegin(thr, pc);
  414. int res = REAL(on_exit)(on_exit_wrapper, ctx);
  415. ThreadIgnoreEnd(thr);
  416. return res;
  417. }
  418. #define TSAN_MAYBE_INTERCEPT_ON_EXIT TSAN_INTERCEPT(on_exit)
  419. #else
  420. #define TSAN_MAYBE_INTERCEPT_ON_EXIT
  421. #endif
  422. // Cleanup old bufs.
  423. static void JmpBufGarbageCollect(ThreadState *thr, uptr sp) {
  424. for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
  425. JmpBuf *buf = &thr->jmp_bufs[i];
  426. if (buf->sp <= sp) {
  427. uptr sz = thr->jmp_bufs.Size();
  428. internal_memcpy(buf, &thr->jmp_bufs[sz - 1], sizeof(*buf));
  429. thr->jmp_bufs.PopBack();
  430. i--;
  431. }
  432. }
  433. }
  434. static void SetJmp(ThreadState *thr, uptr sp) {
  435. if (!thr->is_inited) // called from libc guts during bootstrap
  436. return;
  437. // Cleanup old bufs.
  438. JmpBufGarbageCollect(thr, sp);
  439. // Remember the buf.
  440. JmpBuf *buf = thr->jmp_bufs.PushBack();
  441. buf->sp = sp;
  442. buf->shadow_stack_pos = thr->shadow_stack_pos;
  443. ThreadSignalContext *sctx = SigCtx(thr);
  444. buf->int_signal_send = sctx ? sctx->int_signal_send : 0;
  445. buf->in_blocking_func = sctx ?
  446. atomic_load(&sctx->in_blocking_func, memory_order_relaxed) :
  447. false;
  448. buf->in_signal_handler = atomic_load(&thr->in_signal_handler,
  449. memory_order_relaxed);
  450. }
  451. static void LongJmp(ThreadState *thr, uptr *env) {
  452. uptr sp = ExtractLongJmpSp(env);
  453. // Find the saved buf with matching sp.
  454. for (uptr i = 0; i < thr->jmp_bufs.Size(); i++) {
  455. JmpBuf *buf = &thr->jmp_bufs[i];
  456. if (buf->sp == sp) {
  457. CHECK_GE(thr->shadow_stack_pos, buf->shadow_stack_pos);
  458. // Unwind the stack.
  459. while (thr->shadow_stack_pos > buf->shadow_stack_pos)
  460. FuncExit(thr);
  461. ThreadSignalContext *sctx = SigCtx(thr);
  462. if (sctx) {
  463. sctx->int_signal_send = buf->int_signal_send;
  464. atomic_store(&sctx->in_blocking_func, buf->in_blocking_func,
  465. memory_order_relaxed);
  466. }
  467. atomic_store(&thr->in_signal_handler, buf->in_signal_handler,
  468. memory_order_relaxed);
  469. JmpBufGarbageCollect(thr, buf->sp - 1); // do not collect buf->sp
  470. return;
  471. }
  472. }
  473. Printf("ThreadSanitizer: can't find longjmp buf\n");
  474. CHECK(0);
  475. }
  476. // FIXME: put everything below into a common extern "C" block?
  477. extern "C" void __tsan_setjmp(uptr sp) { SetJmp(cur_thread_init(), sp); }
  478. #if SANITIZER_MAC
  479. TSAN_INTERCEPTOR(int, setjmp, void *env);
  480. TSAN_INTERCEPTOR(int, _setjmp, void *env);
  481. TSAN_INTERCEPTOR(int, sigsetjmp, void *env);
  482. #else // SANITIZER_MAC
  483. #if SANITIZER_NETBSD
  484. #define setjmp_symname __setjmp14
  485. #define sigsetjmp_symname __sigsetjmp14
  486. #else
  487. #define setjmp_symname setjmp
  488. #define sigsetjmp_symname sigsetjmp
  489. #endif
  490. #define TSAN_INTERCEPTOR_SETJMP_(x) __interceptor_ ## x
  491. #define TSAN_INTERCEPTOR_SETJMP__(x) TSAN_INTERCEPTOR_SETJMP_(x)
  492. #define TSAN_INTERCEPTOR_SETJMP TSAN_INTERCEPTOR_SETJMP__(setjmp_symname)
  493. #define TSAN_INTERCEPTOR_SIGSETJMP TSAN_INTERCEPTOR_SETJMP__(sigsetjmp_symname)
  494. #define TSAN_STRING_SETJMP SANITIZER_STRINGIFY(setjmp_symname)
  495. #define TSAN_STRING_SIGSETJMP SANITIZER_STRINGIFY(sigsetjmp_symname)
  496. // Not called. Merely to satisfy TSAN_INTERCEPT().
  497. extern "C" SANITIZER_INTERFACE_ATTRIBUTE
  498. int TSAN_INTERCEPTOR_SETJMP(void *env);
  499. extern "C" int TSAN_INTERCEPTOR_SETJMP(void *env) {
  500. CHECK(0);
  501. return 0;
  502. }
  503. // FIXME: any reason to have a separate declaration?
  504. extern "C" SANITIZER_INTERFACE_ATTRIBUTE
  505. int __interceptor__setjmp(void *env);
  506. extern "C" int __interceptor__setjmp(void *env) {
  507. CHECK(0);
  508. return 0;
  509. }
  510. extern "C" SANITIZER_INTERFACE_ATTRIBUTE
  511. int TSAN_INTERCEPTOR_SIGSETJMP(void *env);
  512. extern "C" int TSAN_INTERCEPTOR_SIGSETJMP(void *env) {
  513. CHECK(0);
  514. return 0;
  515. }
  516. #if !SANITIZER_NETBSD
  517. extern "C" SANITIZER_INTERFACE_ATTRIBUTE
  518. int __interceptor___sigsetjmp(void *env);
  519. extern "C" int __interceptor___sigsetjmp(void *env) {
  520. CHECK(0);
  521. return 0;
  522. }
  523. #endif
  524. extern "C" int setjmp_symname(void *env);
  525. extern "C" int _setjmp(void *env);
  526. extern "C" int sigsetjmp_symname(void *env);
  527. #if !SANITIZER_NETBSD
  528. extern "C" int __sigsetjmp(void *env);
  529. #endif
  530. DEFINE_REAL(int, setjmp_symname, void *env)
  531. DEFINE_REAL(int, _setjmp, void *env)
  532. DEFINE_REAL(int, sigsetjmp_symname, void *env)
  533. #if !SANITIZER_NETBSD
  534. DEFINE_REAL(int, __sigsetjmp, void *env)
  535. #endif
  536. #endif // SANITIZER_MAC
  537. #if SANITIZER_NETBSD
  538. #define longjmp_symname __longjmp14
  539. #define siglongjmp_symname __siglongjmp14
  540. #else
  541. #define longjmp_symname longjmp
  542. #define siglongjmp_symname siglongjmp
  543. #endif
  544. TSAN_INTERCEPTOR(void, longjmp_symname, uptr *env, int val) {
  545. // Note: if we call REAL(longjmp) in the context of ScopedInterceptor,
  546. // bad things will happen. We will jump over ScopedInterceptor dtor and can
  547. // leave thr->in_ignored_lib set.
  548. {
  549. SCOPED_INTERCEPTOR_RAW(longjmp_symname, env, val);
  550. }
  551. LongJmp(cur_thread(), env);
  552. REAL(longjmp_symname)(env, val);
  553. }
  554. TSAN_INTERCEPTOR(void, siglongjmp_symname, uptr *env, int val) {
  555. {
  556. SCOPED_INTERCEPTOR_RAW(siglongjmp_symname, env, val);
  557. }
  558. LongJmp(cur_thread(), env);
  559. REAL(siglongjmp_symname)(env, val);
  560. }
  561. #if SANITIZER_NETBSD
  562. TSAN_INTERCEPTOR(void, _longjmp, uptr *env, int val) {
  563. {
  564. SCOPED_INTERCEPTOR_RAW(_longjmp, env, val);
  565. }
  566. LongJmp(cur_thread(), env);
  567. REAL(_longjmp)(env, val);
  568. }
  569. #endif
  570. #if !SANITIZER_MAC
  571. TSAN_INTERCEPTOR(void*, malloc, uptr size) {
  572. if (in_symbolizer())
  573. return InternalAlloc(size);
  574. void *p = 0;
  575. {
  576. SCOPED_INTERCEPTOR_RAW(malloc, size);
  577. p = user_alloc(thr, pc, size);
  578. }
  579. invoke_malloc_hook(p, size);
  580. return p;
  581. }
  582. // In glibc<2.25, dynamic TLS blocks are allocated by __libc_memalign. Intercept
  583. // __libc_memalign so that (1) we can detect races (2) free will not be called
  584. // on libc internally allocated blocks.
  585. TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
  586. SCOPED_INTERCEPTOR_RAW(__libc_memalign, align, sz);
  587. return user_memalign(thr, pc, align, sz);
  588. }
  589. TSAN_INTERCEPTOR(void*, calloc, uptr size, uptr n) {
  590. if (in_symbolizer())
  591. return InternalCalloc(size, n);
  592. void *p = 0;
  593. {
  594. SCOPED_INTERCEPTOR_RAW(calloc, size, n);
  595. p = user_calloc(thr, pc, size, n);
  596. }
  597. invoke_malloc_hook(p, n * size);
  598. return p;
  599. }
  600. TSAN_INTERCEPTOR(void*, realloc, void *p, uptr size) {
  601. if (in_symbolizer())
  602. return InternalRealloc(p, size);
  603. if (p)
  604. invoke_free_hook(p);
  605. {
  606. SCOPED_INTERCEPTOR_RAW(realloc, p, size);
  607. p = user_realloc(thr, pc, p, size);
  608. }
  609. invoke_malloc_hook(p, size);
  610. return p;
  611. }
  612. TSAN_INTERCEPTOR(void*, reallocarray, void *p, uptr size, uptr n) {
  613. if (in_symbolizer())
  614. return InternalReallocArray(p, size, n);
  615. if (p)
  616. invoke_free_hook(p);
  617. {
  618. SCOPED_INTERCEPTOR_RAW(reallocarray, p, size, n);
  619. p = user_reallocarray(thr, pc, p, size, n);
  620. }
  621. invoke_malloc_hook(p, size);
  622. return p;
  623. }
  624. TSAN_INTERCEPTOR(void, free, void *p) {
  625. if (p == 0)
  626. return;
  627. if (in_symbolizer())
  628. return InternalFree(p);
  629. invoke_free_hook(p);
  630. SCOPED_INTERCEPTOR_RAW(free, p);
  631. user_free(thr, pc, p);
  632. }
  633. TSAN_INTERCEPTOR(void, cfree, void *p) {
  634. if (p == 0)
  635. return;
  636. if (in_symbolizer())
  637. return InternalFree(p);
  638. invoke_free_hook(p);
  639. SCOPED_INTERCEPTOR_RAW(cfree, p);
  640. user_free(thr, pc, p);
  641. }
  642. TSAN_INTERCEPTOR(uptr, malloc_usable_size, void *p) {
  643. SCOPED_INTERCEPTOR_RAW(malloc_usable_size, p);
  644. return user_alloc_usable_size(p);
  645. }
  646. #endif
  647. TSAN_INTERCEPTOR(char *, strcpy, char *dst, const char *src) {
  648. SCOPED_TSAN_INTERCEPTOR(strcpy, dst, src);
  649. uptr srclen = internal_strlen(src);
  650. MemoryAccessRange(thr, pc, (uptr)dst, srclen + 1, true);
  651. MemoryAccessRange(thr, pc, (uptr)src, srclen + 1, false);
  652. return REAL(strcpy)(dst, src);
  653. }
  654. TSAN_INTERCEPTOR(char*, strncpy, char *dst, char *src, uptr n) {
  655. SCOPED_TSAN_INTERCEPTOR(strncpy, dst, src, n);
  656. uptr srclen = internal_strnlen(src, n);
  657. MemoryAccessRange(thr, pc, (uptr)dst, n, true);
  658. MemoryAccessRange(thr, pc, (uptr)src, min(srclen + 1, n), false);
  659. return REAL(strncpy)(dst, src, n);
  660. }
  661. TSAN_INTERCEPTOR(char*, strdup, const char *str) {
  662. SCOPED_TSAN_INTERCEPTOR(strdup, str);
  663. // strdup will call malloc, so no instrumentation is required here.
  664. return REAL(strdup)(str);
  665. }
  666. // Zero out addr if it points into shadow memory and was provided as a hint
  667. // only, i.e., MAP_FIXED is not set.
  668. static bool fix_mmap_addr(void **addr, long_t sz, int flags) {
  669. if (*addr) {
  670. if (!IsAppMem((uptr)*addr) || !IsAppMem((uptr)*addr + sz - 1)) {
  671. if (flags & MAP_FIXED) {
  672. errno = errno_EINVAL;
  673. return false;
  674. } else {
  675. *addr = 0;
  676. }
  677. }
  678. }
  679. return true;
  680. }
  681. template <class Mmap>
  682. static void *mmap_interceptor(ThreadState *thr, uptr pc, Mmap real_mmap,
  683. void *addr, SIZE_T sz, int prot, int flags,
  684. int fd, OFF64_T off) {
  685. if (!fix_mmap_addr(&addr, sz, flags)) return MAP_FAILED;
  686. void *res = real_mmap(addr, sz, prot, flags, fd, off);
  687. if (res != MAP_FAILED) {
  688. if (!IsAppMem((uptr)res) || !IsAppMem((uptr)res + sz - 1)) {
  689. Report("ThreadSanitizer: mmap at bad address: addr=%p size=%p res=%p\n",
  690. addr, (void*)sz, res);
  691. Die();
  692. }
  693. if (fd > 0) FdAccess(thr, pc, fd);
  694. MemoryRangeImitateWriteOrResetRange(thr, pc, (uptr)res, sz);
  695. }
  696. return res;
  697. }
  698. TSAN_INTERCEPTOR(int, munmap, void *addr, long_t sz) {
  699. SCOPED_TSAN_INTERCEPTOR(munmap, addr, sz);
  700. UnmapShadow(thr, (uptr)addr, sz);
  701. int res = REAL(munmap)(addr, sz);
  702. return res;
  703. }
  704. #if SANITIZER_LINUX
  705. TSAN_INTERCEPTOR(void*, memalign, uptr align, uptr sz) {
  706. SCOPED_INTERCEPTOR_RAW(memalign, align, sz);
  707. return user_memalign(thr, pc, align, sz);
  708. }
  709. #define TSAN_MAYBE_INTERCEPT_MEMALIGN TSAN_INTERCEPT(memalign)
  710. #else
  711. #define TSAN_MAYBE_INTERCEPT_MEMALIGN
  712. #endif
  713. #if !SANITIZER_MAC
  714. TSAN_INTERCEPTOR(void*, aligned_alloc, uptr align, uptr sz) {
  715. if (in_symbolizer())
  716. return InternalAlloc(sz, nullptr, align);
  717. SCOPED_INTERCEPTOR_RAW(aligned_alloc, align, sz);
  718. return user_aligned_alloc(thr, pc, align, sz);
  719. }
  720. TSAN_INTERCEPTOR(void*, valloc, uptr sz) {
  721. if (in_symbolizer())
  722. return InternalAlloc(sz, nullptr, GetPageSizeCached());
  723. SCOPED_INTERCEPTOR_RAW(valloc, sz);
  724. return user_valloc(thr, pc, sz);
  725. }
  726. #endif
  727. #if SANITIZER_LINUX
  728. TSAN_INTERCEPTOR(void*, pvalloc, uptr sz) {
  729. if (in_symbolizer()) {
  730. uptr PageSize = GetPageSizeCached();
  731. sz = sz ? RoundUpTo(sz, PageSize) : PageSize;
  732. return InternalAlloc(sz, nullptr, PageSize);
  733. }
  734. SCOPED_INTERCEPTOR_RAW(pvalloc, sz);
  735. return user_pvalloc(thr, pc, sz);
  736. }
  737. #define TSAN_MAYBE_INTERCEPT_PVALLOC TSAN_INTERCEPT(pvalloc)
  738. #else
  739. #define TSAN_MAYBE_INTERCEPT_PVALLOC
  740. #endif
  741. #if !SANITIZER_MAC
  742. TSAN_INTERCEPTOR(int, posix_memalign, void **memptr, uptr align, uptr sz) {
  743. if (in_symbolizer()) {
  744. void *p = InternalAlloc(sz, nullptr, align);
  745. if (!p)
  746. return errno_ENOMEM;
  747. *memptr = p;
  748. return 0;
  749. }
  750. SCOPED_INTERCEPTOR_RAW(posix_memalign, memptr, align, sz);
  751. return user_posix_memalign(thr, pc, memptr, align, sz);
  752. }
  753. #endif
  754. // Both __cxa_guard_acquire and pthread_once 0-initialize
  755. // the object initially. pthread_once does not have any
  756. // other ABI requirements. __cxa_guard_acquire assumes
  757. // that any non-0 value in the first byte means that
  758. // initialization is completed. Contents of the remaining
  759. // bytes are up to us.
  760. constexpr u32 kGuardInit = 0;
  761. constexpr u32 kGuardDone = 1;
  762. constexpr u32 kGuardRunning = 1 << 16;
  763. constexpr u32 kGuardWaiter = 1 << 17;
  764. static int guard_acquire(ThreadState *thr, uptr pc, atomic_uint32_t *g,
  765. bool blocking_hooks = true) {
  766. if (blocking_hooks)
  767. OnPotentiallyBlockingRegionBegin();
  768. auto on_exit = at_scope_exit([blocking_hooks] {
  769. if (blocking_hooks)
  770. OnPotentiallyBlockingRegionEnd();
  771. });
  772. for (;;) {
  773. u32 cmp = atomic_load(g, memory_order_acquire);
  774. if (cmp == kGuardInit) {
  775. if (atomic_compare_exchange_strong(g, &cmp, kGuardRunning,
  776. memory_order_relaxed))
  777. return 1;
  778. } else if (cmp == kGuardDone) {
  779. if (!thr->in_ignored_lib)
  780. Acquire(thr, pc, (uptr)g);
  781. return 0;
  782. } else {
  783. if ((cmp & kGuardWaiter) ||
  784. atomic_compare_exchange_strong(g, &cmp, cmp | kGuardWaiter,
  785. memory_order_relaxed))
  786. FutexWait(g, cmp | kGuardWaiter);
  787. }
  788. }
  789. }
  790. static void guard_release(ThreadState *thr, uptr pc, atomic_uint32_t *g) {
  791. if (!thr->in_ignored_lib)
  792. Release(thr, pc, (uptr)g);
  793. u32 old = atomic_exchange(g, kGuardDone, memory_order_release);
  794. if (old & kGuardWaiter)
  795. FutexWake(g, 1 << 30);
  796. }
  797. // __cxa_guard_acquire and friends need to be intercepted in a special way -
  798. // regular interceptors will break statically-linked libstdc++. Linux
  799. // interceptors are especially defined as weak functions (so that they don't
  800. // cause link errors when user defines them as well). So they silently
  801. // auto-disable themselves when such symbol is already present in the binary. If
  802. // we link libstdc++ statically, it will bring own __cxa_guard_acquire which
  803. // will silently replace our interceptor. That's why on Linux we simply export
  804. // these interceptors with INTERFACE_ATTRIBUTE.
  805. // On OS X, we don't support statically linking, so we just use a regular
  806. // interceptor.
  807. #if SANITIZER_MAC
  808. #define STDCXX_INTERCEPTOR TSAN_INTERCEPTOR
  809. #else
  810. #define STDCXX_INTERCEPTOR(rettype, name, ...) \
  811. extern "C" rettype INTERFACE_ATTRIBUTE name(__VA_ARGS__)
  812. #endif
  813. // Used in thread-safe function static initialization.
  814. STDCXX_INTERCEPTOR(int, __cxa_guard_acquire, atomic_uint32_t *g) {
  815. SCOPED_INTERCEPTOR_RAW(__cxa_guard_acquire, g);
  816. return guard_acquire(thr, pc, g);
  817. }
  818. STDCXX_INTERCEPTOR(void, __cxa_guard_release, atomic_uint32_t *g) {
  819. SCOPED_INTERCEPTOR_RAW(__cxa_guard_release, g);
  820. guard_release(thr, pc, g);
  821. }
  822. STDCXX_INTERCEPTOR(void, __cxa_guard_abort, atomic_uint32_t *g) {
  823. SCOPED_INTERCEPTOR_RAW(__cxa_guard_abort, g);
  824. atomic_store(g, kGuardInit, memory_order_relaxed);
  825. }
  826. namespace __tsan {
  827. void DestroyThreadState() {
  828. ThreadState *thr = cur_thread();
  829. Processor *proc = thr->proc();
  830. ThreadFinish(thr);
  831. ProcUnwire(proc, thr);
  832. ProcDestroy(proc);
  833. DTLS_Destroy();
  834. cur_thread_finalize();
  835. }
  836. void PlatformCleanUpThreadState(ThreadState *thr) {
  837. ThreadSignalContext *sctx = thr->signal_ctx;
  838. if (sctx) {
  839. thr->signal_ctx = 0;
  840. UnmapOrDie(sctx, sizeof(*sctx));
  841. }
  842. }
  843. } // namespace __tsan
  844. #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
  845. static void thread_finalize(void *v) {
  846. uptr iter = (uptr)v;
  847. if (iter > 1) {
  848. if (pthread_setspecific(interceptor_ctx()->finalize_key,
  849. (void*)(iter - 1))) {
  850. Printf("ThreadSanitizer: failed to set thread key\n");
  851. Die();
  852. }
  853. return;
  854. }
  855. DestroyThreadState();
  856. }
  857. #endif
  858. struct ThreadParam {
  859. void* (*callback)(void *arg);
  860. void *param;
  861. Tid tid;
  862. Semaphore created;
  863. Semaphore started;
  864. };
  865. extern "C" void *__tsan_thread_start_func(void *arg) {
  866. ThreadParam *p = (ThreadParam*)arg;
  867. void* (*callback)(void *arg) = p->callback;
  868. void *param = p->param;
  869. {
  870. ThreadState *thr = cur_thread_init();
  871. // Thread-local state is not initialized yet.
  872. ScopedIgnoreInterceptors ignore;
  873. #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
  874. ThreadIgnoreBegin(thr, 0);
  875. if (pthread_setspecific(interceptor_ctx()->finalize_key,
  876. (void *)GetPthreadDestructorIterations())) {
  877. Printf("ThreadSanitizer: failed to set thread key\n");
  878. Die();
  879. }
  880. ThreadIgnoreEnd(thr);
  881. #endif
  882. p->created.Wait();
  883. Processor *proc = ProcCreate();
  884. ProcWire(proc, thr);
  885. ThreadStart(thr, p->tid, GetTid(), ThreadType::Regular);
  886. p->started.Post();
  887. }
  888. void *res = callback(param);
  889. // Prevent the callback from being tail called,
  890. // it mixes up stack traces.
  891. volatile int foo = 42;
  892. foo++;
  893. return res;
  894. }
  895. TSAN_INTERCEPTOR(int, pthread_create,
  896. void *th, void *attr, void *(*callback)(void*), void * param) {
  897. SCOPED_INTERCEPTOR_RAW(pthread_create, th, attr, callback, param);
  898. MaybeSpawnBackgroundThread();
  899. if (ctx->after_multithreaded_fork) {
  900. if (flags()->die_after_fork) {
  901. Report("ThreadSanitizer: starting new threads after multi-threaded "
  902. "fork is not supported. Dying (set die_after_fork=0 to override)\n");
  903. Die();
  904. } else {
  905. VPrintf(1,
  906. "ThreadSanitizer: starting new threads after multi-threaded "
  907. "fork is not supported (pid %lu). Continuing because of "
  908. "die_after_fork=0, but you are on your own\n",
  909. internal_getpid());
  910. }
  911. }
  912. __sanitizer_pthread_attr_t myattr;
  913. if (attr == 0) {
  914. pthread_attr_init(&myattr);
  915. attr = &myattr;
  916. }
  917. int detached = 0;
  918. REAL(pthread_attr_getdetachstate)(attr, &detached);
  919. AdjustStackSize(attr);
  920. ThreadParam p;
  921. p.callback = callback;
  922. p.param = param;
  923. p.tid = kMainTid;
  924. int res = -1;
  925. {
  926. // Otherwise we see false positives in pthread stack manipulation.
  927. ScopedIgnoreInterceptors ignore;
  928. ThreadIgnoreBegin(thr, pc);
  929. res = REAL(pthread_create)(th, attr, __tsan_thread_start_func, &p);
  930. ThreadIgnoreEnd(thr);
  931. }
  932. if (res == 0) {
  933. p.tid = ThreadCreate(thr, pc, *(uptr *)th, IsStateDetached(detached));
  934. CHECK_NE(p.tid, kMainTid);
  935. // Synchronization on p.tid serves two purposes:
  936. // 1. ThreadCreate must finish before the new thread starts.
  937. // Otherwise the new thread can call pthread_detach, but the pthread_t
  938. // identifier is not yet registered in ThreadRegistry by ThreadCreate.
  939. // 2. ThreadStart must finish before this thread continues.
  940. // Otherwise, this thread can call pthread_detach and reset thr->sync
  941. // before the new thread got a chance to acquire from it in ThreadStart.
  942. p.created.Post();
  943. p.started.Wait();
  944. }
  945. if (attr == &myattr)
  946. pthread_attr_destroy(&myattr);
  947. return res;
  948. }
  949. TSAN_INTERCEPTOR(int, pthread_join, void *th, void **ret) {
  950. SCOPED_INTERCEPTOR_RAW(pthread_join, th, ret);
  951. Tid tid = ThreadConsumeTid(thr, pc, (uptr)th);
  952. ThreadIgnoreBegin(thr, pc);
  953. int res = BLOCK_REAL(pthread_join)(th, ret);
  954. ThreadIgnoreEnd(thr);
  955. if (res == 0) {
  956. ThreadJoin(thr, pc, tid);
  957. }
  958. return res;
  959. }
  960. DEFINE_REAL_PTHREAD_FUNCTIONS
  961. TSAN_INTERCEPTOR(int, pthread_detach, void *th) {
  962. SCOPED_INTERCEPTOR_RAW(pthread_detach, th);
  963. Tid tid = ThreadConsumeTid(thr, pc, (uptr)th);
  964. int res = REAL(pthread_detach)(th);
  965. if (res == 0) {
  966. ThreadDetach(thr, pc, tid);
  967. }
  968. return res;
  969. }
  970. TSAN_INTERCEPTOR(void, pthread_exit, void *retval) {
  971. {
  972. SCOPED_INTERCEPTOR_RAW(pthread_exit, retval);
  973. #if !SANITIZER_MAC && !SANITIZER_ANDROID
  974. CHECK_EQ(thr, &cur_thread_placeholder);
  975. #endif
  976. }
  977. REAL(pthread_exit)(retval);
  978. }
  979. #if SANITIZER_LINUX
  980. TSAN_INTERCEPTOR(int, pthread_tryjoin_np, void *th, void **ret) {
  981. SCOPED_INTERCEPTOR_RAW(pthread_tryjoin_np, th, ret);
  982. Tid tid = ThreadConsumeTid(thr, pc, (uptr)th);
  983. ThreadIgnoreBegin(thr, pc);
  984. int res = REAL(pthread_tryjoin_np)(th, ret);
  985. ThreadIgnoreEnd(thr);
  986. if (res == 0)
  987. ThreadJoin(thr, pc, tid);
  988. else
  989. ThreadNotJoined(thr, pc, tid, (uptr)th);
  990. return res;
  991. }
  992. TSAN_INTERCEPTOR(int, pthread_timedjoin_np, void *th, void **ret,
  993. const struct timespec *abstime) {
  994. SCOPED_INTERCEPTOR_RAW(pthread_timedjoin_np, th, ret, abstime);
  995. Tid tid = ThreadConsumeTid(thr, pc, (uptr)th);
  996. ThreadIgnoreBegin(thr, pc);
  997. int res = BLOCK_REAL(pthread_timedjoin_np)(th, ret, abstime);
  998. ThreadIgnoreEnd(thr);
  999. if (res == 0)
  1000. ThreadJoin(thr, pc, tid);
  1001. else
  1002. ThreadNotJoined(thr, pc, tid, (uptr)th);
  1003. return res;
  1004. }
  1005. #endif
  1006. // Problem:
  1007. // NPTL implementation of pthread_cond has 2 versions (2.2.5 and 2.3.2).
  1008. // pthread_cond_t has different size in the different versions.
  1009. // If call new REAL functions for old pthread_cond_t, they will corrupt memory
  1010. // after pthread_cond_t (old cond is smaller).
  1011. // If we call old REAL functions for new pthread_cond_t, we will lose some
  1012. // functionality (e.g. old functions do not support waiting against
  1013. // CLOCK_REALTIME).
  1014. // Proper handling would require to have 2 versions of interceptors as well.
  1015. // But this is messy, in particular requires linker scripts when sanitizer
  1016. // runtime is linked into a shared library.
  1017. // Instead we assume we don't have dynamic libraries built against old
  1018. // pthread (2.2.5 is dated by 2002). And provide legacy_pthread_cond flag
  1019. // that allows to work with old libraries (but this mode does not support
  1020. // some features, e.g. pthread_condattr_getpshared).
  1021. static void *init_cond(void *c, bool force = false) {
  1022. // sizeof(pthread_cond_t) >= sizeof(uptr) in both versions.
  1023. // So we allocate additional memory on the side large enough to hold
  1024. // any pthread_cond_t object. Always call new REAL functions, but pass
  1025. // the aux object to them.
  1026. // Note: the code assumes that PTHREAD_COND_INITIALIZER initializes
  1027. // first word of pthread_cond_t to zero.
  1028. // It's all relevant only for linux.
  1029. if (!common_flags()->legacy_pthread_cond)
  1030. return c;
  1031. atomic_uintptr_t *p = (atomic_uintptr_t*)c;
  1032. uptr cond = atomic_load(p, memory_order_acquire);
  1033. if (!force && cond != 0)
  1034. return (void*)cond;
  1035. void *newcond = WRAP(malloc)(pthread_cond_t_sz);
  1036. internal_memset(newcond, 0, pthread_cond_t_sz);
  1037. if (atomic_compare_exchange_strong(p, &cond, (uptr)newcond,
  1038. memory_order_acq_rel))
  1039. return newcond;
  1040. WRAP(free)(newcond);
  1041. return (void*)cond;
  1042. }
  1043. namespace {
  1044. template <class Fn>
  1045. struct CondMutexUnlockCtx {
  1046. ScopedInterceptor *si;
  1047. ThreadState *thr;
  1048. uptr pc;
  1049. void *m;
  1050. void *c;
  1051. const Fn &fn;
  1052. int Cancel() const { return fn(); }
  1053. void Unlock() const;
  1054. };
  1055. template <class Fn>
  1056. void CondMutexUnlockCtx<Fn>::Unlock() const {
  1057. // pthread_cond_wait interceptor has enabled async signal delivery
  1058. // (see BlockingCall below). Disable async signals since we are running
  1059. // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
  1060. // since the thread is cancelled, so we have to manually execute them
  1061. // (the thread still can run some user code due to pthread_cleanup_push).
  1062. ThreadSignalContext *ctx = SigCtx(thr);
  1063. CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
  1064. atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
  1065. MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
  1066. // Undo BlockingCall ctor effects.
  1067. thr->ignore_interceptors--;
  1068. si->~ScopedInterceptor();
  1069. }
  1070. } // namespace
  1071. INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
  1072. void *cond = init_cond(c, true);
  1073. SCOPED_TSAN_INTERCEPTOR(pthread_cond_init, cond, a);
  1074. MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
  1075. return REAL(pthread_cond_init)(cond, a);
  1076. }
  1077. template <class Fn>
  1078. int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si, const Fn &fn,
  1079. void *c, void *m) {
  1080. MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
  1081. MutexUnlock(thr, pc, (uptr)m);
  1082. int res = 0;
  1083. // This ensures that we handle mutex lock even in case of pthread_cancel.
  1084. // See test/tsan/cond_cancel.cpp.
  1085. {
  1086. // Enable signal delivery while the thread is blocked.
  1087. BlockingCall bc(thr);
  1088. CondMutexUnlockCtx<Fn> arg = {si, thr, pc, m, c, fn};
  1089. res = call_pthread_cancel_with_cleanup(
  1090. [](void *arg) -> int {
  1091. return ((const CondMutexUnlockCtx<Fn> *)arg)->Cancel();
  1092. },
  1093. [](void *arg) { ((const CondMutexUnlockCtx<Fn> *)arg)->Unlock(); },
  1094. &arg);
  1095. }
  1096. if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
  1097. MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
  1098. return res;
  1099. }
  1100. INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
  1101. void *cond = init_cond(c);
  1102. SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
  1103. return cond_wait(
  1104. thr, pc, &si, [=]() { return REAL(pthread_cond_wait)(cond, m); }, cond,
  1105. m);
  1106. }
  1107. INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
  1108. void *cond = init_cond(c);
  1109. SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
  1110. return cond_wait(
  1111. thr, pc, &si,
  1112. [=]() { return REAL(pthread_cond_timedwait)(cond, m, abstime); }, cond,
  1113. m);
  1114. }
  1115. #if SANITIZER_LINUX
  1116. INTERCEPTOR(int, pthread_cond_clockwait, void *c, void *m,
  1117. __sanitizer_clockid_t clock, void *abstime) {
  1118. void *cond = init_cond(c);
  1119. SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait, cond, m, clock, abstime);
  1120. return cond_wait(
  1121. thr, pc, &si,
  1122. [=]() { return REAL(pthread_cond_clockwait)(cond, m, clock, abstime); },
  1123. cond, m);
  1124. }
  1125. #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait)
  1126. #else
  1127. #define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
  1128. #endif
  1129. #if SANITIZER_MAC
  1130. INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
  1131. void *reltime) {
  1132. void *cond = init_cond(c);
  1133. SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
  1134. return cond_wait(
  1135. thr, pc, &si,
  1136. [=]() {
  1137. return REAL(pthread_cond_timedwait_relative_np)(cond, m, reltime);
  1138. },
  1139. cond, m);
  1140. }
  1141. #endif
  1142. INTERCEPTOR(int, pthread_cond_signal, void *c) {
  1143. void *cond = init_cond(c);
  1144. SCOPED_TSAN_INTERCEPTOR(pthread_cond_signal, cond);
  1145. MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
  1146. return REAL(pthread_cond_signal)(cond);
  1147. }
  1148. INTERCEPTOR(int, pthread_cond_broadcast, void *c) {
  1149. void *cond = init_cond(c);
  1150. SCOPED_TSAN_INTERCEPTOR(pthread_cond_broadcast, cond);
  1151. MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
  1152. return REAL(pthread_cond_broadcast)(cond);
  1153. }
  1154. INTERCEPTOR(int, pthread_cond_destroy, void *c) {
  1155. void *cond = init_cond(c);
  1156. SCOPED_TSAN_INTERCEPTOR(pthread_cond_destroy, cond);
  1157. MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), true);
  1158. int res = REAL(pthread_cond_destroy)(cond);
  1159. if (common_flags()->legacy_pthread_cond) {
  1160. // Free our aux cond and zero the pointer to not leave dangling pointers.
  1161. WRAP(free)(cond);
  1162. atomic_store((atomic_uintptr_t*)c, 0, memory_order_relaxed);
  1163. }
  1164. return res;
  1165. }
  1166. TSAN_INTERCEPTOR(int, pthread_mutex_init, void *m, void *a) {
  1167. SCOPED_TSAN_INTERCEPTOR(pthread_mutex_init, m, a);
  1168. int res = REAL(pthread_mutex_init)(m, a);
  1169. if (res == 0) {
  1170. u32 flagz = 0;
  1171. if (a) {
  1172. int type = 0;
  1173. if (REAL(pthread_mutexattr_gettype)(a, &type) == 0)
  1174. if (type == PTHREAD_MUTEX_RECURSIVE ||
  1175. type == PTHREAD_MUTEX_RECURSIVE_NP)
  1176. flagz |= MutexFlagWriteReentrant;
  1177. }
  1178. MutexCreate(thr, pc, (uptr)m, flagz);
  1179. }
  1180. return res;
  1181. }
  1182. TSAN_INTERCEPTOR(int, pthread_mutex_destroy, void *m) {
  1183. SCOPED_TSAN_INTERCEPTOR(pthread_mutex_destroy, m);
  1184. int res = REAL(pthread_mutex_destroy)(m);
  1185. if (res == 0 || res == errno_EBUSY) {
  1186. MutexDestroy(thr, pc, (uptr)m);
  1187. }
  1188. return res;
  1189. }
  1190. TSAN_INTERCEPTOR(int, pthread_mutex_trylock, void *m) {
  1191. SCOPED_TSAN_INTERCEPTOR(pthread_mutex_trylock, m);
  1192. int res = REAL(pthread_mutex_trylock)(m);
  1193. if (res == errno_EOWNERDEAD)
  1194. MutexRepair(thr, pc, (uptr)m);
  1195. if (res == 0 || res == errno_EOWNERDEAD)
  1196. MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1197. return res;
  1198. }
  1199. #if !SANITIZER_MAC
  1200. TSAN_INTERCEPTOR(int, pthread_mutex_timedlock, void *m, void *abstime) {
  1201. SCOPED_TSAN_INTERCEPTOR(pthread_mutex_timedlock, m, abstime);
  1202. int res = REAL(pthread_mutex_timedlock)(m, abstime);
  1203. if (res == 0) {
  1204. MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1205. }
  1206. return res;
  1207. }
  1208. #endif
  1209. #if !SANITIZER_MAC
  1210. TSAN_INTERCEPTOR(int, pthread_spin_init, void *m, int pshared) {
  1211. SCOPED_TSAN_INTERCEPTOR(pthread_spin_init, m, pshared);
  1212. int res = REAL(pthread_spin_init)(m, pshared);
  1213. if (res == 0) {
  1214. MutexCreate(thr, pc, (uptr)m);
  1215. }
  1216. return res;
  1217. }
  1218. TSAN_INTERCEPTOR(int, pthread_spin_destroy, void *m) {
  1219. SCOPED_TSAN_INTERCEPTOR(pthread_spin_destroy, m);
  1220. int res = REAL(pthread_spin_destroy)(m);
  1221. if (res == 0) {
  1222. MutexDestroy(thr, pc, (uptr)m);
  1223. }
  1224. return res;
  1225. }
  1226. TSAN_INTERCEPTOR(int, pthread_spin_lock, void *m) {
  1227. SCOPED_TSAN_INTERCEPTOR(pthread_spin_lock, m);
  1228. MutexPreLock(thr, pc, (uptr)m);
  1229. int res = REAL(pthread_spin_lock)(m);
  1230. if (res == 0) {
  1231. MutexPostLock(thr, pc, (uptr)m);
  1232. }
  1233. return res;
  1234. }
  1235. TSAN_INTERCEPTOR(int, pthread_spin_trylock, void *m) {
  1236. SCOPED_TSAN_INTERCEPTOR(pthread_spin_trylock, m);
  1237. int res = REAL(pthread_spin_trylock)(m);
  1238. if (res == 0) {
  1239. MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1240. }
  1241. return res;
  1242. }
  1243. TSAN_INTERCEPTOR(int, pthread_spin_unlock, void *m) {
  1244. SCOPED_TSAN_INTERCEPTOR(pthread_spin_unlock, m);
  1245. MutexUnlock(thr, pc, (uptr)m);
  1246. int res = REAL(pthread_spin_unlock)(m);
  1247. return res;
  1248. }
  1249. #endif
  1250. TSAN_INTERCEPTOR(int, pthread_rwlock_init, void *m, void *a) {
  1251. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_init, m, a);
  1252. int res = REAL(pthread_rwlock_init)(m, a);
  1253. if (res == 0) {
  1254. MutexCreate(thr, pc, (uptr)m);
  1255. }
  1256. return res;
  1257. }
  1258. TSAN_INTERCEPTOR(int, pthread_rwlock_destroy, void *m) {
  1259. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_destroy, m);
  1260. int res = REAL(pthread_rwlock_destroy)(m);
  1261. if (res == 0) {
  1262. MutexDestroy(thr, pc, (uptr)m);
  1263. }
  1264. return res;
  1265. }
  1266. TSAN_INTERCEPTOR(int, pthread_rwlock_rdlock, void *m) {
  1267. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_rdlock, m);
  1268. MutexPreReadLock(thr, pc, (uptr)m);
  1269. int res = REAL(pthread_rwlock_rdlock)(m);
  1270. if (res == 0) {
  1271. MutexPostReadLock(thr, pc, (uptr)m);
  1272. }
  1273. return res;
  1274. }
  1275. TSAN_INTERCEPTOR(int, pthread_rwlock_tryrdlock, void *m) {
  1276. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_tryrdlock, m);
  1277. int res = REAL(pthread_rwlock_tryrdlock)(m);
  1278. if (res == 0) {
  1279. MutexPostReadLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1280. }
  1281. return res;
  1282. }
  1283. #if !SANITIZER_MAC
  1284. TSAN_INTERCEPTOR(int, pthread_rwlock_timedrdlock, void *m, void *abstime) {
  1285. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedrdlock, m, abstime);
  1286. int res = REAL(pthread_rwlock_timedrdlock)(m, abstime);
  1287. if (res == 0) {
  1288. MutexPostReadLock(thr, pc, (uptr)m);
  1289. }
  1290. return res;
  1291. }
  1292. #endif
  1293. TSAN_INTERCEPTOR(int, pthread_rwlock_wrlock, void *m) {
  1294. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_wrlock, m);
  1295. MutexPreLock(thr, pc, (uptr)m);
  1296. int res = REAL(pthread_rwlock_wrlock)(m);
  1297. if (res == 0) {
  1298. MutexPostLock(thr, pc, (uptr)m);
  1299. }
  1300. return res;
  1301. }
  1302. TSAN_INTERCEPTOR(int, pthread_rwlock_trywrlock, void *m) {
  1303. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_trywrlock, m);
  1304. int res = REAL(pthread_rwlock_trywrlock)(m);
  1305. if (res == 0) {
  1306. MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1307. }
  1308. return res;
  1309. }
  1310. #if !SANITIZER_MAC
  1311. TSAN_INTERCEPTOR(int, pthread_rwlock_timedwrlock, void *m, void *abstime) {
  1312. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_timedwrlock, m, abstime);
  1313. int res = REAL(pthread_rwlock_timedwrlock)(m, abstime);
  1314. if (res == 0) {
  1315. MutexPostLock(thr, pc, (uptr)m, MutexFlagTryLock);
  1316. }
  1317. return res;
  1318. }
  1319. #endif
  1320. TSAN_INTERCEPTOR(int, pthread_rwlock_unlock, void *m) {
  1321. SCOPED_TSAN_INTERCEPTOR(pthread_rwlock_unlock, m);
  1322. MutexReadOrWriteUnlock(thr, pc, (uptr)m);
  1323. int res = REAL(pthread_rwlock_unlock)(m);
  1324. return res;
  1325. }
  1326. #if !SANITIZER_MAC
  1327. TSAN_INTERCEPTOR(int, pthread_barrier_init, void *b, void *a, unsigned count) {
  1328. SCOPED_TSAN_INTERCEPTOR(pthread_barrier_init, b, a, count);
  1329. MemoryAccess(thr, pc, (uptr)b, 1, kAccessWrite);
  1330. int res = REAL(pthread_barrier_init)(b, a, count);
  1331. return res;
  1332. }
  1333. TSAN_INTERCEPTOR(int, pthread_barrier_destroy, void *b) {
  1334. SCOPED_TSAN_INTERCEPTOR(pthread_barrier_destroy, b);
  1335. MemoryAccess(thr, pc, (uptr)b, 1, kAccessWrite);
  1336. int res = REAL(pthread_barrier_destroy)(b);
  1337. return res;
  1338. }
  1339. TSAN_INTERCEPTOR(int, pthread_barrier_wait, void *b) {
  1340. SCOPED_TSAN_INTERCEPTOR(pthread_barrier_wait, b);
  1341. Release(thr, pc, (uptr)b);
  1342. MemoryAccess(thr, pc, (uptr)b, 1, kAccessRead);
  1343. int res = REAL(pthread_barrier_wait)(b);
  1344. MemoryAccess(thr, pc, (uptr)b, 1, kAccessRead);
  1345. if (res == 0 || res == PTHREAD_BARRIER_SERIAL_THREAD) {
  1346. Acquire(thr, pc, (uptr)b);
  1347. }
  1348. return res;
  1349. }
  1350. #endif
  1351. TSAN_INTERCEPTOR(int, pthread_once, void *o, void (*f)()) {
  1352. SCOPED_INTERCEPTOR_RAW(pthread_once, o, f);
  1353. if (o == 0 || f == 0)
  1354. return errno_EINVAL;
  1355. atomic_uint32_t *a;
  1356. if (SANITIZER_MAC)
  1357. a = static_cast<atomic_uint32_t*>((void *)((char *)o + sizeof(long_t)));
  1358. else if (SANITIZER_NETBSD)
  1359. a = static_cast<atomic_uint32_t*>
  1360. ((void *)((char *)o + __sanitizer::pthread_mutex_t_sz));
  1361. else
  1362. a = static_cast<atomic_uint32_t*>(o);
  1363. // Mac OS X appears to use pthread_once() where calling BlockingRegion hooks
  1364. // result in crashes due to too little stack space.
  1365. if (guard_acquire(thr, pc, a, !SANITIZER_MAC)) {
  1366. (*f)();
  1367. guard_release(thr, pc, a);
  1368. }
  1369. return 0;
  1370. }
  1371. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  1372. TSAN_INTERCEPTOR(int, __fxstat, int version, int fd, void *buf) {
  1373. SCOPED_TSAN_INTERCEPTOR(__fxstat, version, fd, buf);
  1374. if (fd > 0)
  1375. FdAccess(thr, pc, fd);
  1376. return REAL(__fxstat)(version, fd, buf);
  1377. }
  1378. #define TSAN_MAYBE_INTERCEPT___FXSTAT TSAN_INTERCEPT(__fxstat)
  1379. #else
  1380. #define TSAN_MAYBE_INTERCEPT___FXSTAT
  1381. #endif
  1382. TSAN_INTERCEPTOR(int, fstat, int fd, void *buf) {
  1383. #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_ANDROID || SANITIZER_NETBSD
  1384. SCOPED_TSAN_INTERCEPTOR(fstat, fd, buf);
  1385. if (fd > 0)
  1386. FdAccess(thr, pc, fd);
  1387. return REAL(fstat)(fd, buf);
  1388. #else
  1389. SCOPED_TSAN_INTERCEPTOR(__fxstat, 0, fd, buf);
  1390. if (fd > 0)
  1391. FdAccess(thr, pc, fd);
  1392. return REAL(__fxstat)(0, fd, buf);
  1393. #endif
  1394. }
  1395. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  1396. TSAN_INTERCEPTOR(int, __fxstat64, int version, int fd, void *buf) {
  1397. SCOPED_TSAN_INTERCEPTOR(__fxstat64, version, fd, buf);
  1398. if (fd > 0)
  1399. FdAccess(thr, pc, fd);
  1400. return REAL(__fxstat64)(version, fd, buf);
  1401. }
  1402. #define TSAN_MAYBE_INTERCEPT___FXSTAT64 TSAN_INTERCEPT(__fxstat64)
  1403. #else
  1404. #define TSAN_MAYBE_INTERCEPT___FXSTAT64
  1405. #endif
  1406. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  1407. TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
  1408. SCOPED_TSAN_INTERCEPTOR(__fxstat64, 0, fd, buf);
  1409. if (fd > 0)
  1410. FdAccess(thr, pc, fd);
  1411. return REAL(__fxstat64)(0, fd, buf);
  1412. }
  1413. #define TSAN_MAYBE_INTERCEPT_FSTAT64 TSAN_INTERCEPT(fstat64)
  1414. #else
  1415. #define TSAN_MAYBE_INTERCEPT_FSTAT64
  1416. #endif
  1417. TSAN_INTERCEPTOR(int, open, const char *name, int oflag, ...) {
  1418. va_list ap;
  1419. va_start(ap, oflag);
  1420. mode_t mode = va_arg(ap, int);
  1421. va_end(ap);
  1422. SCOPED_TSAN_INTERCEPTOR(open, name, oflag, mode);
  1423. READ_STRING(thr, pc, name, 0);
  1424. int fd = REAL(open)(name, oflag, mode);
  1425. if (fd >= 0)
  1426. FdFileCreate(thr, pc, fd);
  1427. return fd;
  1428. }
  1429. #if SANITIZER_LINUX
  1430. TSAN_INTERCEPTOR(int, open64, const char *name, int oflag, ...) {
  1431. va_list ap;
  1432. va_start(ap, oflag);
  1433. mode_t mode = va_arg(ap, int);
  1434. va_end(ap);
  1435. SCOPED_TSAN_INTERCEPTOR(open64, name, oflag, mode);
  1436. READ_STRING(thr, pc, name, 0);
  1437. int fd = REAL(open64)(name, oflag, mode);
  1438. if (fd >= 0)
  1439. FdFileCreate(thr, pc, fd);
  1440. return fd;
  1441. }
  1442. #define TSAN_MAYBE_INTERCEPT_OPEN64 TSAN_INTERCEPT(open64)
  1443. #else
  1444. #define TSAN_MAYBE_INTERCEPT_OPEN64
  1445. #endif
  1446. TSAN_INTERCEPTOR(int, creat, const char *name, int mode) {
  1447. SCOPED_TSAN_INTERCEPTOR(creat, name, mode);
  1448. READ_STRING(thr, pc, name, 0);
  1449. int fd = REAL(creat)(name, mode);
  1450. if (fd >= 0)
  1451. FdFileCreate(thr, pc, fd);
  1452. return fd;
  1453. }
  1454. #if SANITIZER_LINUX
  1455. TSAN_INTERCEPTOR(int, creat64, const char *name, int mode) {
  1456. SCOPED_TSAN_INTERCEPTOR(creat64, name, mode);
  1457. READ_STRING(thr, pc, name, 0);
  1458. int fd = REAL(creat64)(name, mode);
  1459. if (fd >= 0)
  1460. FdFileCreate(thr, pc, fd);
  1461. return fd;
  1462. }
  1463. #define TSAN_MAYBE_INTERCEPT_CREAT64 TSAN_INTERCEPT(creat64)
  1464. #else
  1465. #define TSAN_MAYBE_INTERCEPT_CREAT64
  1466. #endif
  1467. TSAN_INTERCEPTOR(int, dup, int oldfd) {
  1468. SCOPED_TSAN_INTERCEPTOR(dup, oldfd);
  1469. int newfd = REAL(dup)(oldfd);
  1470. if (oldfd >= 0 && newfd >= 0 && newfd != oldfd)
  1471. FdDup(thr, pc, oldfd, newfd, true);
  1472. return newfd;
  1473. }
  1474. TSAN_INTERCEPTOR(int, dup2, int oldfd, int newfd) {
  1475. SCOPED_TSAN_INTERCEPTOR(dup2, oldfd, newfd);
  1476. int newfd2 = REAL(dup2)(oldfd, newfd);
  1477. if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
  1478. FdDup(thr, pc, oldfd, newfd2, false);
  1479. return newfd2;
  1480. }
  1481. #if !SANITIZER_MAC
  1482. TSAN_INTERCEPTOR(int, dup3, int oldfd, int newfd, int flags) {
  1483. SCOPED_TSAN_INTERCEPTOR(dup3, oldfd, newfd, flags);
  1484. int newfd2 = REAL(dup3)(oldfd, newfd, flags);
  1485. if (oldfd >= 0 && newfd2 >= 0 && newfd2 != oldfd)
  1486. FdDup(thr, pc, oldfd, newfd2, false);
  1487. return newfd2;
  1488. }
  1489. #endif
  1490. #if SANITIZER_LINUX
  1491. TSAN_INTERCEPTOR(int, eventfd, unsigned initval, int flags) {
  1492. SCOPED_TSAN_INTERCEPTOR(eventfd, initval, flags);
  1493. int fd = REAL(eventfd)(initval, flags);
  1494. if (fd >= 0)
  1495. FdEventCreate(thr, pc, fd);
  1496. return fd;
  1497. }
  1498. #define TSAN_MAYBE_INTERCEPT_EVENTFD TSAN_INTERCEPT(eventfd)
  1499. #else
  1500. #define TSAN_MAYBE_INTERCEPT_EVENTFD
  1501. #endif
  1502. #if SANITIZER_LINUX
  1503. TSAN_INTERCEPTOR(int, signalfd, int fd, void *mask, int flags) {
  1504. SCOPED_TSAN_INTERCEPTOR(signalfd, fd, mask, flags);
  1505. if (fd >= 0)
  1506. FdClose(thr, pc, fd);
  1507. fd = REAL(signalfd)(fd, mask, flags);
  1508. if (fd >= 0)
  1509. FdSignalCreate(thr, pc, fd);
  1510. return fd;
  1511. }
  1512. #define TSAN_MAYBE_INTERCEPT_SIGNALFD TSAN_INTERCEPT(signalfd)
  1513. #else
  1514. #define TSAN_MAYBE_INTERCEPT_SIGNALFD
  1515. #endif
  1516. #if SANITIZER_LINUX
  1517. TSAN_INTERCEPTOR(int, inotify_init, int fake) {
  1518. SCOPED_TSAN_INTERCEPTOR(inotify_init, fake);
  1519. int fd = REAL(inotify_init)(fake);
  1520. if (fd >= 0)
  1521. FdInotifyCreate(thr, pc, fd);
  1522. return fd;
  1523. }
  1524. #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT TSAN_INTERCEPT(inotify_init)
  1525. #else
  1526. #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT
  1527. #endif
  1528. #if SANITIZER_LINUX
  1529. TSAN_INTERCEPTOR(int, inotify_init1, int flags) {
  1530. SCOPED_TSAN_INTERCEPTOR(inotify_init1, flags);
  1531. int fd = REAL(inotify_init1)(flags);
  1532. if (fd >= 0)
  1533. FdInotifyCreate(thr, pc, fd);
  1534. return fd;
  1535. }
  1536. #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1 TSAN_INTERCEPT(inotify_init1)
  1537. #else
  1538. #define TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1
  1539. #endif
  1540. TSAN_INTERCEPTOR(int, socket, int domain, int type, int protocol) {
  1541. SCOPED_TSAN_INTERCEPTOR(socket, domain, type, protocol);
  1542. int fd = REAL(socket)(domain, type, protocol);
  1543. if (fd >= 0)
  1544. FdSocketCreate(thr, pc, fd);
  1545. return fd;
  1546. }
  1547. TSAN_INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int *fd) {
  1548. SCOPED_TSAN_INTERCEPTOR(socketpair, domain, type, protocol, fd);
  1549. int res = REAL(socketpair)(domain, type, protocol, fd);
  1550. if (res == 0 && fd[0] >= 0 && fd[1] >= 0)
  1551. FdPipeCreate(thr, pc, fd[0], fd[1]);
  1552. return res;
  1553. }
  1554. TSAN_INTERCEPTOR(int, connect, int fd, void *addr, unsigned addrlen) {
  1555. SCOPED_TSAN_INTERCEPTOR(connect, fd, addr, addrlen);
  1556. FdSocketConnecting(thr, pc, fd);
  1557. int res = REAL(connect)(fd, addr, addrlen);
  1558. if (res == 0 && fd >= 0)
  1559. FdSocketConnect(thr, pc, fd);
  1560. return res;
  1561. }
  1562. TSAN_INTERCEPTOR(int, bind, int fd, void *addr, unsigned addrlen) {
  1563. SCOPED_TSAN_INTERCEPTOR(bind, fd, addr, addrlen);
  1564. int res = REAL(bind)(fd, addr, addrlen);
  1565. if (fd > 0 && res == 0)
  1566. FdAccess(thr, pc, fd);
  1567. return res;
  1568. }
  1569. TSAN_INTERCEPTOR(int, listen, int fd, int backlog) {
  1570. SCOPED_TSAN_INTERCEPTOR(listen, fd, backlog);
  1571. int res = REAL(listen)(fd, backlog);
  1572. if (fd > 0 && res == 0)
  1573. FdAccess(thr, pc, fd);
  1574. return res;
  1575. }
  1576. TSAN_INTERCEPTOR(int, close, int fd) {
  1577. SCOPED_TSAN_INTERCEPTOR(close, fd);
  1578. if (fd >= 0)
  1579. FdClose(thr, pc, fd);
  1580. return REAL(close)(fd);
  1581. }
  1582. #if SANITIZER_LINUX
  1583. TSAN_INTERCEPTOR(int, __close, int fd) {
  1584. SCOPED_TSAN_INTERCEPTOR(__close, fd);
  1585. if (fd >= 0)
  1586. FdClose(thr, pc, fd);
  1587. return REAL(__close)(fd);
  1588. }
  1589. #define TSAN_MAYBE_INTERCEPT___CLOSE TSAN_INTERCEPT(__close)
  1590. #else
  1591. #define TSAN_MAYBE_INTERCEPT___CLOSE
  1592. #endif
  1593. // glibc guts
  1594. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  1595. TSAN_INTERCEPTOR(void, __res_iclose, void *state, bool free_addr) {
  1596. SCOPED_TSAN_INTERCEPTOR(__res_iclose, state, free_addr);
  1597. int fds[64];
  1598. int cnt = ExtractResolvFDs(state, fds, ARRAY_SIZE(fds));
  1599. for (int i = 0; i < cnt; i++) {
  1600. if (fds[i] > 0)
  1601. FdClose(thr, pc, fds[i]);
  1602. }
  1603. REAL(__res_iclose)(state, free_addr);
  1604. }
  1605. #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE TSAN_INTERCEPT(__res_iclose)
  1606. #else
  1607. #define TSAN_MAYBE_INTERCEPT___RES_ICLOSE
  1608. #endif
  1609. TSAN_INTERCEPTOR(int, pipe, int *pipefd) {
  1610. SCOPED_TSAN_INTERCEPTOR(pipe, pipefd);
  1611. int res = REAL(pipe)(pipefd);
  1612. if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
  1613. FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
  1614. return res;
  1615. }
  1616. #if !SANITIZER_MAC
  1617. TSAN_INTERCEPTOR(int, pipe2, int *pipefd, int flags) {
  1618. SCOPED_TSAN_INTERCEPTOR(pipe2, pipefd, flags);
  1619. int res = REAL(pipe2)(pipefd, flags);
  1620. if (res == 0 && pipefd[0] >= 0 && pipefd[1] >= 0)
  1621. FdPipeCreate(thr, pc, pipefd[0], pipefd[1]);
  1622. return res;
  1623. }
  1624. #endif
  1625. TSAN_INTERCEPTOR(int, unlink, char *path) {
  1626. SCOPED_TSAN_INTERCEPTOR(unlink, path);
  1627. Release(thr, pc, File2addr(path));
  1628. int res = REAL(unlink)(path);
  1629. return res;
  1630. }
  1631. TSAN_INTERCEPTOR(void*, tmpfile, int fake) {
  1632. SCOPED_TSAN_INTERCEPTOR(tmpfile, fake);
  1633. void *res = REAL(tmpfile)(fake);
  1634. if (res) {
  1635. int fd = fileno_unlocked(res);
  1636. if (fd >= 0)
  1637. FdFileCreate(thr, pc, fd);
  1638. }
  1639. return res;
  1640. }
  1641. #if SANITIZER_LINUX
  1642. TSAN_INTERCEPTOR(void*, tmpfile64, int fake) {
  1643. SCOPED_TSAN_INTERCEPTOR(tmpfile64, fake);
  1644. void *res = REAL(tmpfile64)(fake);
  1645. if (res) {
  1646. int fd = fileno_unlocked(res);
  1647. if (fd >= 0)
  1648. FdFileCreate(thr, pc, fd);
  1649. }
  1650. return res;
  1651. }
  1652. #define TSAN_MAYBE_INTERCEPT_TMPFILE64 TSAN_INTERCEPT(tmpfile64)
  1653. #else
  1654. #define TSAN_MAYBE_INTERCEPT_TMPFILE64
  1655. #endif
  1656. static void FlushStreams() {
  1657. // Flushing all the streams here may freeze the process if a child thread is
  1658. // performing file stream operations at the same time.
  1659. REAL(fflush)(stdout);
  1660. REAL(fflush)(stderr);
  1661. }
  1662. TSAN_INTERCEPTOR(void, abort, int fake) {
  1663. SCOPED_TSAN_INTERCEPTOR(abort, fake);
  1664. FlushStreams();
  1665. REAL(abort)(fake);
  1666. }
  1667. TSAN_INTERCEPTOR(int, rmdir, char *path) {
  1668. SCOPED_TSAN_INTERCEPTOR(rmdir, path);
  1669. Release(thr, pc, Dir2addr(path));
  1670. int res = REAL(rmdir)(path);
  1671. return res;
  1672. }
  1673. TSAN_INTERCEPTOR(int, closedir, void *dirp) {
  1674. SCOPED_TSAN_INTERCEPTOR(closedir, dirp);
  1675. if (dirp) {
  1676. int fd = dirfd(dirp);
  1677. FdClose(thr, pc, fd);
  1678. }
  1679. return REAL(closedir)(dirp);
  1680. }
  1681. #if SANITIZER_LINUX
  1682. TSAN_INTERCEPTOR(int, epoll_create, int size) {
  1683. SCOPED_TSAN_INTERCEPTOR(epoll_create, size);
  1684. int fd = REAL(epoll_create)(size);
  1685. if (fd >= 0)
  1686. FdPollCreate(thr, pc, fd);
  1687. return fd;
  1688. }
  1689. TSAN_INTERCEPTOR(int, epoll_create1, int flags) {
  1690. SCOPED_TSAN_INTERCEPTOR(epoll_create1, flags);
  1691. int fd = REAL(epoll_create1)(flags);
  1692. if (fd >= 0)
  1693. FdPollCreate(thr, pc, fd);
  1694. return fd;
  1695. }
  1696. TSAN_INTERCEPTOR(int, epoll_ctl, int epfd, int op, int fd, void *ev) {
  1697. SCOPED_TSAN_INTERCEPTOR(epoll_ctl, epfd, op, fd, ev);
  1698. if (epfd >= 0)
  1699. FdAccess(thr, pc, epfd);
  1700. if (epfd >= 0 && fd >= 0)
  1701. FdAccess(thr, pc, fd);
  1702. if (op == EPOLL_CTL_ADD && epfd >= 0)
  1703. FdRelease(thr, pc, epfd);
  1704. int res = REAL(epoll_ctl)(epfd, op, fd, ev);
  1705. return res;
  1706. }
  1707. TSAN_INTERCEPTOR(int, epoll_wait, int epfd, void *ev, int cnt, int timeout) {
  1708. SCOPED_TSAN_INTERCEPTOR(epoll_wait, epfd, ev, cnt, timeout);
  1709. if (epfd >= 0)
  1710. FdAccess(thr, pc, epfd);
  1711. int res = BLOCK_REAL(epoll_wait)(epfd, ev, cnt, timeout);
  1712. if (res > 0 && epfd >= 0)
  1713. FdAcquire(thr, pc, epfd);
  1714. return res;
  1715. }
  1716. TSAN_INTERCEPTOR(int, epoll_pwait, int epfd, void *ev, int cnt, int timeout,
  1717. void *sigmask) {
  1718. SCOPED_TSAN_INTERCEPTOR(epoll_pwait, epfd, ev, cnt, timeout, sigmask);
  1719. if (epfd >= 0)
  1720. FdAccess(thr, pc, epfd);
  1721. int res = BLOCK_REAL(epoll_pwait)(epfd, ev, cnt, timeout, sigmask);
  1722. if (res > 0 && epfd >= 0)
  1723. FdAcquire(thr, pc, epfd);
  1724. return res;
  1725. }
  1726. #define TSAN_MAYBE_INTERCEPT_EPOLL \
  1727. TSAN_INTERCEPT(epoll_create); \
  1728. TSAN_INTERCEPT(epoll_create1); \
  1729. TSAN_INTERCEPT(epoll_ctl); \
  1730. TSAN_INTERCEPT(epoll_wait); \
  1731. TSAN_INTERCEPT(epoll_pwait)
  1732. #else
  1733. #define TSAN_MAYBE_INTERCEPT_EPOLL
  1734. #endif
  1735. // The following functions are intercepted merely to process pending signals.
  1736. // If program blocks signal X, we must deliver the signal before the function
  1737. // returns. Similarly, if program unblocks a signal (or returns from sigsuspend)
  1738. // it's better to deliver the signal straight away.
  1739. TSAN_INTERCEPTOR(int, sigsuspend, const __sanitizer_sigset_t *mask) {
  1740. SCOPED_TSAN_INTERCEPTOR(sigsuspend, mask);
  1741. return REAL(sigsuspend)(mask);
  1742. }
  1743. TSAN_INTERCEPTOR(int, sigblock, int mask) {
  1744. SCOPED_TSAN_INTERCEPTOR(sigblock, mask);
  1745. return REAL(sigblock)(mask);
  1746. }
  1747. TSAN_INTERCEPTOR(int, sigsetmask, int mask) {
  1748. SCOPED_TSAN_INTERCEPTOR(sigsetmask, mask);
  1749. return REAL(sigsetmask)(mask);
  1750. }
  1751. TSAN_INTERCEPTOR(int, pthread_sigmask, int how, const __sanitizer_sigset_t *set,
  1752. __sanitizer_sigset_t *oldset) {
  1753. SCOPED_TSAN_INTERCEPTOR(pthread_sigmask, how, set, oldset);
  1754. return REAL(pthread_sigmask)(how, set, oldset);
  1755. }
  1756. namespace __tsan {
  1757. static void ReportErrnoSpoiling(ThreadState *thr, uptr pc) {
  1758. VarSizeStackTrace stack;
  1759. // StackTrace::GetNestInstructionPc(pc) is used because return address is
  1760. // expected, OutputReport() will undo this.
  1761. ObtainCurrentStack(thr, StackTrace::GetNextInstructionPc(pc), &stack);
  1762. ThreadRegistryLock l(&ctx->thread_registry);
  1763. ScopedReport rep(ReportTypeErrnoInSignal);
  1764. if (!IsFiredSuppression(ctx, ReportTypeErrnoInSignal, stack)) {
  1765. rep.AddStack(stack, true);
  1766. OutputReport(thr, rep);
  1767. }
  1768. }
  1769. static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
  1770. int sig, __sanitizer_siginfo *info,
  1771. void *uctx) {
  1772. __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
  1773. if (acquire)
  1774. Acquire(thr, 0, (uptr)&sigactions[sig]);
  1775. // Signals are generally asynchronous, so if we receive a signals when
  1776. // ignores are enabled we should disable ignores. This is critical for sync
  1777. // and interceptors, because otherwise we can miss synchronization and report
  1778. // false races.
  1779. int ignore_reads_and_writes = thr->ignore_reads_and_writes;
  1780. int ignore_interceptors = thr->ignore_interceptors;
  1781. int ignore_sync = thr->ignore_sync;
  1782. // For symbolizer we only process SIGSEGVs synchronously
  1783. // (bug in symbolizer or in tsan). But we want to reset
  1784. // in_symbolizer to fail gracefully. Symbolizer and user code
  1785. // use different memory allocators, so if we don't reset
  1786. // in_symbolizer we can get memory allocated with one being
  1787. // feed with another, which can cause more crashes.
  1788. int in_symbolizer = thr->in_symbolizer;
  1789. if (!ctx->after_multithreaded_fork) {
  1790. thr->ignore_reads_and_writes = 0;
  1791. thr->fast_state.ClearIgnoreBit();
  1792. thr->ignore_interceptors = 0;
  1793. thr->ignore_sync = 0;
  1794. thr->in_symbolizer = 0;
  1795. }
  1796. // Ensure that the handler does not spoil errno.
  1797. const int saved_errno = errno;
  1798. errno = 99;
  1799. // This code races with sigaction. Be careful to not read sa_sigaction twice.
  1800. // Also need to remember pc for reporting before the call,
  1801. // because the handler can reset it.
  1802. volatile uptr pc = (sigactions[sig].sa_flags & SA_SIGINFO)
  1803. ? (uptr)sigactions[sig].sigaction
  1804. : (uptr)sigactions[sig].handler;
  1805. if (pc != sig_dfl && pc != sig_ign) {
  1806. // The callback can be either sa_handler or sa_sigaction.
  1807. // They have different signatures, but we assume that passing
  1808. // additional arguments to sa_handler works and is harmless.
  1809. ((__sanitizer_sigactionhandler_ptr)pc)(sig, info, uctx);
  1810. }
  1811. if (!ctx->after_multithreaded_fork) {
  1812. thr->ignore_reads_and_writes = ignore_reads_and_writes;
  1813. if (ignore_reads_and_writes)
  1814. thr->fast_state.SetIgnoreBit();
  1815. thr->ignore_interceptors = ignore_interceptors;
  1816. thr->ignore_sync = ignore_sync;
  1817. thr->in_symbolizer = in_symbolizer;
  1818. }
  1819. // We do not detect errno spoiling for SIGTERM,
  1820. // because some SIGTERM handlers do spoil errno but reraise SIGTERM,
  1821. // tsan reports false positive in such case.
  1822. // It's difficult to properly detect this situation (reraise),
  1823. // because in async signal processing case (when handler is called directly
  1824. // from rtl_generic_sighandler) we have not yet received the reraised
  1825. // signal; and it looks too fragile to intercept all ways to reraise a signal.
  1826. if (ShouldReport(thr, ReportTypeErrnoInSignal) && !sync && sig != SIGTERM &&
  1827. errno != 99)
  1828. ReportErrnoSpoiling(thr, pc);
  1829. errno = saved_errno;
  1830. }
  1831. void ProcessPendingSignalsImpl(ThreadState *thr) {
  1832. atomic_store(&thr->pending_signals, 0, memory_order_relaxed);
  1833. ThreadSignalContext *sctx = SigCtx(thr);
  1834. if (sctx == 0)
  1835. return;
  1836. atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
  1837. internal_sigfillset(&sctx->emptyset);
  1838. int res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->emptyset, &sctx->oldset);
  1839. CHECK_EQ(res, 0);
  1840. for (int sig = 0; sig < kSigCount; sig++) {
  1841. SignalDesc *signal = &sctx->pending_signals[sig];
  1842. if (signal->armed) {
  1843. signal->armed = false;
  1844. CallUserSignalHandler(thr, false, true, sig, &signal->siginfo,
  1845. &signal->ctx);
  1846. }
  1847. }
  1848. res = REAL(pthread_sigmask)(SIG_SETMASK, &sctx->oldset, 0);
  1849. CHECK_EQ(res, 0);
  1850. atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
  1851. }
  1852. } // namespace __tsan
  1853. static bool is_sync_signal(ThreadSignalContext *sctx, int sig) {
  1854. return sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || sig == SIGTRAP ||
  1855. sig == SIGABRT || sig == SIGFPE || sig == SIGPIPE || sig == SIGSYS ||
  1856. // If we are sending signal to ourselves, we must process it now.
  1857. (sctx && sig == sctx->int_signal_send);
  1858. }
  1859. void sighandler(int sig, __sanitizer_siginfo *info, void *ctx) {
  1860. ThreadState *thr = cur_thread_init();
  1861. ThreadSignalContext *sctx = SigCtx(thr);
  1862. if (sig < 0 || sig >= kSigCount) {
  1863. VPrintf(1, "ThreadSanitizer: ignoring signal %d\n", sig);
  1864. return;
  1865. }
  1866. // Don't mess with synchronous signals.
  1867. const bool sync = is_sync_signal(sctx, sig);
  1868. if (sync ||
  1869. // If we are in blocking function, we can safely process it now
  1870. // (but check if we are in a recursive interceptor,
  1871. // i.e. pthread_join()->munmap()).
  1872. (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed))) {
  1873. atomic_fetch_add(&thr->in_signal_handler, 1, memory_order_relaxed);
  1874. if (sctx && atomic_load(&sctx->in_blocking_func, memory_order_relaxed)) {
  1875. atomic_store(&sctx->in_blocking_func, 0, memory_order_relaxed);
  1876. CallUserSignalHandler(thr, sync, true, sig, info, ctx);
  1877. atomic_store(&sctx->in_blocking_func, 1, memory_order_relaxed);
  1878. } else {
  1879. // Be very conservative with when we do acquire in this case.
  1880. // It's unsafe to do acquire in async handlers, because ThreadState
  1881. // can be in inconsistent state.
  1882. // SIGSYS looks relatively safe -- it's synchronous and can actually
  1883. // need some global state.
  1884. bool acq = (sig == SIGSYS);
  1885. CallUserSignalHandler(thr, sync, acq, sig, info, ctx);
  1886. }
  1887. atomic_fetch_add(&thr->in_signal_handler, -1, memory_order_relaxed);
  1888. return;
  1889. }
  1890. if (sctx == 0)
  1891. return;
  1892. SignalDesc *signal = &sctx->pending_signals[sig];
  1893. if (signal->armed == false) {
  1894. signal->armed = true;
  1895. internal_memcpy(&signal->siginfo, info, sizeof(*info));
  1896. internal_memcpy(&signal->ctx, ctx, sizeof(signal->ctx));
  1897. atomic_store(&thr->pending_signals, 1, memory_order_relaxed);
  1898. }
  1899. }
  1900. TSAN_INTERCEPTOR(int, raise, int sig) {
  1901. SCOPED_TSAN_INTERCEPTOR(raise, sig);
  1902. ThreadSignalContext *sctx = SigCtx(thr);
  1903. CHECK_NE(sctx, 0);
  1904. int prev = sctx->int_signal_send;
  1905. sctx->int_signal_send = sig;
  1906. int res = REAL(raise)(sig);
  1907. CHECK_EQ(sctx->int_signal_send, sig);
  1908. sctx->int_signal_send = prev;
  1909. return res;
  1910. }
  1911. TSAN_INTERCEPTOR(int, kill, int pid, int sig) {
  1912. SCOPED_TSAN_INTERCEPTOR(kill, pid, sig);
  1913. ThreadSignalContext *sctx = SigCtx(thr);
  1914. CHECK_NE(sctx, 0);
  1915. int prev = sctx->int_signal_send;
  1916. if (pid == (int)internal_getpid()) {
  1917. sctx->int_signal_send = sig;
  1918. }
  1919. int res = REAL(kill)(pid, sig);
  1920. if (pid == (int)internal_getpid()) {
  1921. CHECK_EQ(sctx->int_signal_send, sig);
  1922. sctx->int_signal_send = prev;
  1923. }
  1924. return res;
  1925. }
  1926. TSAN_INTERCEPTOR(int, pthread_kill, void *tid, int sig) {
  1927. SCOPED_TSAN_INTERCEPTOR(pthread_kill, tid, sig);
  1928. ThreadSignalContext *sctx = SigCtx(thr);
  1929. CHECK_NE(sctx, 0);
  1930. int prev = sctx->int_signal_send;
  1931. if (tid == pthread_self()) {
  1932. sctx->int_signal_send = sig;
  1933. }
  1934. int res = REAL(pthread_kill)(tid, sig);
  1935. if (tid == pthread_self()) {
  1936. CHECK_EQ(sctx->int_signal_send, sig);
  1937. sctx->int_signal_send = prev;
  1938. }
  1939. return res;
  1940. }
  1941. TSAN_INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
  1942. SCOPED_TSAN_INTERCEPTOR(gettimeofday, tv, tz);
  1943. // It's intercepted merely to process pending signals.
  1944. return REAL(gettimeofday)(tv, tz);
  1945. }
  1946. TSAN_INTERCEPTOR(int, getaddrinfo, void *node, void *service,
  1947. void *hints, void *rv) {
  1948. SCOPED_TSAN_INTERCEPTOR(getaddrinfo, node, service, hints, rv);
  1949. // We miss atomic synchronization in getaddrinfo,
  1950. // and can report false race between malloc and free
  1951. // inside of getaddrinfo. So ignore memory accesses.
  1952. ThreadIgnoreBegin(thr, pc);
  1953. int res = REAL(getaddrinfo)(node, service, hints, rv);
  1954. ThreadIgnoreEnd(thr);
  1955. return res;
  1956. }
  1957. TSAN_INTERCEPTOR(int, fork, int fake) {
  1958. if (in_symbolizer())
  1959. return REAL(fork)(fake);
  1960. SCOPED_INTERCEPTOR_RAW(fork, fake);
  1961. return REAL(fork)(fake);
  1962. }
  1963. void atfork_prepare() {
  1964. if (in_symbolizer())
  1965. return;
  1966. ThreadState *thr = cur_thread();
  1967. const uptr pc = StackTrace::GetCurrentPc();
  1968. ForkBefore(thr, pc);
  1969. }
  1970. void atfork_parent() {
  1971. if (in_symbolizer())
  1972. return;
  1973. ThreadState *thr = cur_thread();
  1974. const uptr pc = StackTrace::GetCurrentPc();
  1975. ForkParentAfter(thr, pc);
  1976. }
  1977. void atfork_child() {
  1978. if (in_symbolizer())
  1979. return;
  1980. ThreadState *thr = cur_thread();
  1981. const uptr pc = StackTrace::GetCurrentPc();
  1982. ForkChildAfter(thr, pc, true);
  1983. FdOnFork(thr, pc);
  1984. }
  1985. TSAN_INTERCEPTOR(int, vfork, int fake) {
  1986. // Some programs (e.g. openjdk) call close for all file descriptors
  1987. // in the child process. Under tsan it leads to false positives, because
  1988. // address space is shared, so the parent process also thinks that
  1989. // the descriptors are closed (while they are actually not).
  1990. // This leads to false positives due to missed synchronization.
  1991. // Strictly saying this is undefined behavior, because vfork child is not
  1992. // allowed to call any functions other than exec/exit. But this is what
  1993. // openjdk does, so we want to handle it.
  1994. // We could disable interceptors in the child process. But it's not possible
  1995. // to simply intercept and wrap vfork, because vfork child is not allowed
  1996. // to return from the function that calls vfork, and that's exactly what
  1997. // we would do. So this would require some assembly trickery as well.
  1998. // Instead we simply turn vfork into fork.
  1999. return WRAP(fork)(fake);
  2000. }
  2001. #if SANITIZER_LINUX
  2002. TSAN_INTERCEPTOR(int, clone, int (*fn)(void *), void *stack, int flags,
  2003. void *arg, int *parent_tid, void *tls, pid_t *child_tid) {
  2004. SCOPED_INTERCEPTOR_RAW(clone, fn, stack, flags, arg, parent_tid, tls,
  2005. child_tid);
  2006. struct Arg {
  2007. int (*fn)(void *);
  2008. void *arg;
  2009. };
  2010. auto wrapper = +[](void *p) -> int {
  2011. auto *thr = cur_thread();
  2012. uptr pc = GET_CURRENT_PC();
  2013. // Start the background thread for fork, but not for clone.
  2014. // For fork we did this always and it's known to work (or user code has
  2015. // adopted). But if we do this for the new clone interceptor some code
  2016. // (sandbox2) fails. So model we used to do for years and don't start the
  2017. // background thread after clone.
  2018. ForkChildAfter(thr, pc, false);
  2019. FdOnFork(thr, pc);
  2020. auto *arg = static_cast<Arg *>(p);
  2021. return arg->fn(arg->arg);
  2022. };
  2023. ForkBefore(thr, pc);
  2024. Arg arg_wrapper = {fn, arg};
  2025. int pid = REAL(clone)(wrapper, stack, flags, &arg_wrapper, parent_tid, tls,
  2026. child_tid);
  2027. ForkParentAfter(thr, pc);
  2028. return pid;
  2029. }
  2030. #endif
  2031. #if !SANITIZER_MAC && !SANITIZER_ANDROID
  2032. typedef int (*dl_iterate_phdr_cb_t)(__sanitizer_dl_phdr_info *info, SIZE_T size,
  2033. void *data);
  2034. struct dl_iterate_phdr_data {
  2035. ThreadState *thr;
  2036. uptr pc;
  2037. dl_iterate_phdr_cb_t cb;
  2038. void *data;
  2039. };
  2040. static bool IsAppNotRodata(uptr addr) {
  2041. return IsAppMem(addr) && *MemToShadow(addr) != kShadowRodata;
  2042. }
  2043. static int dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
  2044. void *data) {
  2045. dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
  2046. // dlopen/dlclose allocate/free dynamic-linker-internal memory, which is later
  2047. // accessible in dl_iterate_phdr callback. But we don't see synchronization
  2048. // inside of dynamic linker, so we "unpoison" it here in order to not
  2049. // produce false reports. Ignoring malloc/free in dlopen/dlclose is not enough
  2050. // because some libc functions call __libc_dlopen.
  2051. if (info && IsAppNotRodata((uptr)info->dlpi_name))
  2052. MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
  2053. internal_strlen(info->dlpi_name));
  2054. int res = cbdata->cb(info, size, cbdata->data);
  2055. // Perform the check one more time in case info->dlpi_name was overwritten
  2056. // by user callback.
  2057. if (info && IsAppNotRodata((uptr)info->dlpi_name))
  2058. MemoryResetRange(cbdata->thr, cbdata->pc, (uptr)info->dlpi_name,
  2059. internal_strlen(info->dlpi_name));
  2060. return res;
  2061. }
  2062. TSAN_INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb_t cb, void *data) {
  2063. SCOPED_TSAN_INTERCEPTOR(dl_iterate_phdr, cb, data);
  2064. dl_iterate_phdr_data cbdata;
  2065. cbdata.thr = thr;
  2066. cbdata.pc = pc;
  2067. cbdata.cb = cb;
  2068. cbdata.data = data;
  2069. int res = REAL(dl_iterate_phdr)(dl_iterate_phdr_cb, &cbdata);
  2070. return res;
  2071. }
  2072. #endif
  2073. static int OnExit(ThreadState *thr) {
  2074. int status = Finalize(thr);
  2075. FlushStreams();
  2076. return status;
  2077. }
  2078. struct TsanInterceptorContext {
  2079. ThreadState *thr;
  2080. const uptr pc;
  2081. };
  2082. #if !SANITIZER_MAC
  2083. static void HandleRecvmsg(ThreadState *thr, uptr pc,
  2084. __sanitizer_msghdr *msg) {
  2085. int fds[64];
  2086. int cnt = ExtractRecvmsgFDs(msg, fds, ARRAY_SIZE(fds));
  2087. for (int i = 0; i < cnt; i++)
  2088. FdEventCreate(thr, pc, fds[i]);
  2089. }
  2090. #endif
  2091. #include "sanitizer_common/sanitizer_platform_interceptors.h"
  2092. // Causes interceptor recursion (getaddrinfo() and fopen())
  2093. #undef SANITIZER_INTERCEPT_GETADDRINFO
  2094. // We define our own.
  2095. #if SANITIZER_INTERCEPT_TLS_GET_ADDR
  2096. #define NEED_TLS_GET_ADDR
  2097. #endif
  2098. #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
  2099. #define SANITIZER_INTERCEPT_TLS_GET_OFFSET 1
  2100. #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK
  2101. #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
  2102. #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \
  2103. INTERCEPT_FUNCTION_VER(name, ver)
  2104. #define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver) \
  2105. (INTERCEPT_FUNCTION_VER(name, ver) || INTERCEPT_FUNCTION(name))
  2106. #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
  2107. MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr, \
  2108. ((TsanInterceptorContext *)ctx)->pc, (uptr)ptr, size, \
  2109. true)
  2110. #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
  2111. MemoryAccessRange(((TsanInterceptorContext *) ctx)->thr, \
  2112. ((TsanInterceptorContext *) ctx)->pc, (uptr) ptr, size, \
  2113. false)
  2114. #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
  2115. SCOPED_TSAN_INTERCEPTOR(func, __VA_ARGS__); \
  2116. TsanInterceptorContext _ctx = {thr, pc}; \
  2117. ctx = (void *)&_ctx; \
  2118. (void)ctx;
  2119. #define COMMON_INTERCEPTOR_ENTER_NOIGNORE(ctx, func, ...) \
  2120. SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
  2121. TsanInterceptorContext _ctx = {thr, pc}; \
  2122. ctx = (void *)&_ctx; \
  2123. (void)ctx;
  2124. #define COMMON_INTERCEPTOR_FILE_OPEN(ctx, file, path) \
  2125. if (path) \
  2126. Acquire(thr, pc, File2addr(path)); \
  2127. if (file) { \
  2128. int fd = fileno_unlocked(file); \
  2129. if (fd >= 0) FdFileCreate(thr, pc, fd); \
  2130. }
  2131. #define COMMON_INTERCEPTOR_FILE_CLOSE(ctx, file) \
  2132. if (file) { \
  2133. int fd = fileno_unlocked(file); \
  2134. if (fd >= 0) FdClose(thr, pc, fd); \
  2135. }
  2136. #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \
  2137. libignore()->OnLibraryLoaded(filename)
  2138. #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \
  2139. libignore()->OnLibraryUnloaded()
  2140. #define COMMON_INTERCEPTOR_ACQUIRE(ctx, u) \
  2141. Acquire(((TsanInterceptorContext *) ctx)->thr, pc, u)
  2142. #define COMMON_INTERCEPTOR_RELEASE(ctx, u) \
  2143. Release(((TsanInterceptorContext *) ctx)->thr, pc, u)
  2144. #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
  2145. Acquire(((TsanInterceptorContext *) ctx)->thr, pc, Dir2addr(path))
  2146. #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
  2147. FdAcquire(((TsanInterceptorContext *) ctx)->thr, pc, fd)
  2148. #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
  2149. FdRelease(((TsanInterceptorContext *) ctx)->thr, pc, fd)
  2150. #define COMMON_INTERCEPTOR_FD_ACCESS(ctx, fd) \
  2151. FdAccess(((TsanInterceptorContext *) ctx)->thr, pc, fd)
  2152. #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
  2153. FdSocketAccept(((TsanInterceptorContext *) ctx)->thr, pc, fd, newfd)
  2154. #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
  2155. ThreadSetName(((TsanInterceptorContext *) ctx)->thr, name)
  2156. #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
  2157. __tsan::ctx->thread_registry.SetThreadNameByUserId(thread, name)
  2158. #define COMMON_INTERCEPTOR_BLOCK_REAL(name) BLOCK_REAL(name)
  2159. #define COMMON_INTERCEPTOR_ON_EXIT(ctx) \
  2160. OnExit(((TsanInterceptorContext *) ctx)->thr)
  2161. #define COMMON_INTERCEPTOR_MUTEX_PRE_LOCK(ctx, m) \
  2162. MutexPreLock(((TsanInterceptorContext *)ctx)->thr, \
  2163. ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
  2164. #define COMMON_INTERCEPTOR_MUTEX_POST_LOCK(ctx, m) \
  2165. MutexPostLock(((TsanInterceptorContext *)ctx)->thr, \
  2166. ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
  2167. #define COMMON_INTERCEPTOR_MUTEX_UNLOCK(ctx, m) \
  2168. MutexUnlock(((TsanInterceptorContext *)ctx)->thr, \
  2169. ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
  2170. #define COMMON_INTERCEPTOR_MUTEX_REPAIR(ctx, m) \
  2171. MutexRepair(((TsanInterceptorContext *)ctx)->thr, \
  2172. ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
  2173. #define COMMON_INTERCEPTOR_MUTEX_INVALID(ctx, m) \
  2174. MutexInvalidAccess(((TsanInterceptorContext *)ctx)->thr, \
  2175. ((TsanInterceptorContext *)ctx)->pc, (uptr)m)
  2176. #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, sz, prot, flags, fd, \
  2177. off) \
  2178. do { \
  2179. return mmap_interceptor(thr, pc, REAL(mmap), addr, sz, prot, flags, fd, \
  2180. off); \
  2181. } while (false)
  2182. #if !SANITIZER_MAC
  2183. #define COMMON_INTERCEPTOR_HANDLE_RECVMSG(ctx, msg) \
  2184. HandleRecvmsg(((TsanInterceptorContext *)ctx)->thr, \
  2185. ((TsanInterceptorContext *)ctx)->pc, msg)
  2186. #endif
  2187. #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \
  2188. if (TsanThread *t = GetCurrentThread()) { \
  2189. *begin = t->tls_begin(); \
  2190. *end = t->tls_end(); \
  2191. } else { \
  2192. *begin = *end = 0; \
  2193. }
  2194. #define COMMON_INTERCEPTOR_USER_CALLBACK_START() \
  2195. SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_START()
  2196. #define COMMON_INTERCEPTOR_USER_CALLBACK_END() \
  2197. SCOPED_TSAN_INTERCEPTOR_USER_CALLBACK_END()
  2198. #include "sanitizer_common/sanitizer_common_interceptors.inc"
  2199. static int sigaction_impl(int sig, const __sanitizer_sigaction *act,
  2200. __sanitizer_sigaction *old);
  2201. static __sanitizer_sighandler_ptr signal_impl(int sig,
  2202. __sanitizer_sighandler_ptr h);
  2203. #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \
  2204. { return sigaction_impl(signo, act, oldact); }
  2205. #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \
  2206. { return (uptr)signal_impl(signo, (__sanitizer_sighandler_ptr)handler); }
  2207. #include "sanitizer_common/sanitizer_signal_interceptors.inc"
  2208. int sigaction_impl(int sig, const __sanitizer_sigaction *act,
  2209. __sanitizer_sigaction *old) {
  2210. // Note: if we call REAL(sigaction) directly for any reason without proxying
  2211. // the signal handler through sighandler, very bad things will happen.
  2212. // The handler will run synchronously and corrupt tsan per-thread state.
  2213. SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
  2214. if (sig <= 0 || sig >= kSigCount) {
  2215. errno = errno_EINVAL;
  2216. return -1;
  2217. }
  2218. __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
  2219. __sanitizer_sigaction old_stored;
  2220. if (old) internal_memcpy(&old_stored, &sigactions[sig], sizeof(old_stored));
  2221. __sanitizer_sigaction newact;
  2222. if (act) {
  2223. // Copy act into sigactions[sig].
  2224. // Can't use struct copy, because compiler can emit call to memcpy.
  2225. // Can't use internal_memcpy, because it copies byte-by-byte,
  2226. // and signal handler reads the handler concurrently. It it can read
  2227. // some bytes from old value and some bytes from new value.
  2228. // Use volatile to prevent insertion of memcpy.
  2229. sigactions[sig].handler =
  2230. *(volatile __sanitizer_sighandler_ptr const *)&act->handler;
  2231. sigactions[sig].sa_flags = *(volatile int const *)&act->sa_flags;
  2232. internal_memcpy(&sigactions[sig].sa_mask, &act->sa_mask,
  2233. sizeof(sigactions[sig].sa_mask));
  2234. #if !SANITIZER_FREEBSD && !SANITIZER_MAC && !SANITIZER_NETBSD
  2235. sigactions[sig].sa_restorer = act->sa_restorer;
  2236. #endif
  2237. internal_memcpy(&newact, act, sizeof(newact));
  2238. internal_sigfillset(&newact.sa_mask);
  2239. if ((act->sa_flags & SA_SIGINFO) ||
  2240. ((uptr)act->handler != sig_ign && (uptr)act->handler != sig_dfl)) {
  2241. newact.sa_flags |= SA_SIGINFO;
  2242. newact.sigaction = sighandler;
  2243. }
  2244. ReleaseStore(thr, pc, (uptr)&sigactions[sig]);
  2245. act = &newact;
  2246. }
  2247. int res = REAL(sigaction)(sig, act, old);
  2248. if (res == 0 && old && old->sigaction == sighandler)
  2249. internal_memcpy(old, &old_stored, sizeof(*old));
  2250. return res;
  2251. }
  2252. static __sanitizer_sighandler_ptr signal_impl(int sig,
  2253. __sanitizer_sighandler_ptr h) {
  2254. __sanitizer_sigaction act;
  2255. act.handler = h;
  2256. internal_memset(&act.sa_mask, -1, sizeof(act.sa_mask));
  2257. act.sa_flags = 0;
  2258. __sanitizer_sigaction old;
  2259. int res = sigaction_symname(sig, &act, &old);
  2260. if (res) return (__sanitizer_sighandler_ptr)sig_err;
  2261. return old.handler;
  2262. }
  2263. #define TSAN_SYSCALL() \
  2264. ThreadState *thr = cur_thread(); \
  2265. if (thr->ignore_interceptors) \
  2266. return; \
  2267. ScopedSyscall scoped_syscall(thr)
  2268. struct ScopedSyscall {
  2269. ThreadState *thr;
  2270. explicit ScopedSyscall(ThreadState *thr) : thr(thr) { LazyInitialize(thr); }
  2271. ~ScopedSyscall() {
  2272. ProcessPendingSignals(thr);
  2273. }
  2274. };
  2275. #if !SANITIZER_FREEBSD && !SANITIZER_MAC
  2276. static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
  2277. TSAN_SYSCALL();
  2278. MemoryAccessRange(thr, pc, p, s, write);
  2279. }
  2280. static USED void syscall_acquire(uptr pc, uptr addr) {
  2281. TSAN_SYSCALL();
  2282. Acquire(thr, pc, addr);
  2283. DPrintf("syscall_acquire(0x%zx))\n", addr);
  2284. }
  2285. static USED void syscall_release(uptr pc, uptr addr) {
  2286. TSAN_SYSCALL();
  2287. DPrintf("syscall_release(0x%zx)\n", addr);
  2288. Release(thr, pc, addr);
  2289. }
  2290. static void syscall_fd_close(uptr pc, int fd) {
  2291. TSAN_SYSCALL();
  2292. FdClose(thr, pc, fd);
  2293. }
  2294. static USED void syscall_fd_acquire(uptr pc, int fd) {
  2295. TSAN_SYSCALL();
  2296. FdAcquire(thr, pc, fd);
  2297. DPrintf("syscall_fd_acquire(%d)\n", fd);
  2298. }
  2299. static USED void syscall_fd_release(uptr pc, int fd) {
  2300. TSAN_SYSCALL();
  2301. DPrintf("syscall_fd_release(%d)\n", fd);
  2302. FdRelease(thr, pc, fd);
  2303. }
  2304. static void syscall_pre_fork(uptr pc) { ForkBefore(cur_thread(), pc); }
  2305. static void syscall_post_fork(uptr pc, int pid) {
  2306. ThreadState *thr = cur_thread();
  2307. if (pid == 0) {
  2308. // child
  2309. ForkChildAfter(thr, pc, true);
  2310. FdOnFork(thr, pc);
  2311. } else if (pid > 0) {
  2312. // parent
  2313. ForkParentAfter(thr, pc);
  2314. } else {
  2315. // error
  2316. ForkParentAfter(thr, pc);
  2317. }
  2318. }
  2319. #endif
  2320. #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) \
  2321. syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), false)
  2322. #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
  2323. syscall_access_range(GET_CALLER_PC(), (uptr)(p), (uptr)(s), true)
  2324. #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
  2325. do { \
  2326. (void)(p); \
  2327. (void)(s); \
  2328. } while (false)
  2329. #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) \
  2330. do { \
  2331. (void)(p); \
  2332. (void)(s); \
  2333. } while (false)
  2334. #define COMMON_SYSCALL_ACQUIRE(addr) \
  2335. syscall_acquire(GET_CALLER_PC(), (uptr)(addr))
  2336. #define COMMON_SYSCALL_RELEASE(addr) \
  2337. syscall_release(GET_CALLER_PC(), (uptr)(addr))
  2338. #define COMMON_SYSCALL_FD_CLOSE(fd) syscall_fd_close(GET_CALLER_PC(), fd)
  2339. #define COMMON_SYSCALL_FD_ACQUIRE(fd) syscall_fd_acquire(GET_CALLER_PC(), fd)
  2340. #define COMMON_SYSCALL_FD_RELEASE(fd) syscall_fd_release(GET_CALLER_PC(), fd)
  2341. #define COMMON_SYSCALL_PRE_FORK() \
  2342. syscall_pre_fork(GET_CALLER_PC())
  2343. #define COMMON_SYSCALL_POST_FORK(res) \
  2344. syscall_post_fork(GET_CALLER_PC(), res)
  2345. #include "sanitizer_common/sanitizer_common_syscalls.inc"
  2346. #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
  2347. #ifdef NEED_TLS_GET_ADDR
  2348. static void handle_tls_addr(void *arg, void *res) {
  2349. ThreadState *thr = cur_thread();
  2350. if (!thr)
  2351. return;
  2352. DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr,
  2353. thr->tls_addr + thr->tls_size);
  2354. if (!dtv)
  2355. return;
  2356. // New DTLS block has been allocated.
  2357. MemoryResetRange(thr, 0, dtv->beg, dtv->size);
  2358. }
  2359. #if !SANITIZER_S390
  2360. // Define own interceptor instead of sanitizer_common's for three reasons:
  2361. // 1. It must not process pending signals.
  2362. // Signal handlers may contain MOVDQA instruction (see below).
  2363. // 2. It must be as simple as possible to not contain MOVDQA.
  2364. // 3. Sanitizer_common version uses COMMON_INTERCEPTOR_INITIALIZE_RANGE which
  2365. // is empty for tsan (meant only for msan).
  2366. // Note: __tls_get_addr can be called with mis-aligned stack due to:
  2367. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58066
  2368. // So the interceptor must work with mis-aligned stack, in particular, does not
  2369. // execute MOVDQA with stack addresses.
  2370. TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
  2371. void *res = REAL(__tls_get_addr)(arg);
  2372. handle_tls_addr(arg, res);
  2373. return res;
  2374. }
  2375. #else // SANITIZER_S390
  2376. TSAN_INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
  2377. uptr res = __tls_get_offset_wrapper(arg, REAL(__tls_get_offset));
  2378. char *tp = static_cast<char *>(__builtin_thread_pointer());
  2379. handle_tls_addr(arg, res + tp);
  2380. return res;
  2381. }
  2382. #endif
  2383. #endif
  2384. #if SANITIZER_NETBSD
  2385. TSAN_INTERCEPTOR(void, _lwp_exit) {
  2386. SCOPED_TSAN_INTERCEPTOR(_lwp_exit);
  2387. DestroyThreadState();
  2388. REAL(_lwp_exit)();
  2389. }
  2390. #define TSAN_MAYBE_INTERCEPT__LWP_EXIT TSAN_INTERCEPT(_lwp_exit)
  2391. #else
  2392. #define TSAN_MAYBE_INTERCEPT__LWP_EXIT
  2393. #endif
  2394. #if SANITIZER_FREEBSD
  2395. TSAN_INTERCEPTOR(void, thr_exit, tid_t *state) {
  2396. SCOPED_TSAN_INTERCEPTOR(thr_exit, state);
  2397. DestroyThreadState();
  2398. REAL(thr_exit(state));
  2399. }
  2400. #define TSAN_MAYBE_INTERCEPT_THR_EXIT TSAN_INTERCEPT(thr_exit)
  2401. #else
  2402. #define TSAN_MAYBE_INTERCEPT_THR_EXIT
  2403. #endif
  2404. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_init, void *c, void *a)
  2405. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_signal, void *c)
  2406. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_broadcast, void *c)
  2407. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_wait, void *c, void *m)
  2408. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, cond_destroy, void *c)
  2409. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_init, void *m, void *a)
  2410. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_destroy, void *m)
  2411. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, mutex_trylock, void *m)
  2412. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_init, void *m, void *a)
  2413. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_destroy, void *m)
  2414. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_rdlock, void *m)
  2415. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_tryrdlock, void *m)
  2416. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_wrlock, void *m)
  2417. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_trywrlock, void *m)
  2418. TSAN_INTERCEPTOR_NETBSD_ALIAS(int, rwlock_unlock, void *m)
  2419. TSAN_INTERCEPTOR_NETBSD_ALIAS_THR(int, once, void *o, void (*f)())
  2420. TSAN_INTERCEPTOR_NETBSD_ALIAS_THR2(int, sigsetmask, sigmask, int a, void *b,
  2421. void *c)
  2422. namespace __tsan {
  2423. static void finalize(void *arg) {
  2424. ThreadState *thr = cur_thread();
  2425. int status = Finalize(thr);
  2426. // Make sure the output is not lost.
  2427. FlushStreams();
  2428. if (status)
  2429. Die();
  2430. }
  2431. #if !SANITIZER_MAC && !SANITIZER_ANDROID
  2432. static void unreachable() {
  2433. Report("FATAL: ThreadSanitizer: unreachable called\n");
  2434. Die();
  2435. }
  2436. #endif
  2437. // Define default implementation since interception of libdispatch is optional.
  2438. SANITIZER_WEAK_ATTRIBUTE void InitializeLibdispatchInterceptors() {}
  2439. void InitializeInterceptors() {
  2440. #if !SANITIZER_MAC
  2441. // We need to setup it early, because functions like dlsym() can call it.
  2442. REAL(memset) = internal_memset;
  2443. REAL(memcpy) = internal_memcpy;
  2444. #endif
  2445. new(interceptor_ctx()) InterceptorContext();
  2446. InitializeCommonInterceptors();
  2447. InitializeSignalInterceptors();
  2448. InitializeLibdispatchInterceptors();
  2449. #if !SANITIZER_MAC
  2450. // We can not use TSAN_INTERCEPT to get setjmp addr,
  2451. // because it does &setjmp and setjmp is not present in some versions of libc.
  2452. using __interception::InterceptFunction;
  2453. InterceptFunction(TSAN_STRING_SETJMP, (uptr*)&REAL(setjmp_symname), 0, 0);
  2454. InterceptFunction("_setjmp", (uptr*)&REAL(_setjmp), 0, 0);
  2455. InterceptFunction(TSAN_STRING_SIGSETJMP, (uptr*)&REAL(sigsetjmp_symname), 0,
  2456. 0);
  2457. #if !SANITIZER_NETBSD
  2458. InterceptFunction("__sigsetjmp", (uptr*)&REAL(__sigsetjmp), 0, 0);
  2459. #endif
  2460. #endif
  2461. TSAN_INTERCEPT(longjmp_symname);
  2462. TSAN_INTERCEPT(siglongjmp_symname);
  2463. #if SANITIZER_NETBSD
  2464. TSAN_INTERCEPT(_longjmp);
  2465. #endif
  2466. TSAN_INTERCEPT(malloc);
  2467. TSAN_INTERCEPT(__libc_memalign);
  2468. TSAN_INTERCEPT(calloc);
  2469. TSAN_INTERCEPT(realloc);
  2470. TSAN_INTERCEPT(reallocarray);
  2471. TSAN_INTERCEPT(free);
  2472. TSAN_INTERCEPT(cfree);
  2473. TSAN_INTERCEPT(munmap);
  2474. TSAN_MAYBE_INTERCEPT_MEMALIGN;
  2475. TSAN_INTERCEPT(valloc);
  2476. TSAN_MAYBE_INTERCEPT_PVALLOC;
  2477. TSAN_INTERCEPT(posix_memalign);
  2478. TSAN_INTERCEPT(strcpy);
  2479. TSAN_INTERCEPT(strncpy);
  2480. TSAN_INTERCEPT(strdup);
  2481. TSAN_INTERCEPT(pthread_create);
  2482. TSAN_INTERCEPT(pthread_join);
  2483. TSAN_INTERCEPT(pthread_detach);
  2484. TSAN_INTERCEPT(pthread_exit);
  2485. #if SANITIZER_LINUX
  2486. TSAN_INTERCEPT(pthread_tryjoin_np);
  2487. TSAN_INTERCEPT(pthread_timedjoin_np);
  2488. #endif
  2489. TSAN_INTERCEPT_VER(pthread_cond_init, PTHREAD_ABI_BASE);
  2490. TSAN_INTERCEPT_VER(pthread_cond_signal, PTHREAD_ABI_BASE);
  2491. TSAN_INTERCEPT_VER(pthread_cond_broadcast, PTHREAD_ABI_BASE);
  2492. TSAN_INTERCEPT_VER(pthread_cond_wait, PTHREAD_ABI_BASE);
  2493. TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
  2494. TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
  2495. TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT;
  2496. TSAN_INTERCEPT(pthread_mutex_init);
  2497. TSAN_INTERCEPT(pthread_mutex_destroy);
  2498. TSAN_INTERCEPT(pthread_mutex_trylock);
  2499. TSAN_INTERCEPT(pthread_mutex_timedlock);
  2500. TSAN_INTERCEPT(pthread_spin_init);
  2501. TSAN_INTERCEPT(pthread_spin_destroy);
  2502. TSAN_INTERCEPT(pthread_spin_lock);
  2503. TSAN_INTERCEPT(pthread_spin_trylock);
  2504. TSAN_INTERCEPT(pthread_spin_unlock);
  2505. TSAN_INTERCEPT(pthread_rwlock_init);
  2506. TSAN_INTERCEPT(pthread_rwlock_destroy);
  2507. TSAN_INTERCEPT(pthread_rwlock_rdlock);
  2508. TSAN_INTERCEPT(pthread_rwlock_tryrdlock);
  2509. TSAN_INTERCEPT(pthread_rwlock_timedrdlock);
  2510. TSAN_INTERCEPT(pthread_rwlock_wrlock);
  2511. TSAN_INTERCEPT(pthread_rwlock_trywrlock);
  2512. TSAN_INTERCEPT(pthread_rwlock_timedwrlock);
  2513. TSAN_INTERCEPT(pthread_rwlock_unlock);
  2514. TSAN_INTERCEPT(pthread_barrier_init);
  2515. TSAN_INTERCEPT(pthread_barrier_destroy);
  2516. TSAN_INTERCEPT(pthread_barrier_wait);
  2517. TSAN_INTERCEPT(pthread_once);
  2518. TSAN_INTERCEPT(fstat);
  2519. TSAN_MAYBE_INTERCEPT___FXSTAT;
  2520. TSAN_MAYBE_INTERCEPT_FSTAT64;
  2521. TSAN_MAYBE_INTERCEPT___FXSTAT64;
  2522. TSAN_INTERCEPT(open);
  2523. TSAN_MAYBE_INTERCEPT_OPEN64;
  2524. TSAN_INTERCEPT(creat);
  2525. TSAN_MAYBE_INTERCEPT_CREAT64;
  2526. TSAN_INTERCEPT(dup);
  2527. TSAN_INTERCEPT(dup2);
  2528. TSAN_INTERCEPT(dup3);
  2529. TSAN_MAYBE_INTERCEPT_EVENTFD;
  2530. TSAN_MAYBE_INTERCEPT_SIGNALFD;
  2531. TSAN_MAYBE_INTERCEPT_INOTIFY_INIT;
  2532. TSAN_MAYBE_INTERCEPT_INOTIFY_INIT1;
  2533. TSAN_INTERCEPT(socket);
  2534. TSAN_INTERCEPT(socketpair);
  2535. TSAN_INTERCEPT(connect);
  2536. TSAN_INTERCEPT(bind);
  2537. TSAN_INTERCEPT(listen);
  2538. TSAN_MAYBE_INTERCEPT_EPOLL;
  2539. TSAN_INTERCEPT(close);
  2540. TSAN_MAYBE_INTERCEPT___CLOSE;
  2541. TSAN_MAYBE_INTERCEPT___RES_ICLOSE;
  2542. TSAN_INTERCEPT(pipe);
  2543. TSAN_INTERCEPT(pipe2);
  2544. TSAN_INTERCEPT(unlink);
  2545. TSAN_INTERCEPT(tmpfile);
  2546. TSAN_MAYBE_INTERCEPT_TMPFILE64;
  2547. TSAN_INTERCEPT(abort);
  2548. TSAN_INTERCEPT(rmdir);
  2549. TSAN_INTERCEPT(closedir);
  2550. TSAN_INTERCEPT(sigsuspend);
  2551. TSAN_INTERCEPT(sigblock);
  2552. TSAN_INTERCEPT(sigsetmask);
  2553. TSAN_INTERCEPT(pthread_sigmask);
  2554. TSAN_INTERCEPT(raise);
  2555. TSAN_INTERCEPT(kill);
  2556. TSAN_INTERCEPT(pthread_kill);
  2557. TSAN_INTERCEPT(sleep);
  2558. TSAN_INTERCEPT(usleep);
  2559. TSAN_INTERCEPT(nanosleep);
  2560. TSAN_INTERCEPT(pause);
  2561. TSAN_INTERCEPT(gettimeofday);
  2562. TSAN_INTERCEPT(getaddrinfo);
  2563. TSAN_INTERCEPT(fork);
  2564. TSAN_INTERCEPT(vfork);
  2565. #if SANITIZER_LINUX
  2566. TSAN_INTERCEPT(clone);
  2567. #endif
  2568. #if !SANITIZER_ANDROID
  2569. TSAN_INTERCEPT(dl_iterate_phdr);
  2570. #endif
  2571. TSAN_MAYBE_INTERCEPT_ON_EXIT;
  2572. TSAN_INTERCEPT(__cxa_atexit);
  2573. TSAN_INTERCEPT(_exit);
  2574. #ifdef NEED_TLS_GET_ADDR
  2575. #if !SANITIZER_S390
  2576. TSAN_INTERCEPT(__tls_get_addr);
  2577. #else
  2578. TSAN_INTERCEPT(__tls_get_addr_internal);
  2579. TSAN_INTERCEPT(__tls_get_offset);
  2580. #endif
  2581. #endif
  2582. TSAN_MAYBE_INTERCEPT__LWP_EXIT;
  2583. TSAN_MAYBE_INTERCEPT_THR_EXIT;
  2584. #if !SANITIZER_MAC && !SANITIZER_ANDROID
  2585. // Need to setup it, because interceptors check that the function is resolved.
  2586. // But atexit is emitted directly into the module, so can't be resolved.
  2587. REAL(atexit) = (int(*)(void(*)()))unreachable;
  2588. #endif
  2589. if (REAL(__cxa_atexit)(&finalize, 0, 0)) {
  2590. Printf("ThreadSanitizer: failed to setup atexit callback\n");
  2591. Die();
  2592. }
  2593. if (pthread_atfork(atfork_prepare, atfork_parent, atfork_child)) {
  2594. Printf("ThreadSanitizer: failed to setup atfork callbacks\n");
  2595. Die();
  2596. }
  2597. #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
  2598. if (pthread_key_create(&interceptor_ctx()->finalize_key, &thread_finalize)) {
  2599. Printf("ThreadSanitizer: failed to create thread key\n");
  2600. Die();
  2601. }
  2602. #endif
  2603. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_init);
  2604. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_signal);
  2605. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_broadcast);
  2606. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_wait);
  2607. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(cond_destroy);
  2608. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_init);
  2609. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_destroy);
  2610. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(mutex_trylock);
  2611. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_init);
  2612. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_destroy);
  2613. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_rdlock);
  2614. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_tryrdlock);
  2615. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_wrlock);
  2616. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_trywrlock);
  2617. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS(rwlock_unlock);
  2618. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(once);
  2619. TSAN_MAYBE_INTERCEPT_NETBSD_ALIAS_THR(sigsetmask);
  2620. FdInit();
  2621. }
  2622. } // namespace __tsan
  2623. // Invisible barrier for tests.
  2624. // There were several unsuccessful iterations for this functionality:
  2625. // 1. Initially it was implemented in user code using
  2626. // REAL(pthread_barrier_wait). But pthread_barrier_wait is not supported on
  2627. // MacOS. Futexes are linux-specific for this matter.
  2628. // 2. Then we switched to atomics+usleep(10). But usleep produced parasitic
  2629. // "as-if synchronized via sleep" messages in reports which failed some
  2630. // output tests.
  2631. // 3. Then we switched to atomics+sched_yield. But this produced tons of tsan-
  2632. // visible events, which lead to "failed to restore stack trace" failures.
  2633. // Note that no_sanitize_thread attribute does not turn off atomic interception
  2634. // so attaching it to the function defined in user code does not help.
  2635. // That's why we now have what we have.
  2636. constexpr u32 kBarrierThreadBits = 10;
  2637. constexpr u32 kBarrierThreads = 1 << kBarrierThreadBits;
  2638. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __tsan_testonly_barrier_init(
  2639. atomic_uint32_t *barrier, u32 num_threads) {
  2640. if (num_threads >= kBarrierThreads) {
  2641. Printf("barrier_init: count is too large (%d)\n", num_threads);
  2642. Die();
  2643. }
  2644. // kBarrierThreadBits lsb is thread count,
  2645. // the remaining are count of entered threads.
  2646. atomic_store(barrier, num_threads, memory_order_relaxed);
  2647. }
  2648. static u32 barrier_epoch(u32 value) {
  2649. return (value >> kBarrierThreadBits) / (value & (kBarrierThreads - 1));
  2650. }
  2651. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __tsan_testonly_barrier_wait(
  2652. atomic_uint32_t *barrier) {
  2653. u32 old = atomic_fetch_add(barrier, kBarrierThreads, memory_order_relaxed);
  2654. u32 old_epoch = barrier_epoch(old);
  2655. if (barrier_epoch(old + kBarrierThreads) != old_epoch) {
  2656. FutexWake(barrier, (1 << 30));
  2657. return;
  2658. }
  2659. for (;;) {
  2660. u32 cur = atomic_load(barrier, memory_order_relaxed);
  2661. if (barrier_epoch(cur) != old_epoch)
  2662. return;
  2663. FutexWait(barrier, cur);
  2664. }
  2665. }