1 //===-- sanitizer_posix.cc ------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements POSIX-specific functions from
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
18 #include "sanitizer_common.h"
19 #include "sanitizer_libc.h"
20 #include "sanitizer_procmaps.h"
21 #include "sanitizer_stacktrace.h"
26 #include <sys/utsname.h>
29 #if SANITIZER_LINUX && !SANITIZER_ANDROID
30 #include <sys/personality.h>
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.
37 #define MAP_NORESERVE 0
40 namespace __sanitizer {
42 // ------------- sanitizer_common.h
43 uptr GetMmapGranularity() {
47 #if SANITIZER_WORDSIZE == 32
48 // Take care of unusable kernel area in top gigabyte.
49 static uptr GetKernelAreaSize() {
51 const uptr gbyte = 1UL << 30;
53 // Firstly check if there are writable segments
54 // mapped to top gigabyte (e.g. stack).
55 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
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)
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"))
76 #endif // SANITIZER_ANDROID
78 // Top gigabyte is reserved for kernel.
82 #endif // SANITIZER_LINUX
84 #endif // SANITIZER_WORDSIZE == 32
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;
101 return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
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);
109 #endif // SANITIZER_WORDSIZE
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);
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");
127 Report("ERROR: %s failed to "
128 "allocate 0x%zx (%zd) bytes of %s (errno: %d)\n",
129 SanitizerToolName, size, size, mem_type, reserrno);
131 CHECK("unable to mmap" && 0);
133 IncreaseTotalMmap(size);
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);
145 DecreaseTotalMmap(size);
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,
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);
162 IncreaseTotalMmap(size);
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,
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);
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,
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);
196 IncreaseTotalMmap(size);
200 void *Mprotect(uptr fixed_addr, uptr size) {
201 return (void *)internal_mmap((void*)fixed_addr, size,
203 MAP_PRIVATE | MAP_ANON | MAP_FIXED |
204 MAP_NORESERVE, -1, 0);
207 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
208 uptr openrv = OpenFile(file_name, false);
209 CHECK(!internal_iserror(openrv));
211 uptr fsize = internal_filesize(fd);
212 CHECK_NE(fsize, (uptr)-1);
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;
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,
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);
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
242 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
243 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
245 while (proc_maps.Next(&start, &end,
246 /*offset*/0, /*filename*/0, /*filename_size*/0,
248 if (!IntervalsAreSeparate(start, end, range_start, range_end))
254 void DumpProcessMap() {
255 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
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);
264 Report("End of process memory map.\n");
265 UnmapOrDie(filename, kBufSize);
268 const char *GetPwd() {
269 return GetEnv("PWD");
272 char *FindPathToBinary(const char *name) {
273 const char *path = GetEnv("PATH");
276 uptr name_len = internal_strlen(name);
277 InternalScopedBuffer<char> buffer(kMaxPathLength);
278 const char *beg = path;
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());
290 if (*end == '\0') break;
296 void ReportFile::Write(const char *buffer, uptr length) {
298 static const char *kWriteError =
299 "ReportFile::Write() can't output requested buffer!\n";
301 if (length != internal_write(fd, buffer, length)) {
302 internal_write(fd, kWriteError, internal_strlen(kWriteError));
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) {
322 } // namespace __sanitizer
324 #endif // SANITIZER_POSIX