sanitizer_linux.cpp 77 KB

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