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"
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"
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.
34 #define MAP_NORESERVE 0
37 namespace __sanitizer {
39 // ------------- sanitizer_common.h
40 uptr GetMmapGranularity() {
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);
50 if (UNLIKELY(internal_iserror(res, &reserrno)))
51 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno, raw_report);
52 IncreaseTotalMmap(size);
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);
64 DecreaseTotalMmap(size);
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);
73 if (UNLIKELY(internal_iserror(res, &reserrno))) {
74 if (reserrno == ENOMEM)
76 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
78 IncreaseTotalMmap(size);
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))
93 uptr map_end = map_res + map_size;
95 if (!IsAligned(res, alignment)) {
96 res = (map_res + alignment - 1) & ~(alignment - 1);
97 UnmapOrDie((void*)map_res, res - map_res);
99 uptr end = res + size;
101 UnmapOrDie((void*)end, map_end - end);
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,
113 if (UNLIKELY(internal_iserror(p, &reserrno)))
114 ReportMmapFailureAndDie(size, mem_type, "allocate noreserve", reserrno);
115 IncreaseTotalMmap(size);
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,
127 if (UNLIKELY(internal_iserror(p, &reserrno))) {
128 if (tolerate_enomem && reserrno == ENOMEM)
131 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
133 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
135 IncreaseTotalMmap(size);
139 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
140 return MmapFixedImpl(fixed_addr, size, false /*tolerate_enomem*/);
143 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
144 return MmapFixedImpl(fixed_addr, size, true /*tolerate_enomem*/);
147 bool MprotectNoAccess(uptr addr, uptr size) {
148 return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
151 bool MprotectReadOnly(uptr addr, uptr size) {
152 return 0 == internal_mprotect((void *)addr, size, PROT_READ);
155 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
158 case RdOnly: flags = O_RDONLY; break;
159 case WrOnly: flags = O_WRONLY | O_CREAT; break;
160 case RdWr: flags = O_RDWR | O_CREAT; break;
162 fd_t res = internal_open(filename, flags, 0660);
163 if (internal_iserror(res, errno_p))
168 void CloseFile(fd_t fd) {
172 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
174 uptr res = internal_read(fd, buff, buff_size);
175 if (internal_iserror(res, error_p))
182 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
184 uptr res = internal_write(fd, buff, buff_size);
185 if (internal_iserror(res, error_p))
188 *bytes_written = res;
192 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
193 uptr res = internal_rename(oldpath, newpath);
194 return !internal_iserror(res, error_p);
197 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
198 fd_t fd = OpenFile(file_name, RdOnly);
199 CHECK(fd != kInvalidFd);
200 uptr fsize = internal_filesize(fd);
201 CHECK_NE(fsize, (uptr)-1);
203 *buff_size = RoundUpTo(fsize, GetPageSizeCached());
204 uptr map = internal_mmap(nullptr, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
205 return internal_iserror(map) ? nullptr : (void *)map;
208 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
209 uptr flags = MAP_SHARED;
210 if (addr) flags |= MAP_FIXED;
211 uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
213 if (internal_iserror(p, &mmap_errno)) {
214 Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
215 fd, (long long)offset, size, p, mmap_errno);
221 static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
222 uptr start2, uptr end2) {
223 CHECK(start1 <= end1);
224 CHECK(start2 <= end2);
225 return (end1 < start2) || (end2 < start1);
228 // FIXME: this is thread-unsafe, but should not cause problems most of the time.
229 // When the shadow is mapped only a single thread usually exists (plus maybe
230 // several worker threads on Mac, which aren't expected to map big chunks of
232 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
233 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
234 MemoryMappedSegment segment;
235 while (proc_maps.Next(&segment)) {
236 if (segment.start == segment.end) continue; // Empty range.
237 CHECK_NE(0, segment.end);
238 if (!IntervalsAreSeparate(segment.start, segment.end - 1, range_start,
245 void DumpProcessMap() {
246 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
247 const sptr kBufSize = 4095;
248 char *filename = (char*)MmapOrDie(kBufSize, __func__);
249 MemoryMappedSegment segment(filename, kBufSize);
250 Report("Process memory map follows:\n");
251 while (proc_maps.Next(&segment)) {
252 Printf("\t%p-%p\t%s\n", (void *)segment.start, (void *)segment.end,
255 Report("End of process memory map.\n");
256 UnmapOrDie(filename, kBufSize);
259 const char *GetPwd() {
260 return GetEnv("PWD");
263 bool IsPathSeparator(const char c) {
267 bool IsAbsolutePath(const char *path) {
268 return path != nullptr && IsPathSeparator(path[0]);
271 void ReportFile::Write(const char *buffer, uptr length) {
273 static const char *kWriteError =
274 "ReportFile::Write() can't output requested buffer!\n";
276 if (length != internal_write(fd, buffer, length)) {
277 internal_write(fd, kWriteError, internal_strlen(kWriteError));
282 bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
283 MemoryMappingLayout proc_maps(/*cache_enabled*/false);
284 InternalScopedString buff(kMaxPathLength);
285 MemoryMappedSegment segment(buff.data(), kMaxPathLength);
286 while (proc_maps.Next(&segment)) {
287 if (segment.IsExecutable() &&
288 internal_strcmp(module, segment.filename) == 0) {
289 *start = segment.start;
297 SignalContext SignalContext::Create(void *siginfo, void *context) {
298 auto si = (siginfo_t *)siginfo;
299 uptr addr = (uptr)si->si_addr;
301 GetPcSpBp(context, &pc, &sp, &bp);
302 WriteFlag write_flag = GetWriteFlag(context);
303 bool is_memory_access = si->si_signo == SIGSEGV;
304 return SignalContext(context, addr, pc, sp, bp, is_memory_access, write_flag);
307 const char *DescribeSignalOrException(int signo) {
320 return "UNKNOWN SIGNAL";
323 } // namespace __sanitizer
325 #endif // SANITIZER_POSIX