tsan_interceptors_posix.cpp 101 KB

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