linux.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //===-- linux.cpp -----------------------------------------------*- C++ -*-===//
  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. #include "platform.h"
  9. #if SCUDO_LINUX
  10. #include "common.h"
  11. #include "linux.h"
  12. #include "mutex.h"
  13. #include "string_utils.h"
  14. #include <errno.h>
  15. #include <fcntl.h>
  16. #include <linux/futex.h>
  17. #include <sched.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <sys/mman.h>
  22. #include <sys/stat.h>
  23. #include <sys/syscall.h>
  24. #include <sys/time.h>
  25. #include <time.h>
  26. #include <unistd.h>
  27. #if SCUDO_ANDROID
  28. #include <sys/prctl.h>
  29. // Definitions of prctl arguments to set a vma name in Android kernels.
  30. #define ANDROID_PR_SET_VMA 0x53564d41
  31. #define ANDROID_PR_SET_VMA_ANON_NAME 0
  32. #endif
  33. namespace scudo {
  34. uptr getPageSize() { return static_cast<uptr>(sysconf(_SC_PAGESIZE)); }
  35. void NORETURN die() { abort(); }
  36. void *map(void *Addr, uptr Size, UNUSED const char *Name, uptr Flags,
  37. UNUSED MapPlatformData *Data) {
  38. int MmapFlags = MAP_PRIVATE | MAP_ANONYMOUS;
  39. int MmapProt;
  40. if (Flags & MAP_NOACCESS) {
  41. MmapFlags |= MAP_NORESERVE;
  42. MmapProt = PROT_NONE;
  43. } else {
  44. MmapProt = PROT_READ | PROT_WRITE;
  45. }
  46. #if defined(__aarch64__)
  47. #ifndef PROT_MTE
  48. #define PROT_MTE 0x20
  49. #endif
  50. if (Flags & MAP_MEMTAG)
  51. MmapProt |= PROT_MTE;
  52. #endif
  53. if (Addr)
  54. MmapFlags |= MAP_FIXED;
  55. void *P = mmap(Addr, Size, MmapProt, MmapFlags, -1, 0);
  56. if (P == MAP_FAILED) {
  57. if (!(Flags & MAP_ALLOWNOMEM) || errno != ENOMEM)
  58. dieOnMapUnmapError(errno == ENOMEM ? Size : 0);
  59. return nullptr;
  60. }
  61. #if SCUDO_ANDROID
  62. if (Name)
  63. prctl(ANDROID_PR_SET_VMA, ANDROID_PR_SET_VMA_ANON_NAME, P, Size, Name);
  64. #endif
  65. return P;
  66. }
  67. void unmap(void *Addr, uptr Size, UNUSED uptr Flags,
  68. UNUSED MapPlatformData *Data) {
  69. if (munmap(Addr, Size) != 0)
  70. dieOnMapUnmapError();
  71. }
  72. void setMemoryPermission(uptr Addr, uptr Size, uptr Flags,
  73. UNUSED MapPlatformData *Data) {
  74. int Prot = (Flags & MAP_NOACCESS) ? PROT_NONE : (PROT_READ | PROT_WRITE);
  75. if (mprotect(reinterpret_cast<void *>(Addr), Size, Prot) != 0)
  76. dieOnMapUnmapError();
  77. }
  78. void releasePagesToOS(uptr BaseAddress, uptr Offset, uptr Size,
  79. UNUSED MapPlatformData *Data) {
  80. void *Addr = reinterpret_cast<void *>(BaseAddress + Offset);
  81. while (madvise(Addr, Size, MADV_DONTNEED) == -1 && errno == EAGAIN) {
  82. }
  83. }
  84. // Calling getenv should be fine (c)(tm) at any time.
  85. const char *getEnv(const char *Name) { return getenv(Name); }
  86. namespace {
  87. enum State : u32 { Unlocked = 0, Locked = 1, Sleeping = 2 };
  88. }
  89. bool HybridMutex::tryLock() {
  90. return atomic_compare_exchange(&M, Unlocked, Locked) == Unlocked;
  91. }
  92. // The following is based on https://akkadia.org/drepper/futex.pdf.
  93. void HybridMutex::lockSlow() {
  94. u32 V = atomic_compare_exchange(&M, Unlocked, Locked);
  95. if (V == Unlocked)
  96. return;
  97. if (V != Sleeping)
  98. V = atomic_exchange(&M, Sleeping, memory_order_acquire);
  99. while (V != Unlocked) {
  100. syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAIT_PRIVATE, Sleeping,
  101. nullptr, nullptr, 0);
  102. V = atomic_exchange(&M, Sleeping, memory_order_acquire);
  103. }
  104. }
  105. void HybridMutex::unlock() {
  106. if (atomic_fetch_sub(&M, 1U, memory_order_release) != Locked) {
  107. atomic_store(&M, Unlocked, memory_order_release);
  108. syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAKE_PRIVATE, 1,
  109. nullptr, nullptr, 0);
  110. }
  111. }
  112. u64 getMonotonicTime() {
  113. timespec TS;
  114. clock_gettime(CLOCK_MONOTONIC, &TS);
  115. return static_cast<u64>(TS.tv_sec) * (1000ULL * 1000 * 1000) +
  116. static_cast<u64>(TS.tv_nsec);
  117. }
  118. u32 getNumberOfCPUs() {
  119. cpu_set_t CPUs;
  120. // sched_getaffinity can fail for a variety of legitimate reasons (lack of
  121. // CAP_SYS_NICE, syscall filtering, etc), in which case we shall return 0.
  122. if (sched_getaffinity(0, sizeof(cpu_set_t), &CPUs) != 0)
  123. return 0;
  124. return static_cast<u32>(CPU_COUNT(&CPUs));
  125. }
  126. u32 getThreadID() {
  127. #if SCUDO_ANDROID
  128. return static_cast<u32>(gettid());
  129. #else
  130. return static_cast<u32>(syscall(SYS_gettid));
  131. #endif
  132. }
  133. // Blocking is possibly unused if the getrandom block is not compiled in.
  134. bool getRandom(void *Buffer, uptr Length, UNUSED bool Blocking) {
  135. if (!Buffer || !Length || Length > MaxRandomLength)
  136. return false;
  137. ssize_t ReadBytes;
  138. #if defined(SYS_getrandom)
  139. #if !defined(GRND_NONBLOCK)
  140. #define GRND_NONBLOCK 1
  141. #endif
  142. // Up to 256 bytes, getrandom will not be interrupted.
  143. ReadBytes =
  144. syscall(SYS_getrandom, Buffer, Length, Blocking ? 0 : GRND_NONBLOCK);
  145. if (ReadBytes == static_cast<ssize_t>(Length))
  146. return true;
  147. #endif // defined(SYS_getrandom)
  148. // Up to 256 bytes, a read off /dev/urandom will not be interrupted.
  149. // Blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom.
  150. const int FileDesc = open("/dev/urandom", O_RDONLY);
  151. if (FileDesc == -1)
  152. return false;
  153. ReadBytes = read(FileDesc, Buffer, Length);
  154. close(FileDesc);
  155. return (ReadBytes == static_cast<ssize_t>(Length));
  156. }
  157. // Allocation free syslog-like API.
  158. extern "C" WEAK int async_safe_write_log(int pri, const char *tag,
  159. const char *msg);
  160. static uptr GetRSSFromBuffer(const char *Buf) {
  161. // The format of the file is:
  162. // 1084 89 69 11 0 79 0
  163. // We need the second number which is RSS in pages.
  164. const char *Pos = Buf;
  165. // Skip the first number.
  166. while (*Pos >= '0' && *Pos <= '9')
  167. Pos++;
  168. // Skip whitespaces.
  169. while (!(*Pos >= '0' && *Pos <= '9') && *Pos != 0)
  170. Pos++;
  171. // Read the number.
  172. u64 Rss = 0;
  173. for (; *Pos >= '0' && *Pos <= '9'; Pos++)
  174. Rss = Rss * 10 + static_cast<u64>(*Pos) - '0';
  175. return static_cast<uptr>(Rss * getPageSizeCached());
  176. }
  177. uptr GetRSS() {
  178. // TODO: We currently use sanitizer_common's GetRSS which reads the
  179. // RSS from /proc/self/statm by default. We might want to
  180. // call getrusage directly, even if it's less accurate.
  181. auto Fd = open("/proc/self/statm", O_RDONLY);
  182. char Buf[64];
  183. s64 Len = read(Fd, Buf, sizeof(Buf) - 1);
  184. close(Fd);
  185. if (Len <= 0)
  186. return 0;
  187. Buf[Len] = 0;
  188. return GetRSSFromBuffer(Buf);
  189. }
  190. void outputRaw(const char *Buffer) {
  191. if (&async_safe_write_log) {
  192. constexpr s32 AndroidLogInfo = 4;
  193. constexpr uptr MaxLength = 1024U;
  194. char LocalBuffer[MaxLength];
  195. while (strlen(Buffer) > MaxLength) {
  196. uptr P;
  197. for (P = MaxLength - 1; P > 0; P--) {
  198. if (Buffer[P] == '\n') {
  199. memcpy(LocalBuffer, Buffer, P);
  200. LocalBuffer[P] = '\0';
  201. async_safe_write_log(AndroidLogInfo, "scudo", LocalBuffer);
  202. Buffer = &Buffer[P + 1];
  203. break;
  204. }
  205. }
  206. // If no newline was found, just log the buffer.
  207. if (P == 0)
  208. break;
  209. }
  210. async_safe_write_log(AndroidLogInfo, "scudo", Buffer);
  211. } else {
  212. (void)write(2, Buffer, strlen(Buffer));
  213. }
  214. }
  215. extern "C" WEAK void android_set_abort_message(const char *);
  216. void setAbortMessage(const char *Message) {
  217. if (&android_set_abort_message)
  218. android_set_abort_message(Message);
  219. }
  220. } // namespace scudo
  221. #endif // SCUDO_LINUX