sanitizer_linux.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291
  1. //===-- sanitizer_linux.cpp -----------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is shared between AddressSanitizer and ThreadSanitizer
  10. // run-time libraries and implements linux-specific functions from
  11. // sanitizer_libc.h.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_platform.h"
  14. #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
  15. SANITIZER_SOLARIS
  16. #include "sanitizer_common.h"
  17. #include "sanitizer_flags.h"
  18. #include "sanitizer_getauxval.h"
  19. #include "sanitizer_internal_defs.h"
  20. #include "sanitizer_libc.h"
  21. #include "sanitizer_linux.h"
  22. #include "sanitizer_mutex.h"
  23. #include "sanitizer_placement_new.h"
  24. #include "sanitizer_procmaps.h"
  25. #if SANITIZER_LINUX && !SANITIZER_GO
  26. #include <asm/param.h>
  27. #endif
  28. // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat'
  29. // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To
  30. // access stat from asm/stat.h, without conflicting with definition in
  31. // sys/stat.h, we use this trick.
  32. #if defined(__mips64)
  33. #include <asm/unistd.h>
  34. #include <sys/types.h>
  35. #define stat kernel_stat
  36. #if SANITIZER_GO
  37. #undef st_atime
  38. #undef st_mtime
  39. #undef st_ctime
  40. #define st_atime st_atim
  41. #define st_mtime st_mtim
  42. #define st_ctime st_ctim
  43. #endif
  44. #include <asm/stat.h>
  45. #undef stat
  46. #endif
  47. #include <dlfcn.h>
  48. #include <errno.h>
  49. #include <fcntl.h>
  50. #include <link.h>
  51. #include <pthread.h>
  52. #include <sched.h>
  53. #include <signal.h>
  54. #include <sys/mman.h>
  55. #include <sys/param.h>
  56. #if !SANITIZER_SOLARIS
  57. #include <sys/ptrace.h>
  58. #endif
  59. #include <sys/resource.h>
  60. #include <sys/stat.h>
  61. #include <sys/syscall.h>
  62. #include <sys/time.h>
  63. #include <sys/types.h>
  64. #include <ucontext.h>
  65. #include <unistd.h>
  66. #if SANITIZER_LINUX
  67. #include <sys/utsname.h>
  68. #endif
  69. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  70. #include <sys/personality.h>
  71. #endif
  72. #if SANITIZER_FREEBSD
  73. #include <sys/exec.h>
  74. #error #include <sys/procctl.h>
  75. #include <sys/sysctl.h>
  76. #include <machine/atomic.h>
  77. extern "C" {
  78. // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on
  79. // FreeBSD 9.2 and 10.0.
  80. #include <sys/umtx.h>
  81. }
  82. #include <sys/thr.h>
  83. #endif // SANITIZER_FREEBSD
  84. #if SANITIZER_NETBSD
  85. #include <limits.h> // For NAME_MAX
  86. #include <sys/sysctl.h>
  87. #include <sys/exec.h>
  88. extern struct ps_strings *__ps_strings;
  89. #endif // SANITIZER_NETBSD
  90. #if SANITIZER_SOLARIS
  91. #include <stdlib.h>
  92. #include <thread.h>
  93. #define environ _environ
  94. #endif
  95. extern char **environ;
  96. #if SANITIZER_LINUX
  97. // <linux/time.h>
  98. struct kernel_timeval {
  99. long tv_sec;
  100. long tv_usec;
  101. };
  102. // <linux/futex.h> is broken on some linux distributions.
  103. const int FUTEX_WAIT = 0;
  104. const int FUTEX_WAKE = 1;
  105. const int FUTEX_PRIVATE_FLAG = 128;
  106. const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
  107. const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
  108. #endif // SANITIZER_LINUX
  109. // Are we using 32-bit or 64-bit Linux syscalls?
  110. // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
  111. // but it still needs to use 64-bit syscalls.
  112. #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \
  113. SANITIZER_WORDSIZE == 64)
  114. # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
  115. #else
  116. # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
  117. #endif
  118. // Note : FreeBSD had implemented both
  119. // Linux apis, available from
  120. // future 12.x version most likely
  121. #if SANITIZER_LINUX && defined(__NR_getrandom)
  122. # if !defined(GRND_NONBLOCK)
  123. # define GRND_NONBLOCK 1
  124. # endif
  125. # define SANITIZER_USE_GETRANDOM 1
  126. #else
  127. # define SANITIZER_USE_GETRANDOM 0
  128. #endif // SANITIZER_LINUX && defined(__NR_getrandom)
  129. #if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
  130. # define SANITIZER_USE_GETENTROPY 1
  131. #else
  132. # define SANITIZER_USE_GETENTROPY 0
  133. #endif
  134. namespace __sanitizer {
  135. void SetSigProcMask(__sanitizer_sigset_t *set, __sanitizer_sigset_t *old) {
  136. CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, set, old));
  137. }
  138. ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t *copy) {
  139. __sanitizer_sigset_t set;
  140. internal_sigfillset(&set);
  141. # if SANITIZER_LINUX && !SANITIZER_ANDROID
  142. // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked
  143. // on any thread, setuid call hangs.
  144. // See test/sanitizer_common/TestCases/Linux/setuid.c.
  145. internal_sigdelset(&set, 33);
  146. # endif
  147. # if SANITIZER_LINUX
  148. // Seccomp-BPF-sandboxed processes rely on SIGSYS to handle trapped syscalls.
  149. // If this signal is blocked, such calls cannot be handled and the process may
  150. // hang.
  151. internal_sigdelset(&set, 31);
  152. # endif
  153. SetSigProcMask(&set, &saved_);
  154. if (copy)
  155. internal_memcpy(copy, &saved_, sizeof(saved_));
  156. }
  157. ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_, nullptr); }
  158. # if SANITIZER_LINUX && defined(__x86_64__)
  159. # include "sanitizer_syscall_linux_x86_64.inc"
  160. # elif SANITIZER_LINUX && SANITIZER_RISCV64
  161. # include "sanitizer_syscall_linux_riscv64.inc"
  162. # elif SANITIZER_LINUX && defined(__aarch64__)
  163. # include "sanitizer_syscall_linux_aarch64.inc"
  164. # elif SANITIZER_LINUX && defined(__arm__)
  165. # include "sanitizer_syscall_linux_arm.inc"
  166. # elif SANITIZER_LINUX && defined(__hexagon__)
  167. # include "sanitizer_syscall_linux_hexagon.inc"
  168. # else
  169. # include "sanitizer_syscall_generic.inc"
  170. # endif
  171. // --------------- sanitizer_libc.h
  172. #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
  173. #if !SANITIZER_S390
  174. uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
  175. u64 offset) {
  176. #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
  177. return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd,
  178. offset);
  179. #else
  180. // mmap2 specifies file offset in 4096-byte units.
  181. CHECK(IsAligned(offset, 4096));
  182. return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd,
  183. offset / 4096);
  184. #endif
  185. }
  186. #endif // !SANITIZER_S390
  187. uptr internal_munmap(void *addr, uptr length) {
  188. return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
  189. }
  190. #if SANITIZER_LINUX
  191. uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
  192. void *new_address) {
  193. return internal_syscall(SYSCALL(mremap), (uptr)old_address, old_size,
  194. new_size, flags, (uptr)new_address);
  195. }
  196. #endif
  197. int internal_mprotect(void *addr, uptr length, int prot) {
  198. return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
  199. }
  200. int internal_madvise(uptr addr, uptr length, int advice) {
  201. return internal_syscall(SYSCALL(madvise), addr, length, advice);
  202. }
  203. uptr internal_close(fd_t fd) {
  204. return internal_syscall(SYSCALL(close), fd);
  205. }
  206. uptr internal_open(const char *filename, int flags) {
  207. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  208. return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags);
  209. #else
  210. return internal_syscall(SYSCALL(open), (uptr)filename, flags);
  211. #endif
  212. }
  213. uptr internal_open(const char *filename, int flags, u32 mode) {
  214. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  215. return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags,
  216. mode);
  217. #else
  218. return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode);
  219. #endif
  220. }
  221. uptr internal_read(fd_t fd, void *buf, uptr count) {
  222. sptr res;
  223. HANDLE_EINTR(res,
  224. (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count));
  225. return res;
  226. }
  227. uptr internal_write(fd_t fd, const void *buf, uptr count) {
  228. sptr res;
  229. HANDLE_EINTR(res,
  230. (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count));
  231. return res;
  232. }
  233. uptr internal_ftruncate(fd_t fd, uptr size) {
  234. sptr res;
  235. HANDLE_EINTR(res, (sptr)internal_syscall(SYSCALL(ftruncate), fd,
  236. (OFF_T)size));
  237. return res;
  238. }
  239. #if !SANITIZER_LINUX_USES_64BIT_SYSCALLS && SANITIZER_LINUX
  240. static void stat64_to_stat(struct stat64 *in, struct stat *out) {
  241. internal_memset(out, 0, sizeof(*out));
  242. out->st_dev = in->st_dev;
  243. out->st_ino = in->st_ino;
  244. out->st_mode = in->st_mode;
  245. out->st_nlink = in->st_nlink;
  246. out->st_uid = in->st_uid;
  247. out->st_gid = in->st_gid;
  248. out->st_rdev = in->st_rdev;
  249. out->st_size = in->st_size;
  250. out->st_blksize = in->st_blksize;
  251. out->st_blocks = in->st_blocks;
  252. out->st_atime = in->st_atime;
  253. out->st_mtime = in->st_mtime;
  254. out->st_ctime = in->st_ctime;
  255. }
  256. #endif
  257. #if defined(__mips64)
  258. // Undefine compatibility macros from <sys/stat.h>
  259. // so that they would not clash with the kernel_stat
  260. // st_[a|m|c]time fields
  261. #if !SANITIZER_GO
  262. #undef st_atime
  263. #undef st_mtime
  264. #undef st_ctime
  265. #endif
  266. #if defined(SANITIZER_ANDROID)
  267. // Bionic sys/stat.h defines additional macros
  268. // for compatibility with the old NDKs and
  269. // they clash with the kernel_stat structure
  270. // st_[a|m|c]time_nsec fields.
  271. #undef st_atime_nsec
  272. #undef st_mtime_nsec
  273. #undef st_ctime_nsec
  274. #endif
  275. static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
  276. internal_memset(out, 0, sizeof(*out));
  277. out->st_dev = in->st_dev;
  278. out->st_ino = in->st_ino;
  279. out->st_mode = in->st_mode;
  280. out->st_nlink = in->st_nlink;
  281. out->st_uid = in->st_uid;
  282. out->st_gid = in->st_gid;
  283. out->st_rdev = in->st_rdev;
  284. out->st_size = in->st_size;
  285. out->st_blksize = in->st_blksize;
  286. out->st_blocks = in->st_blocks;
  287. #if defined(__USE_MISC) || \
  288. defined(__USE_XOPEN2K8) || \
  289. defined(SANITIZER_ANDROID)
  290. out->st_atim.tv_sec = in->st_atime;
  291. out->st_atim.tv_nsec = in->st_atime_nsec;
  292. out->st_mtim.tv_sec = in->st_mtime;
  293. out->st_mtim.tv_nsec = in->st_mtime_nsec;
  294. out->st_ctim.tv_sec = in->st_ctime;
  295. out->st_ctim.tv_nsec = in->st_ctime_nsec;
  296. #else
  297. out->st_atime = in->st_atime;
  298. out->st_atimensec = in->st_atime_nsec;
  299. out->st_mtime = in->st_mtime;
  300. out->st_mtimensec = in->st_mtime_nsec;
  301. out->st_ctime = in->st_ctime;
  302. out->st_atimensec = in->st_ctime_nsec;
  303. #endif
  304. }
  305. #endif
  306. uptr internal_stat(const char *path, void *buf) {
  307. #if SANITIZER_FREEBSD
  308. return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0);
  309. #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  310. return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
  311. 0);
  312. #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
  313. # if defined(__mips64)
  314. // For mips64, stat syscall fills buffer in the format of kernel_stat
  315. struct kernel_stat kbuf;
  316. int res = internal_syscall(SYSCALL(stat), path, &kbuf);
  317. kernel_stat_to_stat(&kbuf, (struct stat *)buf);
  318. return res;
  319. # else
  320. return internal_syscall(SYSCALL(stat), (uptr)path, (uptr)buf);
  321. # endif
  322. #else
  323. struct stat64 buf64;
  324. int res = internal_syscall(SYSCALL(stat64), path, &buf64);
  325. stat64_to_stat(&buf64, (struct stat *)buf);
  326. return res;
  327. #endif
  328. }
  329. uptr internal_lstat(const char *path, void *buf) {
  330. #if SANITIZER_FREEBSD
  331. return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
  332. AT_SYMLINK_NOFOLLOW);
  333. #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  334. return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
  335. AT_SYMLINK_NOFOLLOW);
  336. #elif SANITIZER_LINUX_USES_64BIT_SYSCALLS
  337. # if SANITIZER_MIPS64
  338. // For mips64, lstat syscall fills buffer in the format of kernel_stat
  339. struct kernel_stat kbuf;
  340. int res = internal_syscall(SYSCALL(lstat), path, &kbuf);
  341. kernel_stat_to_stat(&kbuf, (struct stat *)buf);
  342. return res;
  343. # else
  344. return internal_syscall(SYSCALL(lstat), (uptr)path, (uptr)buf);
  345. # endif
  346. #else
  347. struct stat64 buf64;
  348. int res = internal_syscall(SYSCALL(lstat64), path, &buf64);
  349. stat64_to_stat(&buf64, (struct stat *)buf);
  350. return res;
  351. #endif
  352. }
  353. uptr internal_fstat(fd_t fd, void *buf) {
  354. #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
  355. #if SANITIZER_MIPS64
  356. // For mips64, fstat syscall fills buffer in the format of kernel_stat
  357. struct kernel_stat kbuf;
  358. int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
  359. kernel_stat_to_stat(&kbuf, (struct stat *)buf);
  360. return res;
  361. # else
  362. return internal_syscall(SYSCALL(fstat), fd, (uptr)buf);
  363. # endif
  364. #else
  365. struct stat64 buf64;
  366. int res = internal_syscall(SYSCALL(fstat64), fd, &buf64);
  367. stat64_to_stat(&buf64, (struct stat *)buf);
  368. return res;
  369. #endif
  370. }
  371. uptr internal_filesize(fd_t fd) {
  372. struct stat st;
  373. if (internal_fstat(fd, &st))
  374. return -1;
  375. return (uptr)st.st_size;
  376. }
  377. uptr internal_dup(int oldfd) {
  378. return internal_syscall(SYSCALL(dup), oldfd);
  379. }
  380. uptr internal_dup2(int oldfd, int newfd) {
  381. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  382. return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0);
  383. #else
  384. return internal_syscall(SYSCALL(dup2), oldfd, newfd);
  385. #endif
  386. }
  387. uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
  388. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  389. return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
  390. bufsize);
  391. #else
  392. return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
  393. #endif
  394. }
  395. uptr internal_unlink(const char *path) {
  396. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  397. return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
  398. #else
  399. return internal_syscall(SYSCALL(unlink), (uptr)path);
  400. #endif
  401. }
  402. uptr internal_rename(const char *oldpath, const char *newpath) {
  403. #if defined(__riscv) && defined(__linux__)
  404. return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
  405. (uptr)newpath, 0);
  406. #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  407. return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
  408. (uptr)newpath);
  409. #else
  410. return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath);
  411. #endif
  412. }
  413. uptr internal_sched_yield() {
  414. return internal_syscall(SYSCALL(sched_yield));
  415. }
  416. void internal_usleep(u64 useconds) {
  417. struct timespec ts;
  418. ts.tv_sec = useconds / 1000000;
  419. ts.tv_nsec = (useconds % 1000000) * 1000;
  420. internal_syscall(SYSCALL(nanosleep), &ts, &ts);
  421. }
  422. uptr internal_execve(const char *filename, char *const argv[],
  423. char *const envp[]) {
  424. return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv,
  425. (uptr)envp);
  426. }
  427. #endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
  428. #if !SANITIZER_NETBSD
  429. void internal__exit(int exitcode) {
  430. #if SANITIZER_FREEBSD || SANITIZER_SOLARIS
  431. internal_syscall(SYSCALL(exit), exitcode);
  432. #else
  433. internal_syscall(SYSCALL(exit_group), exitcode);
  434. #endif
  435. Die(); // Unreachable.
  436. }
  437. #endif // !SANITIZER_NETBSD
  438. // ----------------- sanitizer_common.h
  439. bool FileExists(const char *filename) {
  440. if (ShouldMockFailureToOpen(filename))
  441. return false;
  442. struct stat st;
  443. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  444. if (internal_syscall(SYSCALL(newfstatat), AT_FDCWD, filename, &st, 0))
  445. #else
  446. if (internal_stat(filename, &st))
  447. #endif
  448. return false;
  449. // Sanity check: filename is a regular file.
  450. return S_ISREG(st.st_mode);
  451. }
  452. #if !SANITIZER_NETBSD
  453. tid_t GetTid() {
  454. #if SANITIZER_FREEBSD
  455. long Tid;
  456. thr_self(&Tid);
  457. return Tid;
  458. #elif SANITIZER_SOLARIS
  459. return thr_self();
  460. #else
  461. return internal_syscall(SYSCALL(gettid));
  462. #endif
  463. }
  464. int TgKill(pid_t pid, tid_t tid, int sig) {
  465. #if SANITIZER_LINUX
  466. return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
  467. #elif SANITIZER_FREEBSD
  468. return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
  469. #elif SANITIZER_SOLARIS
  470. (void)pid;
  471. return thr_kill(tid, sig);
  472. #endif
  473. }
  474. #endif
  475. #if SANITIZER_GLIBC
  476. u64 NanoTime() {
  477. kernel_timeval tv;
  478. internal_memset(&tv, 0, sizeof(tv));
  479. internal_syscall(SYSCALL(gettimeofday), &tv, 0);
  480. return (u64)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000;
  481. }
  482. // Used by real_clock_gettime.
  483. uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
  484. return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
  485. }
  486. #elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD
  487. u64 NanoTime() {
  488. struct timespec ts;
  489. clock_gettime(CLOCK_REALTIME, &ts);
  490. return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
  491. }
  492. #endif
  493. // Like getenv, but reads env directly from /proc (on Linux) or parses the
  494. // 'environ' array (on some others) and does not use libc. This function
  495. // should be called first inside __asan_init.
  496. const char *GetEnv(const char *name) {
  497. #if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS
  498. if (::environ != 0) {
  499. uptr NameLen = internal_strlen(name);
  500. for (char **Env = ::environ; *Env != 0; Env++) {
  501. if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
  502. return (*Env) + NameLen + 1;
  503. }
  504. }
  505. return 0; // Not found.
  506. #elif SANITIZER_LINUX
  507. static char *environ;
  508. static uptr len;
  509. static bool inited;
  510. if (!inited) {
  511. inited = true;
  512. uptr environ_size;
  513. if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len))
  514. environ = nullptr;
  515. }
  516. if (!environ || len == 0) return nullptr;
  517. uptr namelen = internal_strlen(name);
  518. const char *p = environ;
  519. while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
  520. // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
  521. const char* endp =
  522. (char*)internal_memchr(p, '\0', len - (p - environ));
  523. if (!endp) // this entry isn't NUL terminated
  524. return nullptr;
  525. else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
  526. return p + namelen + 1; // point after =
  527. p = endp + 1;
  528. }
  529. return nullptr; // Not found.
  530. #else
  531. #error "Unsupported platform"
  532. #endif
  533. }
  534. #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO
  535. extern "C" {
  536. SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
  537. }
  538. #endif
  539. #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
  540. static void ReadNullSepFileToArray(const char *path, char ***arr,
  541. int arr_size) {
  542. char *buff;
  543. uptr buff_size;
  544. uptr buff_len;
  545. *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
  546. if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) {
  547. (*arr)[0] = nullptr;
  548. return;
  549. }
  550. (*arr)[0] = buff;
  551. int count, i;
  552. for (count = 1, i = 1; ; i++) {
  553. if (buff[i] == 0) {
  554. if (buff[i+1] == 0) break;
  555. (*arr)[count] = &buff[i+1];
  556. CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
  557. count++;
  558. }
  559. }
  560. (*arr)[count] = nullptr;
  561. }
  562. #endif
  563. static void GetArgsAndEnv(char ***argv, char ***envp) {
  564. #if SANITIZER_FREEBSD
  565. // On FreeBSD, retrieving the argument and environment arrays is done via the
  566. // kern.ps_strings sysctl, which returns a pointer to a structure containing
  567. // this information. See also <sys/exec.h>.
  568. ps_strings *pss;
  569. uptr sz = sizeof(pss);
  570. if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) {
  571. Printf("sysctl kern.ps_strings failed\n");
  572. Die();
  573. }
  574. *argv = pss->ps_argvstr;
  575. *envp = pss->ps_envstr;
  576. #elif SANITIZER_NETBSD
  577. *argv = __ps_strings->ps_argvstr;
  578. *envp = __ps_strings->ps_envstr;
  579. #else // SANITIZER_FREEBSD
  580. #if !SANITIZER_GO
  581. if (&__libc_stack_end) {
  582. uptr* stack_end = (uptr*)__libc_stack_end;
  583. // Normally argc can be obtained from *stack_end, however, on ARM glibc's
  584. // _start clobbers it:
  585. // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75
  586. // Do not special-case ARM and infer argc from argv everywhere.
  587. int argc = 0;
  588. while (stack_end[argc + 1]) argc++;
  589. *argv = (char**)(stack_end + 1);
  590. *envp = (char**)(stack_end + argc + 2);
  591. } else {
  592. #endif // !SANITIZER_GO
  593. static const int kMaxArgv = 2000, kMaxEnvp = 2000;
  594. ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
  595. ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
  596. #if !SANITIZER_GO
  597. }
  598. #endif // !SANITIZER_GO
  599. #endif // SANITIZER_FREEBSD
  600. }
  601. char **GetArgv() {
  602. char **argv, **envp;
  603. GetArgsAndEnv(&argv, &envp);
  604. return argv;
  605. }
  606. char **GetEnviron() {
  607. char **argv, **envp;
  608. GetArgsAndEnv(&argv, &envp);
  609. return envp;
  610. }
  611. #if !SANITIZER_SOLARIS
  612. void FutexWait(atomic_uint32_t *p, u32 cmp) {
  613. # if SANITIZER_FREEBSD
  614. _umtx_op(p, UMTX_OP_WAIT_UINT, cmp, 0, 0);
  615. # elif SANITIZER_NETBSD
  616. sched_yield(); /* No userspace futex-like synchronization */
  617. # else
  618. internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0);
  619. # endif
  620. }
  621. void FutexWake(atomic_uint32_t *p, u32 count) {
  622. # if SANITIZER_FREEBSD
  623. _umtx_op(p, UMTX_OP_WAKE, count, 0, 0);
  624. # elif SANITIZER_NETBSD
  625. /* No userspace futex-like synchronization */
  626. # else
  627. internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0);
  628. # endif
  629. }
  630. # endif // !SANITIZER_SOLARIS
  631. // ----------------- sanitizer_linux.h
  632. // The actual size of this structure is specified by d_reclen.
  633. // Note that getdents64 uses a different structure format. We only provide the
  634. // 32-bit syscall here.
  635. #if SANITIZER_NETBSD
  636. // Not used
  637. #else
  638. struct linux_dirent {
  639. #if SANITIZER_X32 || defined(__aarch64__) || SANITIZER_RISCV64
  640. u64 d_ino;
  641. u64 d_off;
  642. #else
  643. unsigned long d_ino;
  644. unsigned long d_off;
  645. #endif
  646. unsigned short d_reclen;
  647. #if defined(__aarch64__) || SANITIZER_RISCV64
  648. unsigned char d_type;
  649. #endif
  650. char d_name[256];
  651. };
  652. #endif
  653. #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
  654. // Syscall wrappers.
  655. uptr internal_ptrace(int request, int pid, void *addr, void *data) {
  656. return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr,
  657. (uptr)data);
  658. }
  659. uptr internal_waitpid(int pid, int *status, int options) {
  660. return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options,
  661. 0 /* rusage */);
  662. }
  663. uptr internal_getpid() {
  664. return internal_syscall(SYSCALL(getpid));
  665. }
  666. uptr internal_getppid() {
  667. return internal_syscall(SYSCALL(getppid));
  668. }
  669. int internal_dlinfo(void *handle, int request, void *p) {
  670. #if SANITIZER_FREEBSD
  671. return dlinfo(handle, request, p);
  672. #else
  673. UNIMPLEMENTED();
  674. #endif
  675. }
  676. uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
  677. #if SANITIZER_FREEBSD
  678. return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL);
  679. #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  680. return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count);
  681. #else
  682. return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count);
  683. #endif
  684. }
  685. uptr internal_lseek(fd_t fd, OFF_T offset, int whence) {
  686. return internal_syscall(SYSCALL(lseek), fd, offset, whence);
  687. }
  688. #if SANITIZER_LINUX
  689. uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
  690. return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5);
  691. }
  692. #endif
  693. uptr internal_sigaltstack(const void *ss, void *oss) {
  694. return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
  695. }
  696. int internal_fork() {
  697. #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
  698. return internal_syscall(SYSCALL(clone), SIGCHLD, 0);
  699. #else
  700. return internal_syscall(SYSCALL(fork));
  701. #endif
  702. }
  703. #if SANITIZER_FREEBSD
  704. int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
  705. uptr *oldlenp, const void *newp, uptr newlen) {
  706. return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
  707. (size_t *)oldlenp, newp, (size_t)newlen);
  708. }
  709. int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
  710. const void *newp, uptr newlen) {
  711. // Note: this function can be called during startup, so we need to avoid
  712. // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
  713. // is a real syscall, but for older versions it calls sysctlnametomib()
  714. // followed by sysctl(). To avoid calling the intercepted version and
  715. // asserting if this happens during startup, call the real sysctlnametomib()
  716. // followed by internal_sysctl() if the syscall is not available.
  717. #ifdef SYS___sysctlbyname
  718. return internal_syscall(SYSCALL(__sysctlbyname), sname,
  719. internal_strlen(sname), oldp, (size_t *)oldlenp, newp,
  720. (size_t)newlen);
  721. #else
  722. static decltype(sysctlnametomib) *real_sysctlnametomib = nullptr;
  723. if (!real_sysctlnametomib)
  724. real_sysctlnametomib =
  725. (decltype(sysctlnametomib) *)dlsym(RTLD_NEXT, "sysctlnametomib");
  726. CHECK(real_sysctlnametomib);
  727. int oid[CTL_MAXNAME];
  728. size_t len = CTL_MAXNAME;
  729. if (real_sysctlnametomib(sname, oid, &len) == -1)
  730. return (-1);
  731. return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen);
  732. #endif
  733. }
  734. #endif
  735. #if SANITIZER_LINUX
  736. #define SA_RESTORER 0x04000000
  737. // Doesn't set sa_restorer if the caller did not set it, so use with caution
  738. //(see below).
  739. int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
  740. __sanitizer_kernel_sigaction_t k_act, k_oldact;
  741. internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t));
  742. internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t));
  743. const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act;
  744. __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact;
  745. if (u_act) {
  746. k_act.handler = u_act->handler;
  747. k_act.sigaction = u_act->sigaction;
  748. internal_memcpy(&k_act.sa_mask, &u_act->sa_mask,
  749. sizeof(__sanitizer_kernel_sigset_t));
  750. // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL).
  751. k_act.sa_flags = u_act->sa_flags | SA_RESTORER;
  752. // FIXME: most often sa_restorer is unset, however the kernel requires it
  753. // to point to a valid signal restorer that calls the rt_sigreturn syscall.
  754. // If sa_restorer passed to the kernel is NULL, the program may crash upon
  755. // signal delivery or fail to unwind the stack in the signal handler.
  756. // libc implementation of sigaction() passes its own restorer to
  757. // rt_sigaction, so we need to do the same (we'll need to reimplement the
  758. // restorers; for x86_64 the restorer address can be obtained from
  759. // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact).
  760. #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
  761. k_act.sa_restorer = u_act->sa_restorer;
  762. #endif
  763. }
  764. uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum,
  765. (uptr)(u_act ? &k_act : nullptr),
  766. (uptr)(u_oldact ? &k_oldact : nullptr),
  767. (uptr)sizeof(__sanitizer_kernel_sigset_t));
  768. if ((result == 0) && u_oldact) {
  769. u_oldact->handler = k_oldact.handler;
  770. u_oldact->sigaction = k_oldact.sigaction;
  771. internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask,
  772. sizeof(__sanitizer_kernel_sigset_t));
  773. u_oldact->sa_flags = k_oldact.sa_flags;
  774. #if !SANITIZER_ANDROID || !SANITIZER_MIPS32
  775. u_oldact->sa_restorer = k_oldact.sa_restorer;
  776. #endif
  777. }
  778. return result;
  779. }
  780. #endif // SANITIZER_LINUX
  781. uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
  782. __sanitizer_sigset_t *oldset) {
  783. #if SANITIZER_FREEBSD
  784. return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
  785. #else
  786. __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
  787. __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset;
  788. return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how, (uptr)k_set,
  789. (uptr)k_oldset, sizeof(__sanitizer_kernel_sigset_t));
  790. #endif
  791. }
  792. void internal_sigfillset(__sanitizer_sigset_t *set) {
  793. internal_memset(set, 0xff, sizeof(*set));
  794. }
  795. void internal_sigemptyset(__sanitizer_sigset_t *set) {
  796. internal_memset(set, 0, sizeof(*set));
  797. }
  798. #if SANITIZER_LINUX
  799. void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
  800. signum -= 1;
  801. CHECK_GE(signum, 0);
  802. CHECK_LT(signum, sizeof(*set) * 8);
  803. __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
  804. const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
  805. const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
  806. k_set->sig[idx] &= ~((uptr)1 << bit);
  807. }
  808. bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
  809. signum -= 1;
  810. CHECK_GE(signum, 0);
  811. CHECK_LT(signum, sizeof(*set) * 8);
  812. __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
  813. const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
  814. const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
  815. return k_set->sig[idx] & ((uptr)1 << bit);
  816. }
  817. #elif SANITIZER_FREEBSD
  818. void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
  819. sigset_t *rset = reinterpret_cast<sigset_t *>(set);
  820. sigdelset(rset, signum);
  821. }
  822. bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
  823. sigset_t *rset = reinterpret_cast<sigset_t *>(set);
  824. return sigismember(rset, signum);
  825. }
  826. #endif
  827. #endif // !SANITIZER_SOLARIS
  828. #if !SANITIZER_NETBSD
  829. // ThreadLister implementation.
  830. ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) {
  831. char task_directory_path[80];
  832. internal_snprintf(task_directory_path, sizeof(task_directory_path),
  833. "/proc/%d/task/", pid);
  834. descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
  835. if (internal_iserror(descriptor_)) {
  836. Report("Can't open /proc/%d/task for reading.\n", pid);
  837. }
  838. }
  839. ThreadLister::Result ThreadLister::ListThreads(
  840. InternalMmapVector<tid_t> *threads) {
  841. if (internal_iserror(descriptor_))
  842. return Error;
  843. internal_lseek(descriptor_, 0, SEEK_SET);
  844. threads->clear();
  845. Result result = Ok;
  846. for (bool first_read = true;; first_read = false) {
  847. // Resize to max capacity if it was downsized by IsAlive.
  848. buffer_.resize(buffer_.capacity());
  849. CHECK_GE(buffer_.size(), 4096);
  850. uptr read = internal_getdents(
  851. descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size());
  852. if (!read)
  853. return result;
  854. if (internal_iserror(read)) {
  855. Report("Can't read directory entries from /proc/%d/task.\n", pid_);
  856. return Error;
  857. }
  858. for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) {
  859. struct linux_dirent *entry = (struct linux_dirent *)begin;
  860. begin += entry->d_reclen;
  861. if (entry->d_ino == 1) {
  862. // Inode 1 is for bad blocks and also can be a reason for early return.
  863. // Should be emitted if kernel tried to output terminating thread.
  864. // See proc_task_readdir implementation in Linux.
  865. result = Incomplete;
  866. }
  867. if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9')
  868. threads->push_back(internal_atoll(entry->d_name));
  869. }
  870. // Now we are going to detect short-read or early EOF. In such cases Linux
  871. // can return inconsistent list with missing alive threads.
  872. // Code will just remember that the list can be incomplete but it will
  873. // continue reads to return as much as possible.
  874. if (!first_read) {
  875. // The first one was a short-read by definition.
  876. result = Incomplete;
  877. } else if (read > buffer_.size() - 1024) {
  878. // Read was close to the buffer size. So double the size and assume the
  879. // worst.
  880. buffer_.resize(buffer_.size() * 2);
  881. result = Incomplete;
  882. } else if (!threads->empty() && !IsAlive(threads->back())) {
  883. // Maybe Linux early returned from read on terminated thread (!pid_alive)
  884. // and failed to restore read position.
  885. // See next_tid and proc_task_instantiate in Linux.
  886. result = Incomplete;
  887. }
  888. }
  889. }
  890. bool ThreadLister::IsAlive(int tid) {
  891. // /proc/%d/task/%d/status uses same call to detect alive threads as
  892. // proc_task_readdir. See task_state implementation in Linux.
  893. char path[80];
  894. internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid);
  895. if (!ReadFileToVector(path, &buffer_) || buffer_.empty())
  896. return false;
  897. buffer_.push_back(0);
  898. static const char kPrefix[] = "\nPPid:";
  899. const char *field = internal_strstr(buffer_.data(), kPrefix);
  900. if (!field)
  901. return false;
  902. field += internal_strlen(kPrefix);
  903. return (int)internal_atoll(field) != 0;
  904. }
  905. ThreadLister::~ThreadLister() {
  906. if (!internal_iserror(descriptor_))
  907. internal_close(descriptor_);
  908. }
  909. #endif
  910. #if SANITIZER_WORDSIZE == 32
  911. // Take care of unusable kernel area in top gigabyte.
  912. static uptr GetKernelAreaSize() {
  913. #if SANITIZER_LINUX && !SANITIZER_X32
  914. const uptr gbyte = 1UL << 30;
  915. // Firstly check if there are writable segments
  916. // mapped to top gigabyte (e.g. stack).
  917. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  918. if (proc_maps.Error())
  919. return 0;
  920. MemoryMappedSegment segment;
  921. while (proc_maps.Next(&segment)) {
  922. if ((segment.end >= 3 * gbyte) && segment.IsWritable()) return 0;
  923. }
  924. #if !SANITIZER_ANDROID
  925. // Even if nothing is mapped, top Gb may still be accessible
  926. // if we are running on 64-bit kernel.
  927. // Uname may report misleading results if personality type
  928. // is modified (e.g. under schroot) so check this as well.
  929. struct utsname uname_info;
  930. int pers = personality(0xffffffffUL);
  931. if (!(pers & PER_MASK) && internal_uname(&uname_info) == 0 &&
  932. internal_strstr(uname_info.machine, "64"))
  933. return 0;
  934. #endif // SANITIZER_ANDROID
  935. // Top gigabyte is reserved for kernel.
  936. return gbyte;
  937. #else
  938. return 0;
  939. #endif // SANITIZER_LINUX && !SANITIZER_X32
  940. }
  941. #endif // SANITIZER_WORDSIZE == 32
  942. uptr GetMaxVirtualAddress() {
  943. #if SANITIZER_NETBSD && defined(__x86_64__)
  944. return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE)
  945. #elif SANITIZER_WORDSIZE == 64
  946. # if defined(__powerpc64__) || defined(__aarch64__)
  947. // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
  948. // We somehow need to figure out which one we are using now and choose
  949. // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
  950. // Note that with 'ulimit -s unlimited' the stack is moved away from the top
  951. // of the address space, so simply checking the stack address is not enough.
  952. // This should (does) work for both PowerPC64 Endian modes.
  953. // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
  954. return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
  955. #elif SANITIZER_RISCV64
  956. return (1ULL << 38) - 1;
  957. # elif defined(__mips64)
  958. return (1ULL << 40) - 1; // 0x000000ffffffffffUL;
  959. # elif defined(__s390x__)
  960. return (1ULL << 53) - 1; // 0x001fffffffffffffUL;
  961. #elif defined(__sparc__)
  962. return ~(uptr)0;
  963. # else
  964. return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
  965. # endif
  966. #else // SANITIZER_WORDSIZE == 32
  967. # if defined(__s390__)
  968. return (1ULL << 31) - 1; // 0x7fffffff;
  969. # else
  970. return (1ULL << 32) - 1; // 0xffffffff;
  971. # endif
  972. #endif // SANITIZER_WORDSIZE
  973. }
  974. uptr GetMaxUserVirtualAddress() {
  975. uptr addr = GetMaxVirtualAddress();
  976. #if SANITIZER_WORDSIZE == 32 && !defined(__s390__)
  977. if (!common_flags()->full_address_space)
  978. addr -= GetKernelAreaSize();
  979. CHECK_LT(reinterpret_cast<uptr>(&addr), addr);
  980. #endif
  981. return addr;
  982. }
  983. #if !SANITIZER_ANDROID
  984. uptr GetPageSize() {
  985. #if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \
  986. defined(EXEC_PAGESIZE)
  987. return EXEC_PAGESIZE;
  988. #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
  989. // Use sysctl as sysconf can trigger interceptors internally.
  990. int pz = 0;
  991. uptr pzl = sizeof(pz);
  992. int mib[2] = {CTL_HW, HW_PAGESIZE};
  993. int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0);
  994. CHECK_EQ(rv, 0);
  995. return (uptr)pz;
  996. #elif SANITIZER_USE_GETAUXVAL
  997. return getauxval(AT_PAGESZ);
  998. #else
  999. return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy.
  1000. #endif
  1001. }
  1002. #endif // !SANITIZER_ANDROID
  1003. uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
  1004. #if SANITIZER_SOLARIS
  1005. const char *default_module_name = getexecname();
  1006. CHECK_NE(default_module_name, NULL);
  1007. return internal_snprintf(buf, buf_len, "%s", default_module_name);
  1008. #else
  1009. #if SANITIZER_FREEBSD || SANITIZER_NETBSD
  1010. #if SANITIZER_FREEBSD
  1011. const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  1012. #else
  1013. const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
  1014. #endif
  1015. const char *default_module_name = "kern.proc.pathname";
  1016. uptr Size = buf_len;
  1017. bool IsErr =
  1018. (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0);
  1019. int readlink_error = IsErr ? errno : 0;
  1020. uptr module_name_len = Size;
  1021. #else
  1022. const char *default_module_name = "/proc/self/exe";
  1023. uptr module_name_len = internal_readlink(
  1024. default_module_name, buf, buf_len);
  1025. int readlink_error;
  1026. bool IsErr = internal_iserror(module_name_len, &readlink_error);
  1027. #endif // SANITIZER_SOLARIS
  1028. if (IsErr) {
  1029. // We can't read binary name for some reason, assume it's unknown.
  1030. Report("WARNING: reading executable name failed with errno %d, "
  1031. "some stack frames may not be symbolized\n", readlink_error);
  1032. module_name_len = internal_snprintf(buf, buf_len, "%s",
  1033. default_module_name);
  1034. CHECK_LT(module_name_len, buf_len);
  1035. }
  1036. return module_name_len;
  1037. #endif
  1038. }
  1039. uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
  1040. #if SANITIZER_LINUX
  1041. char *tmpbuf;
  1042. uptr tmpsize;
  1043. uptr tmplen;
  1044. if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen,
  1045. 1024 * 1024)) {
  1046. internal_strncpy(buf, tmpbuf, buf_len);
  1047. UnmapOrDie(tmpbuf, tmpsize);
  1048. return internal_strlen(buf);
  1049. }
  1050. #endif
  1051. return ReadBinaryName(buf, buf_len);
  1052. }
  1053. // Match full names of the form /path/to/base_name{-,.}*
  1054. bool LibraryNameIs(const char *full_name, const char *base_name) {
  1055. const char *name = full_name;
  1056. // Strip path.
  1057. while (*name != '\0') name++;
  1058. while (name > full_name && *name != '/') name--;
  1059. if (*name == '/') name++;
  1060. uptr base_name_length = internal_strlen(base_name);
  1061. if (internal_strncmp(name, base_name, base_name_length)) return false;
  1062. return (name[base_name_length] == '-' || name[base_name_length] == '.');
  1063. }
  1064. #if !SANITIZER_ANDROID
  1065. // Call cb for each region mapped by map.
  1066. void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
  1067. CHECK_NE(map, nullptr);
  1068. #if !SANITIZER_FREEBSD
  1069. typedef ElfW(Phdr) Elf_Phdr;
  1070. typedef ElfW(Ehdr) Elf_Ehdr;
  1071. #endif // !SANITIZER_FREEBSD
  1072. char *base = (char *)map->l_addr;
  1073. Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
  1074. char *phdrs = base + ehdr->e_phoff;
  1075. char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize;
  1076. // Find the segment with the minimum base so we can "relocate" the p_vaddr
  1077. // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC
  1078. // objects have a non-zero base.
  1079. uptr preferred_base = (uptr)-1;
  1080. for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
  1081. Elf_Phdr *phdr = (Elf_Phdr *)iter;
  1082. if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr)
  1083. preferred_base = (uptr)phdr->p_vaddr;
  1084. }
  1085. // Compute the delta from the real base to get a relocation delta.
  1086. sptr delta = (uptr)base - preferred_base;
  1087. // Now we can figure out what the loader really mapped.
  1088. for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) {
  1089. Elf_Phdr *phdr = (Elf_Phdr *)iter;
  1090. if (phdr->p_type == PT_LOAD) {
  1091. uptr seg_start = phdr->p_vaddr + delta;
  1092. uptr seg_end = seg_start + phdr->p_memsz;
  1093. // None of these values are aligned. We consider the ragged edges of the
  1094. // load command as defined, since they are mapped from the file.
  1095. seg_start = RoundDownTo(seg_start, GetPageSizeCached());
  1096. seg_end = RoundUpTo(seg_end, GetPageSizeCached());
  1097. cb((void *)seg_start, seg_end - seg_start);
  1098. }
  1099. }
  1100. }
  1101. #endif
  1102. #if SANITIZER_LINUX
  1103. #if defined(__x86_64__)
  1104. // We cannot use glibc's clone wrapper, because it messes with the child
  1105. // task's TLS. It writes the PID and TID of the child task to its thread
  1106. // descriptor, but in our case the child task shares the thread descriptor with
  1107. // the parent (because we don't know how to allocate a new thread
  1108. // descriptor to keep glibc happy). So the stock version of clone(), when
  1109. // used with CLONE_VM, would end up corrupting the parent's thread descriptor.
  1110. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1111. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1112. long long res;
  1113. if (!fn || !child_stack)
  1114. return -EINVAL;
  1115. CHECK_EQ(0, (uptr)child_stack % 16);
  1116. child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
  1117. ((unsigned long long *)child_stack)[0] = (uptr)fn;
  1118. ((unsigned long long *)child_stack)[1] = (uptr)arg;
  1119. register void *r8 __asm__("r8") = newtls;
  1120. register int *r10 __asm__("r10") = child_tidptr;
  1121. __asm__ __volatile__(
  1122. /* %rax = syscall(%rax = SYSCALL(clone),
  1123. * %rdi = flags,
  1124. * %rsi = child_stack,
  1125. * %rdx = parent_tidptr,
  1126. * %r8 = new_tls,
  1127. * %r10 = child_tidptr)
  1128. */
  1129. "syscall\n"
  1130. /* if (%rax != 0)
  1131. * return;
  1132. */
  1133. "testq %%rax,%%rax\n"
  1134. "jnz 1f\n"
  1135. /* In the child. Terminate unwind chain. */
  1136. // XXX: We should also terminate the CFI unwind chain
  1137. // here. Unfortunately clang 3.2 doesn't support the
  1138. // necessary CFI directives, so we skip that part.
  1139. "xorq %%rbp,%%rbp\n"
  1140. /* Call "fn(arg)". */
  1141. "popq %%rax\n"
  1142. "popq %%rdi\n"
  1143. "call *%%rax\n"
  1144. /* Call _exit(%rax). */
  1145. "movq %%rax,%%rdi\n"
  1146. "movq %2,%%rax\n"
  1147. "syscall\n"
  1148. /* Return to parent. */
  1149. "1:\n"
  1150. : "=a" (res)
  1151. : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
  1152. "S"(child_stack),
  1153. "D"(flags),
  1154. "d"(parent_tidptr),
  1155. "r"(r8),
  1156. "r"(r10)
  1157. : "memory", "r11", "rcx");
  1158. return res;
  1159. }
  1160. #elif defined(__mips__)
  1161. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1162. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1163. long long res;
  1164. if (!fn || !child_stack)
  1165. return -EINVAL;
  1166. CHECK_EQ(0, (uptr)child_stack % 16);
  1167. child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
  1168. ((unsigned long long *)child_stack)[0] = (uptr)fn;
  1169. ((unsigned long long *)child_stack)[1] = (uptr)arg;
  1170. register void *a3 __asm__("$7") = newtls;
  1171. register int *a4 __asm__("$8") = child_tidptr;
  1172. // We don't have proper CFI directives here because it requires alot of code
  1173. // for very marginal benefits.
  1174. __asm__ __volatile__(
  1175. /* $v0 = syscall($v0 = __NR_clone,
  1176. * $a0 = flags,
  1177. * $a1 = child_stack,
  1178. * $a2 = parent_tidptr,
  1179. * $a3 = new_tls,
  1180. * $a4 = child_tidptr)
  1181. */
  1182. ".cprestore 16;\n"
  1183. "move $4,%1;\n"
  1184. "move $5,%2;\n"
  1185. "move $6,%3;\n"
  1186. "move $7,%4;\n"
  1187. /* Store the fifth argument on stack
  1188. * if we are using 32-bit abi.
  1189. */
  1190. #if SANITIZER_WORDSIZE == 32
  1191. "lw %5,16($29);\n"
  1192. #else
  1193. "move $8,%5;\n"
  1194. #endif
  1195. "li $2,%6;\n"
  1196. "syscall;\n"
  1197. /* if ($v0 != 0)
  1198. * return;
  1199. */
  1200. "bnez $2,1f;\n"
  1201. /* Call "fn(arg)". */
  1202. #if SANITIZER_WORDSIZE == 32
  1203. #ifdef __BIG_ENDIAN__
  1204. "lw $25,4($29);\n"
  1205. "lw $4,12($29);\n"
  1206. #else
  1207. "lw $25,0($29);\n"
  1208. "lw $4,8($29);\n"
  1209. #endif
  1210. #else
  1211. "ld $25,0($29);\n"
  1212. "ld $4,8($29);\n"
  1213. #endif
  1214. "jal $25;\n"
  1215. /* Call _exit($v0). */
  1216. "move $4,$2;\n"
  1217. "li $2,%7;\n"
  1218. "syscall;\n"
  1219. /* Return to parent. */
  1220. "1:\n"
  1221. : "=r" (res)
  1222. : "r"(flags),
  1223. "r"(child_stack),
  1224. "r"(parent_tidptr),
  1225. "r"(a3),
  1226. "r"(a4),
  1227. "i"(__NR_clone),
  1228. "i"(__NR_exit)
  1229. : "memory", "$29" );
  1230. return res;
  1231. }
  1232. #elif SANITIZER_RISCV64
  1233. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1234. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1235. if (!fn || !child_stack)
  1236. return -EINVAL;
  1237. CHECK_EQ(0, (uptr)child_stack % 16);
  1238. register int res __asm__("a0");
  1239. register int __flags __asm__("a0") = flags;
  1240. register void *__stack __asm__("a1") = child_stack;
  1241. register int *__ptid __asm__("a2") = parent_tidptr;
  1242. register void *__tls __asm__("a3") = newtls;
  1243. register int *__ctid __asm__("a4") = child_tidptr;
  1244. register int (*__fn)(void *) __asm__("a5") = fn;
  1245. register void *__arg __asm__("a6") = arg;
  1246. register int nr_clone __asm__("a7") = __NR_clone;
  1247. __asm__ __volatile__(
  1248. "ecall\n"
  1249. /* if (a0 != 0)
  1250. * return a0;
  1251. */
  1252. "bnez a0, 1f\n"
  1253. // In the child, now. Call "fn(arg)".
  1254. "mv a0, a6\n"
  1255. "jalr a5\n"
  1256. // Call _exit(a0).
  1257. "addi a7, zero, %9\n"
  1258. "ecall\n"
  1259. "1:\n"
  1260. : "=r"(res)
  1261. : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid),
  1262. "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit)
  1263. : "memory");
  1264. return res;
  1265. }
  1266. #elif defined(__aarch64__)
  1267. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1268. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1269. register long long res __asm__("x0");
  1270. if (!fn || !child_stack)
  1271. return -EINVAL;
  1272. CHECK_EQ(0, (uptr)child_stack % 16);
  1273. child_stack = (char *)child_stack - 2 * sizeof(unsigned long long);
  1274. ((unsigned long long *)child_stack)[0] = (uptr)fn;
  1275. ((unsigned long long *)child_stack)[1] = (uptr)arg;
  1276. register int (*__fn)(void *) __asm__("x0") = fn;
  1277. register void *__stack __asm__("x1") = child_stack;
  1278. register int __flags __asm__("x2") = flags;
  1279. register void *__arg __asm__("x3") = arg;
  1280. register int *__ptid __asm__("x4") = parent_tidptr;
  1281. register void *__tls __asm__("x5") = newtls;
  1282. register int *__ctid __asm__("x6") = child_tidptr;
  1283. __asm__ __volatile__(
  1284. "mov x0,x2\n" /* flags */
  1285. "mov x2,x4\n" /* ptid */
  1286. "mov x3,x5\n" /* tls */
  1287. "mov x4,x6\n" /* ctid */
  1288. "mov x8,%9\n" /* clone */
  1289. "svc 0x0\n"
  1290. /* if (%r0 != 0)
  1291. * return %r0;
  1292. */
  1293. "cmp x0, #0\n"
  1294. "bne 1f\n"
  1295. /* In the child, now. Call "fn(arg)". */
  1296. "ldp x1, x0, [sp], #16\n"
  1297. "blr x1\n"
  1298. /* Call _exit(%r0). */
  1299. "mov x8, %10\n"
  1300. "svc 0x0\n"
  1301. "1:\n"
  1302. : "=r" (res)
  1303. : "i"(-EINVAL),
  1304. "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg),
  1305. "r"(__ptid), "r"(__tls), "r"(__ctid),
  1306. "i"(__NR_clone), "i"(__NR_exit)
  1307. : "x30", "memory");
  1308. return res;
  1309. }
  1310. #elif defined(__powerpc64__)
  1311. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1312. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1313. long long res;
  1314. // Stack frame structure.
  1315. #if SANITIZER_PPC64V1
  1316. // Back chain == 0 (SP + 112)
  1317. // Frame (112 bytes):
  1318. // Parameter save area (SP + 48), 8 doublewords
  1319. // TOC save area (SP + 40)
  1320. // Link editor doubleword (SP + 32)
  1321. // Compiler doubleword (SP + 24)
  1322. // LR save area (SP + 16)
  1323. // CR save area (SP + 8)
  1324. // Back chain (SP + 0)
  1325. # define FRAME_SIZE 112
  1326. # define FRAME_TOC_SAVE_OFFSET 40
  1327. #elif SANITIZER_PPC64V2
  1328. // Back chain == 0 (SP + 32)
  1329. // Frame (32 bytes):
  1330. // TOC save area (SP + 24)
  1331. // LR save area (SP + 16)
  1332. // CR save area (SP + 8)
  1333. // Back chain (SP + 0)
  1334. # define FRAME_SIZE 32
  1335. # define FRAME_TOC_SAVE_OFFSET 24
  1336. #else
  1337. # error "Unsupported PPC64 ABI"
  1338. #endif
  1339. if (!fn || !child_stack)
  1340. return -EINVAL;
  1341. CHECK_EQ(0, (uptr)child_stack % 16);
  1342. register int (*__fn)(void *) __asm__("r3") = fn;
  1343. register void *__cstack __asm__("r4") = child_stack;
  1344. register int __flags __asm__("r5") = flags;
  1345. register void *__arg __asm__("r6") = arg;
  1346. register int *__ptidptr __asm__("r7") = parent_tidptr;
  1347. register void *__newtls __asm__("r8") = newtls;
  1348. register int *__ctidptr __asm__("r9") = child_tidptr;
  1349. __asm__ __volatile__(
  1350. /* fn and arg are saved across the syscall */
  1351. "mr 28, %5\n\t"
  1352. "mr 27, %8\n\t"
  1353. /* syscall
  1354. r0 == __NR_clone
  1355. r3 == flags
  1356. r4 == child_stack
  1357. r5 == parent_tidptr
  1358. r6 == newtls
  1359. r7 == child_tidptr */
  1360. "mr 3, %7\n\t"
  1361. "mr 5, %9\n\t"
  1362. "mr 6, %10\n\t"
  1363. "mr 7, %11\n\t"
  1364. "li 0, %3\n\t"
  1365. "sc\n\t"
  1366. /* Test if syscall was successful */
  1367. "cmpdi cr1, 3, 0\n\t"
  1368. "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t"
  1369. "bne- cr1, 1f\n\t"
  1370. /* Set up stack frame */
  1371. "li 29, 0\n\t"
  1372. "stdu 29, -8(1)\n\t"
  1373. "stdu 1, -%12(1)\n\t"
  1374. /* Do the function call */
  1375. "std 2, %13(1)\n\t"
  1376. #if SANITIZER_PPC64V1
  1377. "ld 0, 0(28)\n\t"
  1378. "ld 2, 8(28)\n\t"
  1379. "mtctr 0\n\t"
  1380. #elif SANITIZER_PPC64V2
  1381. "mr 12, 28\n\t"
  1382. "mtctr 12\n\t"
  1383. #else
  1384. # error "Unsupported PPC64 ABI"
  1385. #endif
  1386. "mr 3, 27\n\t"
  1387. "bctrl\n\t"
  1388. "ld 2, %13(1)\n\t"
  1389. /* Call _exit(r3) */
  1390. "li 0, %4\n\t"
  1391. "sc\n\t"
  1392. /* Return to parent */
  1393. "1:\n\t"
  1394. "mr %0, 3\n\t"
  1395. : "=r" (res)
  1396. : "0" (-1),
  1397. "i" (EINVAL),
  1398. "i" (__NR_clone),
  1399. "i" (__NR_exit),
  1400. "r" (__fn),
  1401. "r" (__cstack),
  1402. "r" (__flags),
  1403. "r" (__arg),
  1404. "r" (__ptidptr),
  1405. "r" (__newtls),
  1406. "r" (__ctidptr),
  1407. "i" (FRAME_SIZE),
  1408. "i" (FRAME_TOC_SAVE_OFFSET)
  1409. : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29");
  1410. return res;
  1411. }
  1412. #elif defined(__i386__)
  1413. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1414. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1415. int res;
  1416. if (!fn || !child_stack)
  1417. return -EINVAL;
  1418. CHECK_EQ(0, (uptr)child_stack % 16);
  1419. child_stack = (char *)child_stack - 7 * sizeof(unsigned int);
  1420. ((unsigned int *)child_stack)[0] = (uptr)flags;
  1421. ((unsigned int *)child_stack)[1] = (uptr)0;
  1422. ((unsigned int *)child_stack)[2] = (uptr)fn;
  1423. ((unsigned int *)child_stack)[3] = (uptr)arg;
  1424. __asm__ __volatile__(
  1425. /* %eax = syscall(%eax = SYSCALL(clone),
  1426. * %ebx = flags,
  1427. * %ecx = child_stack,
  1428. * %edx = parent_tidptr,
  1429. * %esi = new_tls,
  1430. * %edi = child_tidptr)
  1431. */
  1432. /* Obtain flags */
  1433. "movl (%%ecx), %%ebx\n"
  1434. /* Do the system call */
  1435. "pushl %%ebx\n"
  1436. "pushl %%esi\n"
  1437. "pushl %%edi\n"
  1438. /* Remember the flag value. */
  1439. "movl %%ebx, (%%ecx)\n"
  1440. "int $0x80\n"
  1441. "popl %%edi\n"
  1442. "popl %%esi\n"
  1443. "popl %%ebx\n"
  1444. /* if (%eax != 0)
  1445. * return;
  1446. */
  1447. "test %%eax,%%eax\n"
  1448. "jnz 1f\n"
  1449. /* terminate the stack frame */
  1450. "xorl %%ebp,%%ebp\n"
  1451. /* Call FN. */
  1452. "call *%%ebx\n"
  1453. #ifdef PIC
  1454. "call here\n"
  1455. "here:\n"
  1456. "popl %%ebx\n"
  1457. "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n"
  1458. #endif
  1459. /* Call exit */
  1460. "movl %%eax, %%ebx\n"
  1461. "movl %2, %%eax\n"
  1462. "int $0x80\n"
  1463. "1:\n"
  1464. : "=a" (res)
  1465. : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)),
  1466. "c"(child_stack),
  1467. "d"(parent_tidptr),
  1468. "S"(newtls),
  1469. "D"(child_tidptr)
  1470. : "memory");
  1471. return res;
  1472. }
  1473. #elif defined(__arm__)
  1474. uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
  1475. int *parent_tidptr, void *newtls, int *child_tidptr) {
  1476. unsigned int res;
  1477. if (!fn || !child_stack)
  1478. return -EINVAL;
  1479. child_stack = (char *)child_stack - 2 * sizeof(unsigned int);
  1480. ((unsigned int *)child_stack)[0] = (uptr)fn;
  1481. ((unsigned int *)child_stack)[1] = (uptr)arg;
  1482. register int r0 __asm__("r0") = flags;
  1483. register void *r1 __asm__("r1") = child_stack;
  1484. register int *r2 __asm__("r2") = parent_tidptr;
  1485. register void *r3 __asm__("r3") = newtls;
  1486. register int *r4 __asm__("r4") = child_tidptr;
  1487. register int r7 __asm__("r7") = __NR_clone;
  1488. #if __ARM_ARCH > 4 || defined (__ARM_ARCH_4T__)
  1489. # define ARCH_HAS_BX
  1490. #endif
  1491. #if __ARM_ARCH > 4
  1492. # define ARCH_HAS_BLX
  1493. #endif
  1494. #ifdef ARCH_HAS_BX
  1495. # ifdef ARCH_HAS_BLX
  1496. # define BLX(R) "blx " #R "\n"
  1497. # else
  1498. # define BLX(R) "mov lr, pc; bx " #R "\n"
  1499. # endif
  1500. #else
  1501. # define BLX(R) "mov lr, pc; mov pc," #R "\n"
  1502. #endif
  1503. __asm__ __volatile__(
  1504. /* %r0 = syscall(%r7 = SYSCALL(clone),
  1505. * %r0 = flags,
  1506. * %r1 = child_stack,
  1507. * %r2 = parent_tidptr,
  1508. * %r3 = new_tls,
  1509. * %r4 = child_tidptr)
  1510. */
  1511. /* Do the system call */
  1512. "swi 0x0\n"
  1513. /* if (%r0 != 0)
  1514. * return %r0;
  1515. */
  1516. "cmp r0, #0\n"
  1517. "bne 1f\n"
  1518. /* In the child, now. Call "fn(arg)". */
  1519. "ldr r0, [sp, #4]\n"
  1520. "ldr ip, [sp], #8\n"
  1521. BLX(ip)
  1522. /* Call _exit(%r0). */
  1523. "mov r7, %7\n"
  1524. "swi 0x0\n"
  1525. "1:\n"
  1526. "mov %0, r0\n"
  1527. : "=r"(res)
  1528. : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7),
  1529. "i"(__NR_exit)
  1530. : "memory");
  1531. return res;
  1532. }
  1533. #endif
  1534. #endif // SANITIZER_LINUX
  1535. #if SANITIZER_LINUX
  1536. int internal_uname(struct utsname *buf) {
  1537. return internal_syscall(SYSCALL(uname), buf);
  1538. }
  1539. #endif
  1540. #if SANITIZER_ANDROID
  1541. #if __ANDROID_API__ < 21
  1542. extern "C" __attribute__((weak)) int dl_iterate_phdr(
  1543. int (*)(struct dl_phdr_info *, size_t, void *), void *);
  1544. #endif
  1545. static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size,
  1546. void *data) {
  1547. // Any name starting with "lib" indicates a bug in L where library base names
  1548. // are returned instead of paths.
  1549. if (info->dlpi_name && info->dlpi_name[0] == 'l' &&
  1550. info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') {
  1551. *(bool *)data = true;
  1552. return 1;
  1553. }
  1554. return 0;
  1555. }
  1556. static atomic_uint32_t android_api_level;
  1557. static AndroidApiLevel AndroidDetectApiLevelStatic() {
  1558. #if __ANDROID_API__ <= 19
  1559. return ANDROID_KITKAT;
  1560. #elif __ANDROID_API__ <= 22
  1561. return ANDROID_LOLLIPOP_MR1;
  1562. #else
  1563. return ANDROID_POST_LOLLIPOP;
  1564. #endif
  1565. }
  1566. static AndroidApiLevel AndroidDetectApiLevel() {
  1567. if (!&dl_iterate_phdr)
  1568. return ANDROID_KITKAT; // K or lower
  1569. bool base_name_seen = false;
  1570. dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen);
  1571. if (base_name_seen)
  1572. return ANDROID_LOLLIPOP_MR1; // L MR1
  1573. return ANDROID_POST_LOLLIPOP; // post-L
  1574. // Plain L (API level 21) is completely broken wrt ASan and not very
  1575. // interesting to detect.
  1576. }
  1577. extern "C" __attribute__((weak)) void* _DYNAMIC;
  1578. AndroidApiLevel AndroidGetApiLevel() {
  1579. AndroidApiLevel level =
  1580. (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed);
  1581. if (level) return level;
  1582. level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic()
  1583. : AndroidDetectApiLevel();
  1584. atomic_store(&android_api_level, level, memory_order_relaxed);
  1585. return level;
  1586. }
  1587. #endif
  1588. static HandleSignalMode GetHandleSignalModeImpl(int signum) {
  1589. switch (signum) {
  1590. case SIGABRT:
  1591. return common_flags()->handle_abort;
  1592. case SIGILL:
  1593. return common_flags()->handle_sigill;
  1594. case SIGTRAP:
  1595. return common_flags()->handle_sigtrap;
  1596. case SIGFPE:
  1597. return common_flags()->handle_sigfpe;
  1598. case SIGSEGV:
  1599. return common_flags()->handle_segv;
  1600. case SIGBUS:
  1601. return common_flags()->handle_sigbus;
  1602. }
  1603. return kHandleSignalNo;
  1604. }
  1605. HandleSignalMode GetHandleSignalMode(int signum) {
  1606. HandleSignalMode result = GetHandleSignalModeImpl(signum);
  1607. if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler)
  1608. return kHandleSignalExclusive;
  1609. return result;
  1610. }
  1611. #if !SANITIZER_GO
  1612. void *internal_start_thread(void *(*func)(void *arg), void *arg) {
  1613. if (&real_pthread_create == 0)
  1614. return nullptr;
  1615. // Start the thread with signals blocked, otherwise it can steal user signals.
  1616. ScopedBlockSignals block(nullptr);
  1617. void *th;
  1618. real_pthread_create(&th, nullptr, func, arg);
  1619. return th;
  1620. }
  1621. void internal_join_thread(void *th) {
  1622. if (&real_pthread_join)
  1623. real_pthread_join(th, nullptr);
  1624. }
  1625. #else
  1626. void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; }
  1627. void internal_join_thread(void *th) {}
  1628. #endif
  1629. #if defined(__aarch64__)
  1630. // Android headers in the older NDK releases miss this definition.
  1631. struct __sanitizer_esr_context {
  1632. struct _aarch64_ctx head;
  1633. uint64_t esr;
  1634. };
  1635. static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
  1636. static const u32 kEsrMagic = 0x45535201;
  1637. u8 *aux = reinterpret_cast<u8 *>(ucontext->uc_mcontext.__reserved);
  1638. while (true) {
  1639. _aarch64_ctx *ctx = (_aarch64_ctx *)aux;
  1640. if (ctx->size == 0) break;
  1641. if (ctx->magic == kEsrMagic) {
  1642. *esr = ((__sanitizer_esr_context *)ctx)->esr;
  1643. return true;
  1644. }
  1645. aux += ctx->size;
  1646. }
  1647. return false;
  1648. }
  1649. #endif
  1650. using Context = ucontext_t;
  1651. SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
  1652. Context *ucontext = (Context *)context;
  1653. #if defined(__x86_64__) || defined(__i386__)
  1654. static const uptr PF_WRITE = 1U << 1;
  1655. #if SANITIZER_FREEBSD
  1656. uptr err = ucontext->uc_mcontext.mc_err;
  1657. #elif SANITIZER_NETBSD
  1658. uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
  1659. #elif SANITIZER_SOLARIS && defined(__i386__)
  1660. const int Err = 13;
  1661. uptr err = ucontext->uc_mcontext.gregs[Err];
  1662. #else
  1663. uptr err = ucontext->uc_mcontext.gregs[REG_ERR];
  1664. #endif // SANITIZER_FREEBSD
  1665. return err & PF_WRITE ? Write : Read;
  1666. #elif defined(__mips__)
  1667. uint32_t *exception_source;
  1668. uint32_t faulty_instruction;
  1669. uint32_t op_code;
  1670. exception_source = (uint32_t *)ucontext->uc_mcontext.pc;
  1671. faulty_instruction = (uint32_t)(*exception_source);
  1672. op_code = (faulty_instruction >> 26) & 0x3f;
  1673. // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions.
  1674. switch (op_code) {
  1675. case 0x28: // sb
  1676. case 0x29: // sh
  1677. case 0x2b: // sw
  1678. case 0x3f: // sd
  1679. #if __mips_isa_rev < 6
  1680. case 0x2c: // sdl
  1681. case 0x2d: // sdr
  1682. case 0x2a: // swl
  1683. case 0x2e: // swr
  1684. #endif
  1685. return SignalContext::Write;
  1686. case 0x20: // lb
  1687. case 0x24: // lbu
  1688. case 0x21: // lh
  1689. case 0x25: // lhu
  1690. case 0x23: // lw
  1691. case 0x27: // lwu
  1692. case 0x37: // ld
  1693. #if __mips_isa_rev < 6
  1694. case 0x1a: // ldl
  1695. case 0x1b: // ldr
  1696. case 0x22: // lwl
  1697. case 0x26: // lwr
  1698. #endif
  1699. return SignalContext::Read;
  1700. #if __mips_isa_rev == 6
  1701. case 0x3b: // pcrel
  1702. op_code = (faulty_instruction >> 19) & 0x3;
  1703. switch (op_code) {
  1704. case 0x1: // lwpc
  1705. case 0x2: // lwupc
  1706. return SignalContext::Read;
  1707. }
  1708. #endif
  1709. }
  1710. return SignalContext::Unknown;
  1711. #elif defined(__arm__)
  1712. static const uptr FSR_WRITE = 1U << 11;
  1713. uptr fsr = ucontext->uc_mcontext.error_code;
  1714. return fsr & FSR_WRITE ? Write : Read;
  1715. #elif defined(__aarch64__)
  1716. static const u64 ESR_ELx_WNR = 1U << 6;
  1717. u64 esr;
  1718. if (!Aarch64GetESR(ucontext, &esr)) return Unknown;
  1719. return esr & ESR_ELx_WNR ? Write : Read;
  1720. #elif defined(__sparc__)
  1721. // Decode the instruction to determine the access type.
  1722. // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype).
  1723. #if SANITIZER_SOLARIS
  1724. uptr pc = ucontext->uc_mcontext.gregs[REG_PC];
  1725. #else
  1726. // Historical BSDism here.
  1727. struct sigcontext *scontext = (struct sigcontext *)context;
  1728. #if defined(__arch64__)
  1729. uptr pc = scontext->sigc_regs.tpc;
  1730. #else
  1731. uptr pc = scontext->si_regs.pc;
  1732. #endif
  1733. #endif
  1734. u32 instr = *(u32 *)pc;
  1735. return (instr >> 21) & 1 ? Write: Read;
  1736. #elif defined(__riscv)
  1737. #if SANITIZER_FREEBSD
  1738. unsigned long pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
  1739. #else
  1740. unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC];
  1741. #endif
  1742. unsigned faulty_instruction = *(uint16_t *)pc;
  1743. #if defined(__riscv_compressed)
  1744. if ((faulty_instruction & 0x3) != 0x3) { // it's a compressed instruction
  1745. // set op_bits to the instruction bits [1, 0, 15, 14, 13]
  1746. unsigned op_bits =
  1747. ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13);
  1748. unsigned rd = faulty_instruction & 0xF80; // bits 7-11, inclusive
  1749. switch (op_bits) {
  1750. case 0b10'010: // c.lwsp (rd != x0)
  1751. #if __riscv_xlen == 64
  1752. case 0b10'011: // c.ldsp (rd != x0)
  1753. #endif
  1754. return rd ? SignalContext::Read : SignalContext::Unknown;
  1755. case 0b00'010: // c.lw
  1756. #if __riscv_flen >= 32 && __riscv_xlen == 32
  1757. case 0b10'011: // c.flwsp
  1758. #endif
  1759. #if __riscv_flen >= 32 || __riscv_xlen == 64
  1760. case 0b00'011: // c.flw / c.ld
  1761. #endif
  1762. #if __riscv_flen == 64
  1763. case 0b00'001: // c.fld
  1764. case 0b10'001: // c.fldsp
  1765. #endif
  1766. return SignalContext::Read;
  1767. case 0b00'110: // c.sw
  1768. case 0b10'110: // c.swsp
  1769. #if __riscv_flen >= 32 || __riscv_xlen == 64
  1770. case 0b00'111: // c.fsw / c.sd
  1771. case 0b10'111: // c.fswsp / c.sdsp
  1772. #endif
  1773. #if __riscv_flen == 64
  1774. case 0b00'101: // c.fsd
  1775. case 0b10'101: // c.fsdsp
  1776. #endif
  1777. return SignalContext::Write;
  1778. default:
  1779. return SignalContext::Unknown;
  1780. }
  1781. }
  1782. #endif
  1783. unsigned opcode = faulty_instruction & 0x7f; // lower 7 bits
  1784. unsigned funct3 = (faulty_instruction >> 12) & 0x7; // bits 12-14, inclusive
  1785. switch (opcode) {
  1786. case 0b0000011: // loads
  1787. switch (funct3) {
  1788. case 0b000: // lb
  1789. case 0b001: // lh
  1790. case 0b010: // lw
  1791. #if __riscv_xlen == 64
  1792. case 0b011: // ld
  1793. #endif
  1794. case 0b100: // lbu
  1795. case 0b101: // lhu
  1796. return SignalContext::Read;
  1797. default:
  1798. return SignalContext::Unknown;
  1799. }
  1800. case 0b0100011: // stores
  1801. switch (funct3) {
  1802. case 0b000: // sb
  1803. case 0b001: // sh
  1804. case 0b010: // sw
  1805. #if __riscv_xlen == 64
  1806. case 0b011: // sd
  1807. #endif
  1808. return SignalContext::Write;
  1809. default:
  1810. return SignalContext::Unknown;
  1811. }
  1812. #if __riscv_flen >= 32
  1813. case 0b0000111: // floating-point loads
  1814. switch (funct3) {
  1815. case 0b010: // flw
  1816. #if __riscv_flen == 64
  1817. case 0b011: // fld
  1818. #endif
  1819. return SignalContext::Read;
  1820. default:
  1821. return SignalContext::Unknown;
  1822. }
  1823. case 0b0100111: // floating-point stores
  1824. switch (funct3) {
  1825. case 0b010: // fsw
  1826. #if __riscv_flen == 64
  1827. case 0b011: // fsd
  1828. #endif
  1829. return SignalContext::Write;
  1830. default:
  1831. return SignalContext::Unknown;
  1832. }
  1833. #endif
  1834. default:
  1835. return SignalContext::Unknown;
  1836. }
  1837. #else
  1838. (void)ucontext;
  1839. return Unknown; // FIXME: Implement.
  1840. #endif
  1841. }
  1842. bool SignalContext::IsTrueFaultingAddress() const {
  1843. auto si = static_cast<const siginfo_t *>(siginfo);
  1844. // SIGSEGV signals without a true fault address have si_code set to 128.
  1845. return si->si_signo == SIGSEGV && si->si_code != 128;
  1846. }
  1847. void SignalContext::DumpAllRegisters(void *context) {
  1848. // FIXME: Implement this.
  1849. }
  1850. static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
  1851. #if SANITIZER_NETBSD
  1852. // This covers all NetBSD architectures
  1853. ucontext_t *ucontext = (ucontext_t *)context;
  1854. *pc = _UC_MACHINE_PC(ucontext);
  1855. *bp = _UC_MACHINE_FP(ucontext);
  1856. *sp = _UC_MACHINE_SP(ucontext);
  1857. #elif defined(__arm__)
  1858. ucontext_t *ucontext = (ucontext_t*)context;
  1859. *pc = ucontext->uc_mcontext.arm_pc;
  1860. *bp = ucontext->uc_mcontext.arm_fp;
  1861. *sp = ucontext->uc_mcontext.arm_sp;
  1862. #elif defined(__aarch64__)
  1863. ucontext_t *ucontext = (ucontext_t*)context;
  1864. *pc = ucontext->uc_mcontext.pc;
  1865. *bp = ucontext->uc_mcontext.regs[29];
  1866. *sp = ucontext->uc_mcontext.sp;
  1867. #elif defined(__hppa__)
  1868. ucontext_t *ucontext = (ucontext_t*)context;
  1869. *pc = ucontext->uc_mcontext.sc_iaoq[0];
  1870. /* GCC uses %r3 whenever a frame pointer is needed. */
  1871. *bp = ucontext->uc_mcontext.sc_gr[3];
  1872. *sp = ucontext->uc_mcontext.sc_gr[30];
  1873. #elif defined(__x86_64__)
  1874. # if SANITIZER_FREEBSD
  1875. ucontext_t *ucontext = (ucontext_t*)context;
  1876. *pc = ucontext->uc_mcontext.mc_rip;
  1877. *bp = ucontext->uc_mcontext.mc_rbp;
  1878. *sp = ucontext->uc_mcontext.mc_rsp;
  1879. # else
  1880. ucontext_t *ucontext = (ucontext_t*)context;
  1881. *pc = ucontext->uc_mcontext.gregs[REG_RIP];
  1882. *bp = ucontext->uc_mcontext.gregs[REG_RBP];
  1883. *sp = ucontext->uc_mcontext.gregs[REG_RSP];
  1884. # endif
  1885. #elif defined(__i386__)
  1886. # if SANITIZER_FREEBSD
  1887. ucontext_t *ucontext = (ucontext_t*)context;
  1888. *pc = ucontext->uc_mcontext.mc_eip;
  1889. *bp = ucontext->uc_mcontext.mc_ebp;
  1890. *sp = ucontext->uc_mcontext.mc_esp;
  1891. # else
  1892. ucontext_t *ucontext = (ucontext_t*)context;
  1893. # if SANITIZER_SOLARIS
  1894. /* Use the numeric values: the symbolic ones are undefined by llvm
  1895. include/llvm/Support/Solaris.h. */
  1896. # ifndef REG_EIP
  1897. # define REG_EIP 14 // REG_PC
  1898. # endif
  1899. # ifndef REG_EBP
  1900. # define REG_EBP 6 // REG_FP
  1901. # endif
  1902. # ifndef REG_UESP
  1903. # define REG_UESP 17 // REG_SP
  1904. # endif
  1905. # endif
  1906. *pc = ucontext->uc_mcontext.gregs[REG_EIP];
  1907. *bp = ucontext->uc_mcontext.gregs[REG_EBP];
  1908. *sp = ucontext->uc_mcontext.gregs[REG_UESP];
  1909. # endif
  1910. #elif defined(__powerpc__) || defined(__powerpc64__)
  1911. ucontext_t *ucontext = (ucontext_t*)context;
  1912. *pc = ucontext->uc_mcontext.regs->nip;
  1913. *sp = ucontext->uc_mcontext.regs->gpr[PT_R1];
  1914. // The powerpc{,64}-linux ABIs do not specify r31 as the frame
  1915. // pointer, but GCC always uses r31 when we need a frame pointer.
  1916. *bp = ucontext->uc_mcontext.regs->gpr[PT_R31];
  1917. #elif defined(__sparc__)
  1918. #if defined(__arch64__) || defined(__sparcv9)
  1919. #define STACK_BIAS 2047
  1920. #else
  1921. #define STACK_BIAS 0
  1922. # endif
  1923. # if SANITIZER_SOLARIS
  1924. ucontext_t *ucontext = (ucontext_t *)context;
  1925. *pc = ucontext->uc_mcontext.gregs[REG_PC];
  1926. *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS;
  1927. #else
  1928. // Historical BSDism here.
  1929. struct sigcontext *scontext = (struct sigcontext *)context;
  1930. #if defined(__arch64__)
  1931. *pc = scontext->sigc_regs.tpc;
  1932. *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS;
  1933. #else
  1934. *pc = scontext->si_regs.pc;
  1935. *sp = scontext->si_regs.u_regs[14];
  1936. #endif
  1937. # endif
  1938. *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS;
  1939. #elif defined(__mips__)
  1940. ucontext_t *ucontext = (ucontext_t*)context;
  1941. *pc = ucontext->uc_mcontext.pc;
  1942. *bp = ucontext->uc_mcontext.gregs[30];
  1943. *sp = ucontext->uc_mcontext.gregs[29];
  1944. #elif defined(__s390__)
  1945. ucontext_t *ucontext = (ucontext_t*)context;
  1946. # if defined(__s390x__)
  1947. *pc = ucontext->uc_mcontext.psw.addr;
  1948. # else
  1949. *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff;
  1950. # endif
  1951. *bp = ucontext->uc_mcontext.gregs[11];
  1952. *sp = ucontext->uc_mcontext.gregs[15];
  1953. #elif defined(__riscv)
  1954. ucontext_t *ucontext = (ucontext_t*)context;
  1955. # if SANITIZER_FREEBSD
  1956. *pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc;
  1957. *bp = ucontext->uc_mcontext.mc_gpregs.gp_s[0];
  1958. *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp;
  1959. # else
  1960. *pc = ucontext->uc_mcontext.__gregs[REG_PC];
  1961. *bp = ucontext->uc_mcontext.__gregs[REG_S0];
  1962. *sp = ucontext->uc_mcontext.__gregs[REG_SP];
  1963. # endif
  1964. # elif defined(__hexagon__)
  1965. ucontext_t *ucontext = (ucontext_t *)context;
  1966. *pc = ucontext->uc_mcontext.pc;
  1967. *bp = ucontext->uc_mcontext.r30;
  1968. *sp = ucontext->uc_mcontext.r29;
  1969. # else
  1970. # error "Unsupported arch"
  1971. # endif
  1972. }
  1973. void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); }
  1974. void InitializePlatformEarly() {
  1975. // Do nothing.
  1976. }
  1977. void MaybeReexec() {
  1978. // No need to re-exec on Linux.
  1979. }
  1980. void CheckASLR() {
  1981. #if SANITIZER_NETBSD
  1982. int mib[3];
  1983. int paxflags;
  1984. uptr len = sizeof(paxflags);
  1985. mib[0] = CTL_PROC;
  1986. mib[1] = internal_getpid();
  1987. mib[2] = PROC_PID_PAXFLAGS;
  1988. if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
  1989. Printf("sysctl failed\n");
  1990. Die();
  1991. }
  1992. if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) {
  1993. Printf("This sanitizer is not compatible with enabled ASLR.\n"
  1994. "To disable ASLR, please run \"paxctl +a %s\" and try again.\n",
  1995. GetArgv()[0]);
  1996. Die();
  1997. }
  1998. #elif SANITIZER_PPC64V2
  1999. // Disable ASLR for Linux PPC64LE.
  2000. int old_personality = personality(0xffffffff);
  2001. if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
  2002. VReport(1, "WARNING: Program is being run with address space layout "
  2003. "randomization (ASLR) enabled which prevents the thread and "
  2004. "memory sanitizers from working on powerpc64le.\n"
  2005. "ASLR will be disabled and the program re-executed.\n");
  2006. CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
  2007. ReExec();
  2008. }
  2009. #elif SANITIZER_FREEBSD
  2010. int aslr_status;
  2011. if (UNLIKELY(procctl(P_PID, 0, PROC_ASLR_STATUS, &aslr_status) == -1)) {
  2012. // We're making things less 'dramatic' here since
  2013. // the cmd is not necessarily guaranteed to be here
  2014. // just yet regarding FreeBSD release
  2015. return;
  2016. }
  2017. if ((aslr_status & PROC_ASLR_ACTIVE) != 0) {
  2018. Printf("This sanitizer is not compatible with enabled ASLR "
  2019. "and binaries compiled with PIE\n");
  2020. Die();
  2021. }
  2022. #else
  2023. // Do nothing
  2024. #endif
  2025. }
  2026. void CheckMPROTECT() {
  2027. #if SANITIZER_NETBSD
  2028. int mib[3];
  2029. int paxflags;
  2030. uptr len = sizeof(paxflags);
  2031. mib[0] = CTL_PROC;
  2032. mib[1] = internal_getpid();
  2033. mib[2] = PROC_PID_PAXFLAGS;
  2034. if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) {
  2035. Printf("sysctl failed\n");
  2036. Die();
  2037. }
  2038. if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) {
  2039. Printf("This sanitizer is not compatible with enabled MPROTECT\n");
  2040. Die();
  2041. }
  2042. #else
  2043. // Do nothing
  2044. #endif
  2045. }
  2046. void CheckNoDeepBind(const char *filename, int flag) {
  2047. #ifdef RTLD_DEEPBIND
  2048. if (flag & RTLD_DEEPBIND) {
  2049. Report(
  2050. "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag"
  2051. " which is incompatible with sanitizer runtime "
  2052. "(see https://github.com/google/sanitizers/issues/611 for details"
  2053. "). If you want to run %s library under sanitizers please remove "
  2054. "RTLD_DEEPBIND from dlopen flags.\n",
  2055. filename, filename);
  2056. Die();
  2057. }
  2058. #endif
  2059. }
  2060. uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
  2061. uptr *largest_gap_found,
  2062. uptr *max_occupied_addr) {
  2063. UNREACHABLE("FindAvailableMemoryRange is not available");
  2064. return 0;
  2065. }
  2066. bool GetRandom(void *buffer, uptr length, bool blocking) {
  2067. if (!buffer || !length || length > 256)
  2068. return false;
  2069. #if SANITIZER_USE_GETENTROPY
  2070. uptr rnd = getentropy(buffer, length);
  2071. int rverrno = 0;
  2072. if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT)
  2073. return false;
  2074. else if (rnd == 0)
  2075. return true;
  2076. #endif // SANITIZER_USE_GETENTROPY
  2077. #if SANITIZER_USE_GETRANDOM
  2078. static atomic_uint8_t skip_getrandom_syscall;
  2079. if (!atomic_load_relaxed(&skip_getrandom_syscall)) {
  2080. // Up to 256 bytes, getrandom will not be interrupted.
  2081. uptr res = internal_syscall(SYSCALL(getrandom), buffer, length,
  2082. blocking ? 0 : GRND_NONBLOCK);
  2083. int rverrno = 0;
  2084. if (internal_iserror(res, &rverrno) && rverrno == ENOSYS)
  2085. atomic_store_relaxed(&skip_getrandom_syscall, 1);
  2086. else if (res == length)
  2087. return true;
  2088. }
  2089. #endif // SANITIZER_USE_GETRANDOM
  2090. // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
  2091. // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
  2092. uptr fd = internal_open("/dev/urandom", O_RDONLY);
  2093. if (internal_iserror(fd))
  2094. return false;
  2095. uptr res = internal_read(fd, buffer, length);
  2096. if (internal_iserror(res))
  2097. return false;
  2098. internal_close(fd);
  2099. return true;
  2100. }
  2101. } // namespace __sanitizer
  2102. #endif