tsan_interceptors_posix.cpp 102 KB

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