xref: /NextBSD/contrib/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
1 //===-- sanitizer_posix.cc ------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements POSIX-specific functions from
12 // sanitizer_posix.h.
13 //===----------------------------------------------------------------------===//
14 
15 #include "sanitizer_platform.h"
16 #if SANITIZER_POSIX
17 
18 #include "sanitizer_common.h"
19 #include "sanitizer_libc.h"
20 #include "sanitizer_posix.h"
21 #include "sanitizer_procmaps.h"
22 #include "sanitizer_stacktrace.h"
23 
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <sys/mman.h>
27 
28 #if SANITIZER_LINUX
29 #include <sys/utsname.h>
30 #endif
31 
32 #if SANITIZER_LINUX && !SANITIZER_ANDROID
33 #include <sys/personality.h>
34 #endif
35 
36 #if SANITIZER_FREEBSD
37 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
38 // that, it was never implemented.  So just define it to zero.
39 #undef  MAP_NORESERVE
40 #define MAP_NORESERVE 0
41 #endif
42 
43 namespace __sanitizer {
44 
45 // ------------- sanitizer_common.h
GetMmapGranularity()46 uptr GetMmapGranularity() {
47   return GetPageSize();
48 }
49 
50 #if SANITIZER_WORDSIZE == 32
51 // Take care of unusable kernel area in top gigabyte.
GetKernelAreaSize()52 static uptr GetKernelAreaSize() {
53 #if SANITIZER_LINUX && !SANITIZER_X32
54   const uptr gbyte = 1UL << 30;
55 
56   // Firstly check if there are writable segments
57   // mapped to top gigabyte (e.g. stack).
58   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
59   uptr end, prot;
60   while (proc_maps.Next(/*start*/0, &end,
61                         /*offset*/0, /*filename*/0,
62                         /*filename_size*/0, &prot)) {
63     if ((end >= 3 * gbyte)
64         && (prot & MemoryMappingLayout::kProtectionWrite) != 0)
65       return 0;
66   }
67 
68 #if !SANITIZER_ANDROID
69   // Even if nothing is mapped, top Gb may still be accessible
70   // if we are running on 64-bit kernel.
71   // Uname may report misleading results if personality type
72   // is modified (e.g. under schroot) so check this as well.
73   struct utsname uname_info;
74   int pers = personality(0xffffffffUL);
75   if (!(pers & PER_MASK)
76       && uname(&uname_info) == 0
77       && internal_strstr(uname_info.machine, "64"))
78     return 0;
79 #endif  // SANITIZER_ANDROID
80 
81   // Top gigabyte is reserved for kernel.
82   return gbyte;
83 #else
84   return 0;
85 #endif  // SANITIZER_LINUX && !SANITIZER_X32
86 }
87 #endif  // SANITIZER_WORDSIZE == 32
88 
GetMaxVirtualAddress()89 uptr GetMaxVirtualAddress() {
90 #if SANITIZER_WORDSIZE == 64
91 # if defined(__powerpc64__) || defined(__aarch64__)
92   // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
93   // We somehow need to figure out which one we are using now and choose
94   // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
95   // Note that with 'ulimit -s unlimited' the stack is moved away from the top
96   // of the address space, so simply checking the stack address is not enough.
97   // This should (does) work for both PowerPC64 Endian modes.
98   // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
99   return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
100 # elif defined(__mips64)
101   return (1ULL << 40) - 1;  // 0x000000ffffffffffUL;
102 # else
103   return (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
104 # endif
105 #else  // SANITIZER_WORDSIZE == 32
106   uptr res = (1ULL << 32) - 1;  // 0xffffffff;
107   if (!common_flags()->full_address_space)
108     res -= GetKernelAreaSize();
109   CHECK_LT(reinterpret_cast<uptr>(&res), res);
110   return res;
111 #endif  // SANITIZER_WORDSIZE
112 }
113 
MmapOrDie(uptr size,const char * mem_type)114 void *MmapOrDie(uptr size, const char *mem_type) {
115   size = RoundUpTo(size, GetPageSizeCached());
116   uptr res = internal_mmap(0, size,
117                             PROT_READ | PROT_WRITE,
118                             MAP_PRIVATE | MAP_ANON, -1, 0);
119   int reserrno;
120   if (internal_iserror(res, &reserrno)) {
121     static int recursion_count;
122     if (recursion_count) {
123       // The Report() and CHECK calls below may call mmap recursively and fail.
124       // If we went into recursion, just die.
125       RawWrite("ERROR: Failed to mmap\n");
126       Die();
127     }
128     recursion_count++;
129     Report("ERROR: %s failed to "
130            "allocate 0x%zx (%zd) bytes of %s (errno: %d)\n",
131            SanitizerToolName, size, size, mem_type, reserrno);
132     DumpProcessMap();
133     CHECK("unable to mmap" && 0);
134   }
135   IncreaseTotalMmap(size);
136   return (void *)res;
137 }
138 
UnmapOrDie(void * addr,uptr size)139 void UnmapOrDie(void *addr, uptr size) {
140   if (!addr || !size) return;
141   uptr res = internal_munmap(addr, size);
142   if (internal_iserror(res)) {
143     Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
144            SanitizerToolName, size, size, addr);
145     CHECK("unable to unmap" && 0);
146   }
147   DecreaseTotalMmap(size);
148 }
149 
MmapNoReserveOrDie(uptr size,const char * mem_type)150 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
151   uptr PageSize = GetPageSizeCached();
152   uptr p = internal_mmap(0,
153       RoundUpTo(size, PageSize),
154       PROT_READ | PROT_WRITE,
155       MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
156       -1, 0);
157   int reserrno;
158   if (internal_iserror(p, &reserrno)) {
159     Report("ERROR: %s failed to "
160            "allocate noreserve 0x%zx (%zd) bytes for '%s' (errno: %d)\n",
161            SanitizerToolName, size, size, mem_type, reserrno);
162     CHECK("unable to mmap" && 0);
163   }
164   IncreaseTotalMmap(size);
165   return (void *)p;
166 }
167 
MmapFixedOrDie(uptr fixed_addr,uptr size)168 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
169   uptr PageSize = GetPageSizeCached();
170   uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
171       RoundUpTo(size, PageSize),
172       PROT_READ | PROT_WRITE,
173       MAP_PRIVATE | MAP_ANON | MAP_FIXED,
174       -1, 0);
175   int reserrno;
176   if (internal_iserror(p, &reserrno)) {
177     Report("ERROR: %s failed to "
178            "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
179            SanitizerToolName, size, size, fixed_addr, reserrno);
180     CHECK("unable to mmap" && 0);
181   }
182   IncreaseTotalMmap(size);
183   return (void *)p;
184 }
185 
MprotectNoAccess(uptr addr,uptr size)186 bool MprotectNoAccess(uptr addr, uptr size) {
187   return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
188 }
189 
OpenFile(const char * filename,FileAccessMode mode,error_t * errno_p)190 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
191   int flags;
192   switch (mode) {
193     case RdOnly: flags = O_RDONLY; break;
194     case WrOnly: flags = O_WRONLY | O_CREAT; break;
195     case RdWr: flags = O_RDWR | O_CREAT; break;
196   }
197   fd_t res = internal_open(filename, flags, 0660);
198   if (internal_iserror(res, errno_p))
199     return kInvalidFd;
200   return res;
201 }
202 
CloseFile(fd_t fd)203 void CloseFile(fd_t fd) {
204   internal_close(fd);
205 }
206 
ReadFromFile(fd_t fd,void * buff,uptr buff_size,uptr * bytes_read,error_t * error_p)207 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
208                   error_t *error_p) {
209   uptr res = internal_read(fd, buff, buff_size);
210   if (internal_iserror(res, error_p))
211     return false;
212   if (bytes_read)
213     *bytes_read = res;
214   return true;
215 }
216 
WriteToFile(fd_t fd,const void * buff,uptr buff_size,uptr * bytes_written,error_t * error_p)217 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
218                  error_t *error_p) {
219   uptr res = internal_write(fd, buff, buff_size);
220   if (internal_iserror(res, error_p))
221     return false;
222   if (bytes_written)
223     *bytes_written = res;
224   return true;
225 }
226 
RenameFile(const char * oldpath,const char * newpath,error_t * error_p)227 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
228   uptr res = internal_rename(oldpath, newpath);
229   return !internal_iserror(res, error_p);
230 }
231 
MapFileToMemory(const char * file_name,uptr * buff_size)232 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
233   fd_t fd = OpenFile(file_name, RdOnly);
234   CHECK(fd != kInvalidFd);
235   uptr fsize = internal_filesize(fd);
236   CHECK_NE(fsize, (uptr)-1);
237   CHECK_GT(fsize, 0);
238   *buff_size = RoundUpTo(fsize, GetPageSizeCached());
239   uptr map = internal_mmap(0, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
240   return internal_iserror(map) ? 0 : (void *)map;
241 }
242 
MapWritableFileToMemory(void * addr,uptr size,fd_t fd,OFF_T offset)243 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
244   uptr flags = MAP_SHARED;
245   if (addr) flags |= MAP_FIXED;
246   uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
247   int mmap_errno = 0;
248   if (internal_iserror(p, &mmap_errno)) {
249     Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
250            fd, (long long)offset, size, p, mmap_errno);
251     return 0;
252   }
253   return (void *)p;
254 }
255 
IntervalsAreSeparate(uptr start1,uptr end1,uptr start2,uptr end2)256 static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
257                                         uptr start2, uptr end2) {
258   CHECK(start1 <= end1);
259   CHECK(start2 <= end2);
260   return (end1 < start2) || (end2 < start1);
261 }
262 
263 // FIXME: this is thread-unsafe, but should not cause problems most of the time.
264 // When the shadow is mapped only a single thread usually exists (plus maybe
265 // several worker threads on Mac, which aren't expected to map big chunks of
266 // memory).
MemoryRangeIsAvailable(uptr range_start,uptr range_end)267 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
268   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
269   uptr start, end;
270   while (proc_maps.Next(&start, &end,
271                         /*offset*/0, /*filename*/0, /*filename_size*/0,
272                         /*protection*/0)) {
273     if (start == end) continue;  // Empty range.
274     CHECK_NE(0, end);
275     if (!IntervalsAreSeparate(start, end - 1, range_start, range_end))
276       return false;
277   }
278   return true;
279 }
280 
DumpProcessMap()281 void DumpProcessMap() {
282   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
283   uptr start, end;
284   const sptr kBufSize = 4095;
285   char *filename = (char*)MmapOrDie(kBufSize, __func__);
286   Report("Process memory map follows:\n");
287   while (proc_maps.Next(&start, &end, /* file_offset */0,
288                         filename, kBufSize, /* protection */0)) {
289     Printf("\t%p-%p\t%s\n", (void*)start, (void*)end, filename);
290   }
291   Report("End of process memory map.\n");
292   UnmapOrDie(filename, kBufSize);
293 }
294 
GetPwd()295 const char *GetPwd() {
296   return GetEnv("PWD");
297 }
298 
FindPathToBinary(const char * name)299 char *FindPathToBinary(const char *name) {
300   const char *path = GetEnv("PATH");
301   if (!path)
302     return 0;
303   uptr name_len = internal_strlen(name);
304   InternalScopedBuffer<char> buffer(kMaxPathLength);
305   const char *beg = path;
306   while (true) {
307     const char *end = internal_strchrnul(beg, ':');
308     uptr prefix_len = end - beg;
309     if (prefix_len + name_len + 2 <= kMaxPathLength) {
310       internal_memcpy(buffer.data(), beg, prefix_len);
311       buffer[prefix_len] = '/';
312       internal_memcpy(&buffer[prefix_len + 1], name, name_len);
313       buffer[prefix_len + 1 + name_len] = '\0';
314       if (FileExists(buffer.data()))
315         return internal_strdup(buffer.data());
316     }
317     if (*end == '\0') break;
318     beg = end + 1;
319   }
320   return 0;
321 }
322 
IsPathSeparator(const char c)323 bool IsPathSeparator(const char c) {
324   return c == '/';
325 }
326 
IsAbsolutePath(const char * path)327 bool IsAbsolutePath(const char *path) {
328   return path != nullptr && IsPathSeparator(path[0]);
329 }
330 
Write(const char * buffer,uptr length)331 void ReportFile::Write(const char *buffer, uptr length) {
332   SpinMutexLock l(mu);
333   static const char *kWriteError =
334       "ReportFile::Write() can't output requested buffer!\n";
335   ReopenIfNecessary();
336   if (length != internal_write(fd, buffer, length)) {
337     internal_write(fd, kWriteError, internal_strlen(kWriteError));
338     Die();
339   }
340 }
341 
GetCodeRangeForFile(const char * module,uptr * start,uptr * end)342 bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
343   uptr s, e, off, prot;
344   InternalScopedString buff(kMaxPathLength);
345   MemoryMappingLayout proc_maps(/*cache_enabled*/false);
346   while (proc_maps.Next(&s, &e, &off, buff.data(), buff.size(), &prot)) {
347     if ((prot & MemoryMappingLayout::kProtectionExecute) != 0
348         && internal_strcmp(module, buff.data()) == 0) {
349       *start = s;
350       *end = e;
351       return true;
352     }
353   }
354   return false;
355 }
356 
Create(void * siginfo,void * context)357 SignalContext SignalContext::Create(void *siginfo, void *context) {
358   uptr addr = (uptr)((siginfo_t*)siginfo)->si_addr;
359   uptr pc, sp, bp;
360   GetPcSpBp(context, &pc, &sp, &bp);
361   return SignalContext(context, addr, pc, sp, bp);
362 }
363 
364 }  // namespace __sanitizer
365 
366 #endif  // SANITIZER_POSIX
367