]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_posix.cc
Merge llvm, clang, lld, lldb, compiler-rt and libc++ 7.0.0 release
[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_posix.h.
13 //===----------------------------------------------------------------------===//
14
15 #include "sanitizer_platform.h"
16
17 #if SANITIZER_POSIX
18
19 #include "sanitizer_common.h"
20 #include "sanitizer_file.h"
21 #include "sanitizer_libc.h"
22 #include "sanitizer_posix.h"
23 #include "sanitizer_procmaps.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/mman.h>
29
30 #if SANITIZER_FREEBSD
31 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
32 // that, it was never implemented.  So just define it to zero.
33 #undef  MAP_NORESERVE
34 #define MAP_NORESERVE 0
35 #endif
36
37 namespace __sanitizer {
38
39 // ------------- sanitizer_common.h
40 uptr GetMmapGranularity() {
41   return GetPageSize();
42 }
43
44 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
45   size = RoundUpTo(size, GetPageSizeCached());
46   uptr res = internal_mmap(nullptr, size,
47                            PROT_READ | PROT_WRITE,
48                            MAP_PRIVATE | MAP_ANON, -1, 0);
49   int reserrno;
50   if (UNLIKELY(internal_iserror(res, &reserrno)))
51     ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno, raw_report);
52   IncreaseTotalMmap(size);
53   return (void *)res;
54 }
55
56 void UnmapOrDie(void *addr, uptr size) {
57   if (!addr || !size) return;
58   uptr res = internal_munmap(addr, size);
59   if (UNLIKELY(internal_iserror(res))) {
60     Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
61            SanitizerToolName, size, size, addr);
62     CHECK("unable to unmap" && 0);
63   }
64   DecreaseTotalMmap(size);
65 }
66
67 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
68   size = RoundUpTo(size, GetPageSizeCached());
69   uptr res = internal_mmap(nullptr, size,
70                            PROT_READ | PROT_WRITE,
71                            MAP_PRIVATE | MAP_ANON, -1, 0);
72   int reserrno;
73   if (UNLIKELY(internal_iserror(res, &reserrno))) {
74     if (reserrno == ENOMEM)
75       return nullptr;
76     ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
77   }
78   IncreaseTotalMmap(size);
79   return (void *)res;
80 }
81
82 // We want to map a chunk of address space aligned to 'alignment'.
83 // We do it by mapping a bit more and then unmapping redundant pieces.
84 // We probably can do it with fewer syscalls in some OS-dependent way.
85 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
86                                    const char *mem_type) {
87   CHECK(IsPowerOfTwo(size));
88   CHECK(IsPowerOfTwo(alignment));
89   uptr map_size = size + alignment;
90   uptr map_res = (uptr)MmapOrDieOnFatalError(map_size, mem_type);
91   if (UNLIKELY(!map_res))
92     return nullptr;
93   uptr map_end = map_res + map_size;
94   uptr res = map_res;
95   if (!IsAligned(res, alignment)) {
96     res = (map_res + alignment - 1) & ~(alignment - 1);
97     UnmapOrDie((void*)map_res, res - map_res);
98   }
99   uptr end = res + size;
100   if (end != map_end)
101     UnmapOrDie((void*)end, map_end - end);
102   return (void*)res;
103 }
104
105 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
106   uptr PageSize = GetPageSizeCached();
107   uptr p = internal_mmap(nullptr,
108                          RoundUpTo(size, PageSize),
109                          PROT_READ | PROT_WRITE,
110                          MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
111                          -1, 0);
112   int reserrno;
113   if (UNLIKELY(internal_iserror(p, &reserrno)))
114     ReportMmapFailureAndDie(size, mem_type, "allocate noreserve", reserrno);
115   IncreaseTotalMmap(size);
116   return (void *)p;
117 }
118
119 void *MmapFixedImpl(uptr fixed_addr, uptr size, bool tolerate_enomem) {
120   uptr PageSize = GetPageSizeCached();
121   uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
122       RoundUpTo(size, PageSize),
123       PROT_READ | PROT_WRITE,
124       MAP_PRIVATE | MAP_ANON | MAP_FIXED,
125       -1, 0);
126   int reserrno;
127   if (UNLIKELY(internal_iserror(p, &reserrno))) {
128     if (tolerate_enomem && reserrno == ENOMEM)
129       return nullptr;
130     char mem_type[40];
131     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
132                       fixed_addr);
133     ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
134   }
135   IncreaseTotalMmap(size);
136   return (void *)p;
137 }
138
139 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
140   return MmapFixedImpl(fixed_addr, size, false /*tolerate_enomem*/);
141 }
142
143 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
144   return MmapFixedImpl(fixed_addr, size, true /*tolerate_enomem*/);
145 }
146
147 bool MprotectNoAccess(uptr addr, uptr size) {
148   return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
149 }
150
151 bool MprotectReadOnly(uptr addr, uptr size) {
152   return 0 == internal_mprotect((void *)addr, size, PROT_READ);
153 }
154
155 #if !SANITIZER_MAC
156 void MprotectMallocZones(void *addr, int prot) {}
157 #endif
158
159 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
160   int flags;
161   switch (mode) {
162     case RdOnly: flags = O_RDONLY; break;
163     case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
164     case RdWr: flags = O_RDWR | O_CREAT; break;
165   }
166   fd_t res = internal_open(filename, flags, 0660);
167   if (internal_iserror(res, errno_p))
168     return kInvalidFd;
169   return res;
170 }
171
172 void CloseFile(fd_t fd) {
173   internal_close(fd);
174 }
175
176 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
177                   error_t *error_p) {
178   uptr res = internal_read(fd, buff, buff_size);
179   if (internal_iserror(res, error_p))
180     return false;
181   if (bytes_read)
182     *bytes_read = res;
183   return true;
184 }
185
186 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
187                  error_t *error_p) {
188   uptr res = internal_write(fd, buff, buff_size);
189   if (internal_iserror(res, error_p))
190     return false;
191   if (bytes_written)
192     *bytes_written = res;
193   return true;
194 }
195
196 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
197   uptr res = internal_rename(oldpath, newpath);
198   return !internal_iserror(res, error_p);
199 }
200
201 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
202   fd_t fd = OpenFile(file_name, RdOnly);
203   CHECK(fd != kInvalidFd);
204   uptr fsize = internal_filesize(fd);
205   CHECK_NE(fsize, (uptr)-1);
206   CHECK_GT(fsize, 0);
207   *buff_size = RoundUpTo(fsize, GetPageSizeCached());
208   uptr map = internal_mmap(nullptr, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
209   return internal_iserror(map) ? nullptr : (void *)map;
210 }
211
212 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
213   uptr flags = MAP_SHARED;
214   if (addr) flags |= MAP_FIXED;
215   uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
216   int mmap_errno = 0;
217   if (internal_iserror(p, &mmap_errno)) {
218     Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
219            fd, (long long)offset, size, p, mmap_errno);
220     return nullptr;
221   }
222   return (void *)p;
223 }
224
225 static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
226                                         uptr start2, uptr end2) {
227   CHECK(start1 <= end1);
228   CHECK(start2 <= end2);
229   return (end1 < start2) || (end2 < start1);
230 }
231
232 // FIXME: this is thread-unsafe, but should not cause problems most of the time.
233 // When the shadow is mapped only a single thread usually exists (plus maybe
234 // several worker threads on Mac, which aren't expected to map big chunks of
235 // memory).
236 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
237   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
238   MemoryMappedSegment segment;
239   while (proc_maps.Next(&segment)) {
240     if (segment.start == segment.end) continue;  // Empty range.
241     CHECK_NE(0, segment.end);
242     if (!IntervalsAreSeparate(segment.start, segment.end - 1, range_start,
243                               range_end))
244       return false;
245   }
246   return true;
247 }
248
249 void DumpProcessMap() {
250   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
251   const sptr kBufSize = 4095;
252   char *filename = (char*)MmapOrDie(kBufSize, __func__);
253   MemoryMappedSegment segment(filename, kBufSize);
254   Report("Process memory map follows:\n");
255   while (proc_maps.Next(&segment)) {
256     Printf("\t%p-%p\t%s\n", (void *)segment.start, (void *)segment.end,
257            segment.filename);
258   }
259   Report("End of process memory map.\n");
260   UnmapOrDie(filename, kBufSize);
261 }
262
263 const char *GetPwd() {
264   return GetEnv("PWD");
265 }
266
267 bool IsPathSeparator(const char c) {
268   return c == '/';
269 }
270
271 bool IsAbsolutePath(const char *path) {
272   return path != nullptr && IsPathSeparator(path[0]);
273 }
274
275 void ReportFile::Write(const char *buffer, uptr length) {
276   SpinMutexLock l(mu);
277   static const char *kWriteError =
278       "ReportFile::Write() can't output requested buffer!\n";
279   ReopenIfNecessary();
280   if (length != internal_write(fd, buffer, length)) {
281     internal_write(fd, kWriteError, internal_strlen(kWriteError));
282     Die();
283   }
284 }
285
286 bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
287   MemoryMappingLayout proc_maps(/*cache_enabled*/false);
288   InternalScopedString buff(kMaxPathLength);
289   MemoryMappedSegment segment(buff.data(), kMaxPathLength);
290   while (proc_maps.Next(&segment)) {
291     if (segment.IsExecutable() &&
292         internal_strcmp(module, segment.filename) == 0) {
293       *start = segment.start;
294       *end = segment.end;
295       return true;
296     }
297   }
298   return false;
299 }
300
301 uptr SignalContext::GetAddress() const {
302   auto si = static_cast<const siginfo_t *>(siginfo);
303   return (uptr)si->si_addr;
304 }
305
306 bool SignalContext::IsMemoryAccess() const {
307   auto si = static_cast<const siginfo_t *>(siginfo);
308   return si->si_signo == SIGSEGV;
309 }
310
311 int SignalContext::GetType() const {
312   return static_cast<const siginfo_t *>(siginfo)->si_signo;
313 }
314
315 const char *SignalContext::Describe() const {
316   switch (GetType()) {
317     case SIGFPE:
318       return "FPE";
319     case SIGILL:
320       return "ILL";
321     case SIGABRT:
322       return "ABRT";
323     case SIGSEGV:
324       return "SEGV";
325     case SIGBUS:
326       return "BUS";
327   }
328   return "UNKNOWN SIGNAL";
329 }
330
331 } // namespace __sanitizer
332
333 #endif // SANITIZER_POSIX