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