sanitizer_posix.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. //===-- sanitizer_posix.cpp -----------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is shared between AddressSanitizer and ThreadSanitizer
  10. // run-time libraries and implements POSIX-specific functions from
  11. // sanitizer_posix.h.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_platform.h"
  14. #if SANITIZER_POSIX
  15. #include "sanitizer_common.h"
  16. #include "sanitizer_file.h"
  17. #include "sanitizer_flags.h"
  18. #include "sanitizer_libc.h"
  19. #include "sanitizer_posix.h"
  20. #include "sanitizer_procmaps.h"
  21. #include <errno.h>
  22. #include <fcntl.h>
  23. #include <signal.h>
  24. #include <sys/mman.h>
  25. #if SANITIZER_FREEBSD
  26. // The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
  27. // that, it was never implemented. So just define it to zero.
  28. #undef MAP_NORESERVE
  29. #define MAP_NORESERVE 0
  30. #endif
  31. namespace __sanitizer {
  32. // ------------- sanitizer_common.h
  33. uptr GetMmapGranularity() {
  34. return GetPageSize();
  35. }
  36. void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
  37. size = RoundUpTo(size, GetPageSizeCached());
  38. uptr res = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
  39. MAP_PRIVATE | MAP_ANON, mem_type);
  40. int reserrno;
  41. if (UNLIKELY(internal_iserror(res, &reserrno)))
  42. ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno, raw_report);
  43. IncreaseTotalMmap(size);
  44. return (void *)res;
  45. }
  46. void UnmapOrDie(void *addr, uptr size) {
  47. if (!addr || !size) return;
  48. uptr res = internal_munmap(addr, size);
  49. if (UNLIKELY(internal_iserror(res))) {
  50. Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
  51. SanitizerToolName, size, size, addr);
  52. CHECK("unable to unmap" && 0);
  53. }
  54. DecreaseTotalMmap(size);
  55. }
  56. void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
  57. size = RoundUpTo(size, GetPageSizeCached());
  58. uptr res = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
  59. MAP_PRIVATE | MAP_ANON, mem_type);
  60. int reserrno;
  61. if (UNLIKELY(internal_iserror(res, &reserrno))) {
  62. if (reserrno == ENOMEM)
  63. return nullptr;
  64. ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
  65. }
  66. IncreaseTotalMmap(size);
  67. return (void *)res;
  68. }
  69. // We want to map a chunk of address space aligned to 'alignment'.
  70. // We do it by mapping a bit more and then unmapping redundant pieces.
  71. // We probably can do it with fewer syscalls in some OS-dependent way.
  72. void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
  73. const char *mem_type) {
  74. CHECK(IsPowerOfTwo(size));
  75. CHECK(IsPowerOfTwo(alignment));
  76. uptr map_size = size + alignment;
  77. uptr map_res = (uptr)MmapOrDieOnFatalError(map_size, mem_type);
  78. if (UNLIKELY(!map_res))
  79. return nullptr;
  80. uptr map_end = map_res + map_size;
  81. uptr res = map_res;
  82. if (!IsAligned(res, alignment)) {
  83. res = (map_res + alignment - 1) & ~(alignment - 1);
  84. UnmapOrDie((void*)map_res, res - map_res);
  85. }
  86. uptr end = res + size;
  87. if (end != map_end)
  88. UnmapOrDie((void*)end, map_end - end);
  89. return (void*)res;
  90. }
  91. void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
  92. size = RoundUpTo(size, GetPageSizeCached());
  93. uptr p = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
  94. MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, mem_type);
  95. int reserrno;
  96. if (UNLIKELY(internal_iserror(p, &reserrno)))
  97. ReportMmapFailureAndDie(size, mem_type, "allocate noreserve", reserrno);
  98. IncreaseTotalMmap(size);
  99. return (void *)p;
  100. }
  101. static void *MmapFixedImpl(uptr fixed_addr, uptr size, bool tolerate_enomem,
  102. const char *name) {
  103. size = RoundUpTo(size, GetPageSizeCached());
  104. fixed_addr = RoundDownTo(fixed_addr, GetPageSizeCached());
  105. uptr p = MmapNamed((void *)fixed_addr, size, PROT_READ | PROT_WRITE,
  106. MAP_PRIVATE | MAP_ANON | MAP_FIXED, name);
  107. int reserrno;
  108. if (UNLIKELY(internal_iserror(p, &reserrno))) {
  109. if (tolerate_enomem && reserrno == ENOMEM)
  110. return nullptr;
  111. char mem_type[40];
  112. internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
  113. fixed_addr);
  114. ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
  115. }
  116. IncreaseTotalMmap(size);
  117. return (void *)p;
  118. }
  119. void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
  120. return MmapFixedImpl(fixed_addr, size, false /*tolerate_enomem*/, name);
  121. }
  122. void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
  123. return MmapFixedImpl(fixed_addr, size, true /*tolerate_enomem*/, name);
  124. }
  125. bool MprotectNoAccess(uptr addr, uptr size) {
  126. return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
  127. }
  128. bool MprotectReadOnly(uptr addr, uptr size) {
  129. return 0 == internal_mprotect((void *)addr, size, PROT_READ);
  130. }
  131. #if !SANITIZER_MAC
  132. void MprotectMallocZones(void *addr, int prot) {}
  133. #endif
  134. fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
  135. if (ShouldMockFailureToOpen(filename))
  136. return kInvalidFd;
  137. int flags;
  138. switch (mode) {
  139. case RdOnly: flags = O_RDONLY; break;
  140. case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
  141. case RdWr: flags = O_RDWR | O_CREAT; break;
  142. }
  143. fd_t res = internal_open(filename, flags, 0660);
  144. if (internal_iserror(res, errno_p))
  145. return kInvalidFd;
  146. return ReserveStandardFds(res);
  147. }
  148. void CloseFile(fd_t fd) {
  149. internal_close(fd);
  150. }
  151. bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
  152. error_t *error_p) {
  153. uptr res = internal_read(fd, buff, buff_size);
  154. if (internal_iserror(res, error_p))
  155. return false;
  156. if (bytes_read)
  157. *bytes_read = res;
  158. return true;
  159. }
  160. bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
  161. error_t *error_p) {
  162. uptr res = internal_write(fd, buff, buff_size);
  163. if (internal_iserror(res, error_p))
  164. return false;
  165. if (bytes_written)
  166. *bytes_written = res;
  167. return true;
  168. }
  169. void *MapFileToMemory(const char *file_name, uptr *buff_size) {
  170. fd_t fd = OpenFile(file_name, RdOnly);
  171. CHECK(fd != kInvalidFd);
  172. uptr fsize = internal_filesize(fd);
  173. CHECK_NE(fsize, (uptr)-1);
  174. CHECK_GT(fsize, 0);
  175. *buff_size = RoundUpTo(fsize, GetPageSizeCached());
  176. uptr map = internal_mmap(nullptr, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
  177. return internal_iserror(map) ? nullptr : (void *)map;
  178. }
  179. void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
  180. uptr flags = MAP_SHARED;
  181. if (addr) flags |= MAP_FIXED;
  182. uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
  183. int mmap_errno = 0;
  184. if (internal_iserror(p, &mmap_errno)) {
  185. Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
  186. fd, (long long)offset, size, p, mmap_errno);
  187. return nullptr;
  188. }
  189. return (void *)p;
  190. }
  191. static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
  192. uptr start2, uptr end2) {
  193. CHECK(start1 <= end1);
  194. CHECK(start2 <= end2);
  195. return (end1 < start2) || (end2 < start1);
  196. }
  197. // FIXME: this is thread-unsafe, but should not cause problems most of the time.
  198. // When the shadow is mapped only a single thread usually exists (plus maybe
  199. // several worker threads on Mac, which aren't expected to map big chunks of
  200. // memory).
  201. bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
  202. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  203. if (proc_maps.Error())
  204. return true; // and hope for the best
  205. MemoryMappedSegment segment;
  206. while (proc_maps.Next(&segment)) {
  207. if (segment.start == segment.end) continue; // Empty range.
  208. CHECK_NE(0, segment.end);
  209. if (!IntervalsAreSeparate(segment.start, segment.end - 1, range_start,
  210. range_end))
  211. return false;
  212. }
  213. return true;
  214. }
  215. #if !SANITIZER_MAC
  216. void DumpProcessMap() {
  217. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  218. const sptr kBufSize = 4095;
  219. char *filename = (char*)MmapOrDie(kBufSize, __func__);
  220. MemoryMappedSegment segment(filename, kBufSize);
  221. Report("Process memory map follows:\n");
  222. while (proc_maps.Next(&segment)) {
  223. Printf("\t%p-%p\t%s\n", (void *)segment.start, (void *)segment.end,
  224. segment.filename);
  225. }
  226. Report("End of process memory map.\n");
  227. UnmapOrDie(filename, kBufSize);
  228. }
  229. #endif
  230. const char *GetPwd() {
  231. return GetEnv("PWD");
  232. }
  233. bool IsPathSeparator(const char c) {
  234. return c == '/';
  235. }
  236. bool IsAbsolutePath(const char *path) {
  237. return path != nullptr && IsPathSeparator(path[0]);
  238. }
  239. void ReportFile::Write(const char *buffer, uptr length) {
  240. SpinMutexLock l(mu);
  241. ReopenIfNecessary();
  242. internal_write(fd, buffer, length);
  243. }
  244. bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
  245. MemoryMappingLayout proc_maps(/*cache_enabled*/false);
  246. InternalMmapVector<char> buff(kMaxPathLength);
  247. MemoryMappedSegment segment(buff.data(), buff.size());
  248. while (proc_maps.Next(&segment)) {
  249. if (segment.IsExecutable() &&
  250. internal_strcmp(module, segment.filename) == 0) {
  251. *start = segment.start;
  252. *end = segment.end;
  253. return true;
  254. }
  255. }
  256. return false;
  257. }
  258. uptr SignalContext::GetAddress() const {
  259. auto si = static_cast<const siginfo_t *>(siginfo);
  260. return (uptr)si->si_addr;
  261. }
  262. bool SignalContext::IsMemoryAccess() const {
  263. auto si = static_cast<const siginfo_t *>(siginfo);
  264. return si->si_signo == SIGSEGV || si->si_signo == SIGBUS;
  265. }
  266. int SignalContext::GetType() const {
  267. return static_cast<const siginfo_t *>(siginfo)->si_signo;
  268. }
  269. const char *SignalContext::Describe() const {
  270. switch (GetType()) {
  271. case SIGFPE:
  272. return "FPE";
  273. case SIGILL:
  274. return "ILL";
  275. case SIGABRT:
  276. return "ABRT";
  277. case SIGSEGV:
  278. return "SEGV";
  279. case SIGBUS:
  280. return "BUS";
  281. case SIGTRAP:
  282. return "TRAP";
  283. }
  284. return "UNKNOWN SIGNAL";
  285. }
  286. fd_t ReserveStandardFds(fd_t fd) {
  287. CHECK_GE(fd, 0);
  288. if (fd > 2)
  289. return fd;
  290. bool used[3];
  291. internal_memset(used, 0, sizeof(used));
  292. while (fd <= 2) {
  293. used[fd] = true;
  294. fd = internal_dup(fd);
  295. }
  296. for (int i = 0; i <= 2; ++i)
  297. if (used[i])
  298. internal_close(i);
  299. return fd;
  300. }
  301. bool ShouldMockFailureToOpen(const char *path) {
  302. return common_flags()->test_only_emulate_no_memorymap &&
  303. internal_strncmp(path, "/proc/", 6) == 0;
  304. }
  305. #if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_GO
  306. int GetNamedMappingFd(const char *name, uptr size, int *flags) {
  307. if (!common_flags()->decorate_proc_maps || !name)
  308. return -1;
  309. char shmname[200];
  310. CHECK(internal_strlen(name) < sizeof(shmname) - 10);
  311. internal_snprintf(shmname, sizeof(shmname), "/dev/shm/%zu [%s]",
  312. internal_getpid(), name);
  313. int o_cloexec = 0;
  314. #if defined(O_CLOEXEC)
  315. o_cloexec = O_CLOEXEC;
  316. #endif
  317. int fd = ReserveStandardFds(
  318. internal_open(shmname, O_RDWR | O_CREAT | O_TRUNC | o_cloexec, S_IRWXU));
  319. CHECK_GE(fd, 0);
  320. int res = internal_ftruncate(fd, size);
  321. #if !defined(O_CLOEXEC)
  322. res = fcntl(fd, F_SETFD, FD_CLOEXEC);
  323. CHECK_EQ(0, res);
  324. #endif
  325. CHECK_EQ(0, res);
  326. res = internal_unlink(shmname);
  327. CHECK_EQ(0, res);
  328. *flags &= ~(MAP_ANON | MAP_ANONYMOUS);
  329. return fd;
  330. }
  331. #else
  332. int GetNamedMappingFd(const char *name, uptr size, int *flags) {
  333. return -1;
  334. }
  335. #endif
  336. #if SANITIZER_ANDROID
  337. #define PR_SET_VMA 0x53564d41
  338. #define PR_SET_VMA_ANON_NAME 0
  339. void DecorateMapping(uptr addr, uptr size, const char *name) {
  340. if (!common_flags()->decorate_proc_maps || !name)
  341. return;
  342. internal_prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, addr, size, (uptr)name);
  343. }
  344. #else
  345. void DecorateMapping(uptr addr, uptr size, const char *name) {
  346. }
  347. #endif
  348. uptr MmapNamed(void *addr, uptr length, int prot, int flags, const char *name) {
  349. int fd = GetNamedMappingFd(name, length, &flags);
  350. uptr res = internal_mmap(addr, length, prot, flags, fd, 0);
  351. if (!internal_iserror(res))
  352. DecorateMapping(res, length, name);
  353. return res;
  354. }
  355. } // namespace __sanitizer
  356. #endif // SANITIZER_POSIX