sanitizer_posix.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. //===-- sanitizer_posix.cc ------------------------------------------------===//
  2. //
  3. // This file is distributed under the University of Illinois Open Source
  4. // License. See LICENSE.TXT for details.
  5. //
  6. //===----------------------------------------------------------------------===//
  7. //
  8. // This file is shared between AddressSanitizer and ThreadSanitizer
  9. // run-time libraries and implements POSIX-specific functions from
  10. // sanitizer_libc.h.
  11. //===----------------------------------------------------------------------===//
  12. #include "sanitizer_platform.h"
  13. #if SANITIZER_POSIX
  14. #include "sanitizer_common.h"
  15. #include "sanitizer_libc.h"
  16. #include "sanitizer_procmaps.h"
  17. #include "sanitizer_stacktrace.h"
  18. #include <sys/mman.h>
  19. #if SANITIZER_LINUX
  20. #include <sys/utsname.h>
  21. #endif
  22. #if SANITIZER_LINUX && !SANITIZER_ANDROID
  23. #include <sys/personality.h>
  24. #endif
  25. namespace __sanitizer {
  26. // ------------- sanitizer_common.h
  27. uptr GetMmapGranularity() {
  28. return GetPageSize();
  29. }
  30. #if SANITIZER_WORDSIZE == 32
  31. // Take care of unusable kernel area in top gigabyte.
  32. static uptr GetKernelAreaSize() {
  33. #if SANITIZER_LINUX
  34. const uptr gbyte = 1UL << 30;
  35. // Firstly check if there are writable segments
  36. // mapped to top gigabyte (e.g. stack).
  37. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  38. uptr end, prot;
  39. while (proc_maps.Next(/*start*/0, &end,
  40. /*offset*/0, /*filename*/0,
  41. /*filename_size*/0, &prot)) {
  42. if ((end >= 3 * gbyte)
  43. && (prot & MemoryMappingLayout::kProtectionWrite) != 0)
  44. return 0;
  45. }
  46. #if !SANITIZER_ANDROID
  47. // Even if nothing is mapped, top Gb may still be accessible
  48. // if we are running on 64-bit kernel.
  49. // Uname may report misleading results if personality type
  50. // is modified (e.g. under schroot) so check this as well.
  51. struct utsname uname_info;
  52. int pers = personality(0xffffffffUL);
  53. if (!(pers & PER_MASK)
  54. && uname(&uname_info) == 0
  55. && internal_strstr(uname_info.machine, "64"))
  56. return 0;
  57. #endif // SANITIZER_ANDROID
  58. // Top gigabyte is reserved for kernel.
  59. return gbyte;
  60. #else
  61. return 0;
  62. #endif // SANITIZER_LINUX
  63. }
  64. #endif // SANITIZER_WORDSIZE == 32
  65. uptr GetMaxVirtualAddress() {
  66. #if SANITIZER_WORDSIZE == 64
  67. # if defined(__powerpc64__) || defined(__aarch64__)
  68. // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
  69. // We somehow need to figure out which one we are using now and choose
  70. // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
  71. // Note that with 'ulimit -s unlimited' the stack is moved away from the top
  72. // of the address space, so simply checking the stack address is not enough.
  73. // This should (does) work for both PowerPC64 Endian modes.
  74. // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
  75. return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
  76. # elif defined(__mips64)
  77. return (1ULL << 40) - 1;
  78. # else
  79. return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
  80. # endif
  81. #else // SANITIZER_WORDSIZE == 32
  82. uptr res = (1ULL << 32) - 1; // 0xffffffff;
  83. if (!common_flags()->full_address_space)
  84. res -= GetKernelAreaSize();
  85. CHECK_LT(reinterpret_cast<uptr>(&res), res);
  86. return res;
  87. #endif // SANITIZER_WORDSIZE
  88. }
  89. void *MmapOrDie(uptr size, const char *mem_type) {
  90. size = RoundUpTo(size, GetPageSizeCached());
  91. uptr res = internal_mmap(0, size,
  92. PROT_READ | PROT_WRITE,
  93. MAP_PRIVATE | MAP_ANON, -1, 0);
  94. int reserrno;
  95. if (internal_iserror(res, &reserrno)) {
  96. static int recursion_count;
  97. if (recursion_count) {
  98. // The Report() and CHECK calls below may call mmap recursively and fail.
  99. // If we went into recursion, just die.
  100. RawWrite("ERROR: Failed to mmap\n");
  101. Die();
  102. }
  103. recursion_count++;
  104. Report("ERROR: %s failed to "
  105. "allocate 0x%zx (%zd) bytes of %s (errno: %d)\n",
  106. SanitizerToolName, size, size, mem_type, reserrno);
  107. DumpProcessMap();
  108. CHECK("unable to mmap" && 0);
  109. }
  110. IncreaseTotalMmap(size);
  111. return (void *)res;
  112. }
  113. void UnmapOrDie(void *addr, uptr size) {
  114. if (!addr || !size) return;
  115. uptr res = internal_munmap(addr, size);
  116. if (internal_iserror(res)) {
  117. Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
  118. SanitizerToolName, size, size, addr);
  119. CHECK("unable to unmap" && 0);
  120. }
  121. DecreaseTotalMmap(size);
  122. }
  123. void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
  124. uptr PageSize = GetPageSizeCached();
  125. uptr p = internal_mmap(0,
  126. RoundUpTo(size, PageSize),
  127. PROT_READ | PROT_WRITE,
  128. MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
  129. -1, 0);
  130. int reserrno;
  131. if (internal_iserror(p, &reserrno)) {
  132. Report("ERROR: %s failed to "
  133. "allocate noreserve 0x%zx (%zd) bytes for '%s' (errno: %d)\n",
  134. SanitizerToolName, size, size, mem_type, reserrno);
  135. CHECK("unable to mmap" && 0);
  136. }
  137. IncreaseTotalMmap(size);
  138. return (void *)p;
  139. }
  140. void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
  141. uptr PageSize = GetPageSizeCached();
  142. uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
  143. RoundUpTo(size, PageSize),
  144. PROT_READ | PROT_WRITE,
  145. MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
  146. -1, 0);
  147. int reserrno;
  148. if (internal_iserror(p, &reserrno))
  149. Report("ERROR: %s failed to "
  150. "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
  151. SanitizerToolName, size, size, fixed_addr, reserrno);
  152. IncreaseTotalMmap(size);
  153. return (void *)p;
  154. }
  155. void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
  156. uptr PageSize = GetPageSizeCached();
  157. uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
  158. RoundUpTo(size, PageSize),
  159. PROT_READ | PROT_WRITE,
  160. MAP_PRIVATE | MAP_ANON | MAP_FIXED,
  161. -1, 0);
  162. int reserrno;
  163. if (internal_iserror(p, &reserrno)) {
  164. Report("ERROR: %s failed to "
  165. "allocate 0x%zx (%zd) bytes at address %zx (errno: %d)\n",
  166. SanitizerToolName, size, size, fixed_addr, reserrno);
  167. CHECK("unable to mmap" && 0);
  168. }
  169. IncreaseTotalMmap(size);
  170. return (void *)p;
  171. }
  172. void *Mprotect(uptr fixed_addr, uptr size) {
  173. return (void *)internal_mmap((void*)fixed_addr, size,
  174. PROT_NONE,
  175. MAP_PRIVATE | MAP_ANON | MAP_FIXED |
  176. MAP_NORESERVE, -1, 0);
  177. }
  178. void *MapFileToMemory(const char *file_name, uptr *buff_size) {
  179. uptr openrv = OpenFile(file_name, false);
  180. CHECK(!internal_iserror(openrv));
  181. fd_t fd = openrv;
  182. uptr fsize = internal_filesize(fd);
  183. CHECK_NE(fsize, (uptr)-1);
  184. CHECK_GT(fsize, 0);
  185. *buff_size = RoundUpTo(fsize, GetPageSizeCached());
  186. uptr map = internal_mmap(0, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
  187. return internal_iserror(map) ? 0 : (void *)map;
  188. }
  189. void *MapWritableFileToMemory(void *addr, uptr size, uptr fd, uptr offset) {
  190. uptr flags = MAP_SHARED;
  191. if (addr) flags |= MAP_FIXED;
  192. uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
  193. if (internal_iserror(p)) {
  194. Printf("could not map writable file (%zd, %zu, %zu): %zd\n", fd, offset,
  195. size, p);
  196. return 0;
  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. uptr start, end;
  213. while (proc_maps.Next(&start, &end,
  214. /*offset*/0, /*filename*/0, /*filename_size*/0,
  215. /*protection*/0)) {
  216. if (!IntervalsAreSeparate(start, end, range_start, range_end))
  217. return false;
  218. }
  219. return true;
  220. }
  221. void DumpProcessMap() {
  222. MemoryMappingLayout proc_maps(/*cache_enabled*/true);
  223. uptr start, end;
  224. const sptr kBufSize = 4095;
  225. char *filename = (char*)MmapOrDie(kBufSize, __func__);
  226. Report("Process memory map follows:\n");
  227. while (proc_maps.Next(&start, &end, /* file_offset */0,
  228. filename, kBufSize, /* protection */0)) {
  229. Printf("\t%p-%p\t%s\n", (void*)start, (void*)end, filename);
  230. }
  231. Report("End of process memory map.\n");
  232. UnmapOrDie(filename, kBufSize);
  233. }
  234. const char *GetPwd() {
  235. return GetEnv("PWD");
  236. }
  237. char *FindPathToBinary(const char *name) {
  238. const char *path = GetEnv("PATH");
  239. if (!path)
  240. return 0;
  241. uptr name_len = internal_strlen(name);
  242. InternalScopedBuffer<char> buffer(kMaxPathLength);
  243. const char *beg = path;
  244. while (true) {
  245. const char *end = internal_strchrnul(beg, ':');
  246. uptr prefix_len = end - beg;
  247. if (prefix_len + name_len + 2 <= kMaxPathLength) {
  248. internal_memcpy(buffer.data(), beg, prefix_len);
  249. buffer[prefix_len] = '/';
  250. internal_memcpy(&buffer[prefix_len + 1], name, name_len);
  251. buffer[prefix_len + 1 + name_len] = '\0';
  252. if (FileExists(buffer.data()))
  253. return internal_strdup(buffer.data());
  254. }
  255. if (*end == '\0') break;
  256. beg = end + 1;
  257. }
  258. return 0;
  259. }
  260. void MaybeOpenReportFile() {
  261. if (!log_to_file) return;
  262. uptr pid = internal_getpid();
  263. // If in tracer, use the parent's file.
  264. if (pid == stoptheworld_tracer_pid)
  265. pid = stoptheworld_tracer_ppid;
  266. if (report_fd_pid == pid) return;
  267. InternalScopedBuffer<char> report_path_full(4096);
  268. internal_snprintf(report_path_full.data(), report_path_full.size(),
  269. "%s.%zu", report_path_prefix, pid);
  270. uptr openrv = OpenFile(report_path_full.data(), true);
  271. if (internal_iserror(openrv)) {
  272. report_fd = kStderrFd;
  273. log_to_file = false;
  274. Report("ERROR: Can't open file: %s\n", report_path_full.data());
  275. Die();
  276. }
  277. if (report_fd != kInvalidFd) {
  278. // We're in the child. Close the parent's log.
  279. internal_close(report_fd);
  280. }
  281. report_fd = openrv;
  282. report_fd_pid = pid;
  283. }
  284. void RawWrite(const char *buffer) {
  285. static const char *kRawWriteError =
  286. "RawWrite can't output requested buffer!\n";
  287. uptr length = (uptr)internal_strlen(buffer);
  288. MaybeOpenReportFile();
  289. if (length != internal_write(report_fd, buffer, length)) {
  290. internal_write(report_fd, kRawWriteError, internal_strlen(kRawWriteError));
  291. Die();
  292. }
  293. }
  294. bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
  295. uptr s, e, off, prot;
  296. InternalScopedString buff(4096);
  297. MemoryMappingLayout proc_maps(/*cache_enabled*/false);
  298. while (proc_maps.Next(&s, &e, &off, buff.data(), buff.size(), &prot)) {
  299. if ((prot & MemoryMappingLayout::kProtectionExecute) != 0
  300. && internal_strcmp(module, buff.data()) == 0) {
  301. *start = s;
  302. *end = e;
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. } // namespace __sanitizer
  309. #endif // SANITIZER_POSIX