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 "atomic_helpers.h" 14 #include "common.h" 15 #include "linux.h" 16 #include "mutex.h" 17 #include "string_utils.h" 18 19 #include <errno.h> 20 #include <fcntl.h> 21 #include <linux/futex.h> 22 #include <sched.h> 23 #include <stdlib.h> 24 #include <string.h> 25 #include <sys/mman.h> 26 #include <sys/stat.h> 27 #include <sys/syscall.h> 28 #include <sys/time.h> 29 #include <time.h> 30 #include <unistd.h> 31 32 #if SCUDO_ANDROID 33 #include <sys/prctl.h> 34 // Definitions of prctl arguments to set a vma name in Android kernels. 35 #define ANDROID_PR_SET_VMA 0x53564d41 36 #define ANDROID_PR_SET_VMA_ANON_NAME 0 37 #endif 38 39 namespace scudo { 40 41 uptr getPageSize() { return static_cast<uptr>(sysconf(_SC_PAGESIZE)); } 42 43 void NORETURN die() { abort(); } 44 45 void *map(void *Addr, uptr Size, UNUSED const char *Name, uptr Flags, 46 UNUSED MapPlatformData *Data) { 47 int MmapFlags = MAP_PRIVATE | MAP_ANONYMOUS; 48 int MmapProt; 49 if (Flags & MAP_NOACCESS) { 50 MmapFlags |= MAP_NORESERVE; 51 MmapProt = PROT_NONE; 52 } else { 53 MmapProt = PROT_READ | PROT_WRITE; 54 } 55 #if defined(__aarch64__) 56 #ifndef PROT_MTE 57 #define PROT_MTE 0x20 58 #endif 59 if (Flags & MAP_MEMTAG) 60 MmapProt |= PROT_MTE; 61 #endif 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 (Name) 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 setMemoryPermission(uptr Addr, uptr Size, uptr Flags, 87 UNUSED MapPlatformData *Data) { 88 int Prot = (Flags & MAP_NOACCESS) ? PROT_NONE : (PROT_READ | PROT_WRITE); 89 if (mprotect(reinterpret_cast<void *>(Addr), Size, Prot) != 0) 90 dieOnMapUnmapError(); 91 } 92 93 static bool madviseNeedsMemset() { 94 uptr Size = getPageSizeCached(); 95 char *P = (char *)mmap(0, Size, PROT_READ | PROT_WRITE, 96 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 97 if (!P) 98 dieOnMapUnmapError(errno == ENOMEM); 99 *P = 1; 100 while (madvise(P, Size, MADV_DONTNEED) == -1 && errno == EAGAIN) { 101 } 102 bool R = (*P != 0); 103 if (munmap(P, Size) != 0) 104 dieOnMapUnmapError(); 105 return R; 106 } 107 108 static bool madviseNeedsMemsetCached() { 109 static atomic_u8 Cache; 110 enum State : u8 { Unknown = 0, Yes = 1, No = 2 }; 111 State NeedsMemset = static_cast<State>(atomic_load_relaxed(&Cache)); 112 if (NeedsMemset == Unknown) { 113 NeedsMemset = madviseNeedsMemset() ? Yes : No; 114 atomic_store_relaxed(&Cache, NeedsMemset); 115 } 116 return NeedsMemset == Yes; 117 } 118 119 void releasePagesToOS(uptr BaseAddress, uptr Offset, uptr Size, 120 UNUSED MapPlatformData *Data) { 121 void *Addr = reinterpret_cast<void *>(BaseAddress + Offset); 122 if (madviseNeedsMemsetCached()) { 123 // Workaround for QEMU-user ignoring MADV_DONTNEED. 124 // https://github.com/qemu/qemu/blob/b1cffefa1b163bce9aebc3416f562c1d3886eeaa/linux-user/syscall.c#L11941 125 memset(Addr, 0, Size); 126 } 127 while (madvise(Addr, Size, MADV_DONTNEED) == -1 && errno == EAGAIN) { 128 } 129 } 130 131 // Calling getenv should be fine (c)(tm) at any time. 132 const char *getEnv(const char *Name) { return getenv(Name); } 133 134 namespace { 135 enum State : u32 { Unlocked = 0, Locked = 1, Sleeping = 2 }; 136 } 137 138 bool HybridMutex::tryLock() { 139 return atomic_compare_exchange(&M, Unlocked, Locked) == Unlocked; 140 } 141 142 // The following is based on https://akkadia.org/drepper/futex.pdf. 143 void HybridMutex::lockSlow() { 144 u32 V = atomic_compare_exchange(&M, Unlocked, Locked); 145 if (V == Unlocked) 146 return; 147 if (V != Sleeping) 148 V = atomic_exchange(&M, Sleeping, memory_order_acquire); 149 while (V != Unlocked) { 150 syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAIT_PRIVATE, Sleeping, 151 nullptr, nullptr, 0); 152 V = atomic_exchange(&M, Sleeping, memory_order_acquire); 153 } 154 } 155 156 void HybridMutex::unlock() { 157 if (atomic_fetch_sub(&M, 1U, memory_order_release) != Locked) { 158 atomic_store(&M, Unlocked, memory_order_release); 159 syscall(SYS_futex, reinterpret_cast<uptr>(&M), FUTEX_WAKE_PRIVATE, 1, 160 nullptr, nullptr, 0); 161 } 162 } 163 164 u64 getMonotonicTime() { 165 timespec TS; 166 clock_gettime(CLOCK_MONOTONIC, &TS); 167 return static_cast<u64>(TS.tv_sec) * (1000ULL * 1000 * 1000) + 168 static_cast<u64>(TS.tv_nsec); 169 } 170 171 u32 getNumberOfCPUs() { 172 cpu_set_t CPUs; 173 // sched_getaffinity can fail for a variety of legitimate reasons (lack of 174 // CAP_SYS_NICE, syscall filtering, etc), in which case we shall return 0. 175 if (sched_getaffinity(0, sizeof(cpu_set_t), &CPUs) != 0) 176 return 0; 177 return static_cast<u32>(CPU_COUNT(&CPUs)); 178 } 179 180 u32 getThreadID() { 181 #if SCUDO_ANDROID 182 return static_cast<u32>(gettid()); 183 #else 184 return static_cast<u32>(syscall(SYS_gettid)); 185 #endif 186 } 187 188 // Blocking is possibly unused if the getrandom block is not compiled in. 189 bool getRandom(void *Buffer, uptr Length, UNUSED bool Blocking) { 190 if (!Buffer || !Length || Length > MaxRandomLength) 191 return false; 192 ssize_t ReadBytes; 193 #if defined(SYS_getrandom) 194 #if !defined(GRND_NONBLOCK) 195 #define GRND_NONBLOCK 1 196 #endif 197 // Up to 256 bytes, getrandom will not be interrupted. 198 ReadBytes = 199 syscall(SYS_getrandom, Buffer, Length, Blocking ? 0 : GRND_NONBLOCK); 200 if (ReadBytes == static_cast<ssize_t>(Length)) 201 return true; 202 #endif // defined(SYS_getrandom) 203 // Up to 256 bytes, a read off /dev/urandom will not be interrupted. 204 // Blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom. 205 const int FileDesc = open("/dev/urandom", O_RDONLY); 206 if (FileDesc == -1) 207 return false; 208 ReadBytes = read(FileDesc, Buffer, Length); 209 close(FileDesc); 210 return (ReadBytes == static_cast<ssize_t>(Length)); 211 } 212 213 // Allocation free syslog-like API. 214 extern "C" WEAK int async_safe_write_log(int pri, const char *tag, 215 const char *msg); 216 217 void outputRaw(const char *Buffer) { 218 if (&async_safe_write_log) { 219 constexpr s32 AndroidLogInfo = 4; 220 constexpr uptr MaxLength = 1024U; 221 char LocalBuffer[MaxLength]; 222 while (strlen(Buffer) > MaxLength) { 223 uptr P; 224 for (P = MaxLength - 1; P > 0; P--) { 225 if (Buffer[P] == '\n') { 226 memcpy(LocalBuffer, Buffer, P); 227 LocalBuffer[P] = '\0'; 228 async_safe_write_log(AndroidLogInfo, "scudo", LocalBuffer); 229 Buffer = &Buffer[P + 1]; 230 break; 231 } 232 } 233 // If no newline was found, just log the buffer. 234 if (P == 0) 235 break; 236 } 237 async_safe_write_log(AndroidLogInfo, "scudo", Buffer); 238 } else { 239 (void)write(2, Buffer, strlen(Buffer)); 240 } 241 } 242 243 extern "C" WEAK void android_set_abort_message(const char *); 244 245 void setAbortMessage(const char *Message) { 246 if (&android_set_abort_message) 247 android_set_abort_message(Message); 248 } 249 250 } // namespace scudo 251 252 #endif // SCUDO_LINUX 253