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