sanitizer_posix.cpp 12 KB

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