linux.cpp 7.1 KB

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