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