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_file.h"
21 #include "sanitizer_libc.h"
22 #include "sanitizer_posix.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_stacktrace.h"
32 // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
33 // that, it was never implemented. So just define it to zero.
35 #define MAP_NORESERVE 0
38 namespace __sanitizer {
40 // ------------- sanitizer_common.h
41 uptr GetMmapGranularity() {
45 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
46 size = RoundUpTo(size, GetPageSizeCached());
47 uptr res = internal_mmap(nullptr, size,
48 PROT_READ | PROT_WRITE,
49 MAP_PRIVATE | MAP_ANON, -1, 0);
51 if (UNLIKELY(internal_iserror(res, &reserrno)))
52 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno, raw_report);
53 IncreaseTotalMmap(size);
57 void UnmapOrDie(void *addr, uptr size) {
58 if (!addr || !size) return;
59 uptr res = internal_munmap(addr, size);
60 if (UNLIKELY(internal_iserror(res))) {
61 Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
62 SanitizerToolName, size, size, addr);
63 CHECK("unable to unmap" && 0);
65 DecreaseTotalMmap(size);
68 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
69 size = RoundUpTo(size, GetPageSizeCached());
70 uptr res = internal_mmap(nullptr, size,
71 PROT_READ | PROT_WRITE,
72 MAP_PRIVATE | MAP_ANON, -1, 0);
74 if (UNLIKELY(internal_iserror(res, &reserrno))) {
75 if (reserrno == ENOMEM)
77 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
79 IncreaseTotalMmap(size);
83 // We want to map a chunk of address space aligned to 'alignment'.
84 // We do it by mapping a bit more and then unmapping redundant pieces.
85 // We probably can do it with fewer syscalls in some OS-dependent way.
86 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
87 const char *mem_type) {
88 CHECK(IsPowerOfTwo(size));
89 CHECK(IsPowerOfTwo(alignment));
90 uptr map_size = size + alignment;
91 uptr map_res = (uptr)MmapOrDieOnFatalError(map_size, mem_type);
92 if (UNLIKELY(!map_res))
94 uptr map_end = map_res + map_size;
96 if (!IsAligned(res, alignment)) {
97 res = (map_res + alignment - 1) & ~(alignment - 1);
98 UnmapOrDie((void*)map_res, res - map_res);
100 uptr end = res + size;
102 UnmapOrDie((void*)end, map_end - end);
106 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
107 uptr PageSize = GetPageSizeCached();
108 uptr p = internal_mmap(nullptr,
109 RoundUpTo(size, PageSize),
110 PROT_READ | PROT_WRITE,
111 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
114 if (UNLIKELY(internal_iserror(p, &reserrno)))
115 ReportMmapFailureAndDie(size, mem_type, "allocate noreserve", reserrno);
116 IncreaseTotalMmap(size);
120 void *MmapFixedImpl(uptr fixed_addr, uptr size, bool tolerate_enomem) {
121 uptr PageSize = GetPageSizeCached();
122 uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
123 RoundUpTo(size, PageSize),
124 PROT_READ | PROT_WRITE,
125 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
128 if (UNLIKELY(internal_iserror(p, &reserrno))) {
129 if (tolerate_enomem && reserrno == ENOMEM)
132 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
134 ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
136 IncreaseTotalMmap(size);
140 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
141 return MmapFixedImpl(fixed_addr, size, false /*tolerate_enomem*/);
144 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
145 return MmapFixedImpl(fixed_addr, size, true /*tolerate_enomem*/);
148 bool MprotectNoAccess(uptr addr, uptr size) {
149 return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
152 bool MprotectReadOnly(uptr addr, uptr size) {
153 return 0 == internal_mprotect((void *)addr, size, PROT_READ);
156 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
159 case RdOnly: flags = O_RDONLY; break;
160 case WrOnly: flags = O_WRONLY | O_CREAT; break;
161 case RdWr: flags = O_RDWR | O_CREAT; break;
163 fd_t res = internal_open(filename, flags, 0660);
164 if (internal_iserror(res, errno_p))
169 void CloseFile(fd_t fd) {
173 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
175 uptr res = internal_read(fd, buff, buff_size);
176 if (internal_iserror(res, error_p))
183 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
185 uptr res = internal_write(fd, buff, buff_size);
186 if (internal_iserror(res, error_p))
189 *bytes_written = res;
193 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
194 uptr res = internal_rename(oldpath, newpath);
195 return !internal_iserror(res, error_p);
198 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
199 fd_t fd = OpenFile(file_name, RdOnly);
200 CHECK(fd != kInvalidFd);
201 uptr fsize = internal_filesize(fd);
202 CHECK_NE(fsize, (uptr)-1);
204 *buff_size = RoundUpTo(fsize, GetPageSizeCached());
205 uptr map = internal_mmap(nullptr, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
206 return internal_iserror(map) ? nullptr : (void *)map;
209 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
210 uptr flags = MAP_SHARED;
211 if (addr) flags |= MAP_FIXED;
212 uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
214 if (internal_iserror(p, &mmap_errno)) {
215 Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
216 fd, (long long)offset, size, p, mmap_errno);
222 static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
223 uptr start2, uptr end2) {
224 CHECK(start1 <= end1);
225 CHECK(start2 <= end2);
226 return (end1 < start2) || (end2 < start1);
229 // FIXME: this is thread-unsafe, but should not cause problems most of the time.
230 // When the shadow is mapped only a single thread usually exists (plus maybe
231 // several worker threads on Mac, which aren't expected to map big chunks of
233 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
234 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
235 MemoryMappedSegment segment;
236 while (proc_maps.Next(&segment)) {
237 if (segment.start == segment.end) continue; // Empty range.
238 CHECK_NE(0, segment.end);
239 if (!IntervalsAreSeparate(segment.start, segment.end - 1, range_start,
246 void DumpProcessMap() {
247 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
248 const sptr kBufSize = 4095;
249 char *filename = (char*)MmapOrDie(kBufSize, __func__);
250 MemoryMappedSegment segment(filename, kBufSize);
251 Report("Process memory map follows:\n");
252 while (proc_maps.Next(&segment)) {
253 Printf("\t%p-%p\t%s\n", (void *)segment.start, (void *)segment.end,
256 Report("End of process memory map.\n");
257 UnmapOrDie(filename, kBufSize);
260 const char *GetPwd() {
261 return GetEnv("PWD");
264 bool IsPathSeparator(const char c) {
268 bool IsAbsolutePath(const char *path) {
269 return path != nullptr && IsPathSeparator(path[0]);
272 void ReportFile::Write(const char *buffer, uptr length) {
274 static const char *kWriteError =
275 "ReportFile::Write() can't output requested buffer!\n";
277 if (length != internal_write(fd, buffer, length)) {
278 internal_write(fd, kWriteError, internal_strlen(kWriteError));
283 bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
284 MemoryMappingLayout proc_maps(/*cache_enabled*/false);
285 InternalScopedString buff(kMaxPathLength);
286 MemoryMappedSegment segment(buff.data(), kMaxPathLength);
287 while (proc_maps.Next(&segment)) {
288 if (segment.IsExecutable() &&
289 internal_strcmp(module, segment.filename) == 0) {
290 *start = segment.start;
298 uptr SignalContext::GetAddress() const {
299 auto si = static_cast<const siginfo_t *>(siginfo);
300 return (uptr)si->si_addr;
303 bool SignalContext::IsMemoryAccess() const {
304 auto si = static_cast<const siginfo_t *>(siginfo);
305 return si->si_signo == SIGSEGV;
308 int SignalContext::GetType() const {
309 return static_cast<const siginfo_t *>(siginfo)->si_signo;
312 const char *SignalContext::Describe() const {
325 return "UNKNOWN SIGNAL";
328 } // namespace __sanitizer
330 #endif // SANITIZER_POSIX