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