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