summaryrefslogtreecommitdiff
path: root/lib/tsan/rtl/tsan_platform_linux.cc
blob: 91d31e6059a6f65279376a7d313c960c60f308e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//===-- tsan_platform_linux.cc --------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
// Linux-specific code.
//===----------------------------------------------------------------------===//

#include "sanitizer_common/sanitizer_libc.h"
#include "tsan_platform.h"
#include "tsan_rtl.h"
#include "tsan_flags.h"

#include <asm/prctl.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <sched.h>
#include <dlfcn.h>

extern "C" int arch_prctl(int code, __sanitizer::uptr *addr);

namespace __sanitizer {

void Die() {
  _exit(1);
}

}  // namespace __sanitizer

namespace __tsan {

static uptr g_tls_size;

ScopedInRtl::ScopedInRtl()
    : thr_(cur_thread()) {
  in_rtl_ = thr_->in_rtl;
  thr_->in_rtl++;
  errno_ = errno;
}

ScopedInRtl::~ScopedInRtl() {
  thr_->in_rtl--;
  errno = errno_;
  CHECK_EQ(in_rtl_, thr_->in_rtl);
}

uptr GetShadowMemoryConsumption() {
  return 0;
}

void FlushShadowMemory() {
  madvise((void*)kLinuxShadowBeg,
          kLinuxShadowEnd - kLinuxShadowBeg,
          MADV_DONTNEED);
}

void internal_yield() {
  ScopedInRtl in_rtl;
  syscall(__NR_sched_yield);
}

void internal_sleep_ms(u32 ms) {
  usleep(ms * 1000);
}

const char *internal_getpwd() {
  return getenv("PWD");
}

static void ProtectRange(uptr beg, uptr end) {
  ScopedInRtl in_rtl;
  CHECK_LE(beg, end);
  if (beg == end)
    return;
  if (beg != (uptr)internal_mmap((void*)(beg), end - beg,
      PROT_NONE,
      MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
      -1, 0)) {
    TsanPrintf("FATAL: ThreadSanitizer can not protect [%zx,%zx]\n", beg, end);
    TsanPrintf("FATAL: Make sure you are not using unlimited stack\n");
    Die();
  }
}

void InitializeShadowMemory() {
  const uptr kClosedLowBeg  = 0x200000;
  const uptr kClosedLowEnd  = kLinuxShadowBeg - 1;
  const uptr kClosedMidBeg = kLinuxShadowEnd + 1;
  const uptr kClosedMidEnd = kLinuxAppMemBeg - 1;
  uptr shadow = (uptr)internal_mmap((void*)kLinuxShadowBeg,
      kLinuxShadowEnd - kLinuxShadowBeg,
      PROT_READ | PROT_WRITE,
      MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
      -1, 0);
  if (shadow != kLinuxShadowBeg) {
    TsanPrintf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
    TsanPrintf("FATAL: Make sure to compile with -fPIE and "
               "to link with -pie.\n");
    Die();
  }
  ProtectRange(kClosedLowBeg, kClosedLowEnd);
  ProtectRange(kClosedMidBeg, kClosedMidEnd);
  DPrintf("kClosedLow   %zx-%zx (%zuGB)\n",
      kClosedLowBeg, kClosedLowEnd, (kClosedLowEnd - kClosedLowBeg) >> 30);
  DPrintf("kLinuxShadow %zx-%zx (%zuGB)\n",
      kLinuxShadowBeg, kLinuxShadowEnd,
      (kLinuxShadowEnd - kLinuxShadowBeg) >> 30);
  DPrintf("kClosedMid   %zx-%zx (%zuGB)\n",
      kClosedMidBeg, kClosedMidEnd, (kClosedMidEnd - kClosedMidBeg) >> 30);
  DPrintf("kLinuxAppMem %zx-%zx (%zuGB)\n",
      kLinuxAppMemBeg, kLinuxAppMemEnd,
      (kLinuxAppMemEnd - kLinuxAppMemBeg) >> 30);
  DPrintf("stack        %zx\n", (uptr)&shadow);
}

static void CheckPIE() {
  // Ensure that the binary is indeed compiled with -pie.
  fd_t fmaps = internal_open("/proc/self/maps", false);
  if (fmaps == kInvalidFd)
    return;
  char buf[20];
  if (internal_read(fmaps, buf, sizeof(buf)) == sizeof(buf)) {
    buf[sizeof(buf) - 1] = 0;
    u64 addr = strtoll(buf, 0, 16);
    if ((u64)addr < kLinuxAppMemBeg) {
      TsanPrintf("FATAL: ThreadSanitizer can not mmap the shadow memory ("
             "something is mapped at 0x%zx < 0x%zx)\n",
             (uptr)addr, kLinuxAppMemBeg);
      TsanPrintf("FATAL: Make sure to compile with -fPIE"
             " and to link with -pie.\n");
      Die();
    }
  }
  internal_close(fmaps);
}

#ifdef __i386__
# define INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
#else
# define INTERNAL_FUNCTION
#endif
extern "C" void _dl_get_tls_static_info(size_t*, size_t*)
    __attribute__((weak)) INTERNAL_FUNCTION;

static int InitTlsSize() {
  typedef void (*get_tls_func)(size_t*, size_t*) INTERNAL_FUNCTION;
  get_tls_func get_tls = &_dl_get_tls_static_info;
  if (get_tls == 0)
    get_tls = (get_tls_func)dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
  CHECK_NE(get_tls, 0);
  size_t tls_size = 0;
  size_t tls_align = 0;
  get_tls(&tls_size, &tls_align);
  return tls_size;
}

const char *InitializePlatform() {
  void *p = 0;
  if (sizeof(p) == 8) {
    // Disable core dumps, dumping of 16TB usually takes a bit long.
    // The following magic is to prevent clang from replacing it with memset.
    volatile rlimit lim;
    lim.rlim_cur = 0;
    lim.rlim_max = 0;
    setrlimit(RLIMIT_CORE, (rlimit*)&lim);
  }

  CheckPIE();
  g_tls_size = (uptr)InitTlsSize();
  return getenv("TSAN_OPTIONS");
}

void FinalizePlatform() {
  fflush(0);
}

uptr GetTlsSize() {
  return g_tls_size;
}

void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
                          uptr *tls_addr, uptr *tls_size) {
  arch_prctl(ARCH_GET_FS, tls_addr);
  *tls_addr -= g_tls_size;
  *tls_size = g_tls_size;

  if (main) {
    uptr kBufSize = 1 << 26;
    char *buf = (char*)internal_mmap(0, kBufSize, PROT_READ | PROT_WRITE,
                               MAP_PRIVATE | MAP_ANON, -1, 0);
    fd_t maps = internal_open("/proc/self/maps", false);
    if (maps == kInvalidFd) {
      TsanPrintf("Failed to open /proc/self/maps\n");
      Die();
    }
    char *end = buf;
    while (end + kPageSize < buf + kBufSize) {
      uptr read = internal_read(maps, end, kPageSize);
      if ((int)read <= 0)
        break;
      end += read;
    }
    end[0] = 0;
    end = (char*)internal_strstr(buf, "[stack]");
    if (end == 0) {
      TsanPrintf("Can't find [stack] in /proc/self/maps\n");
      Die();
    }
    end[0] = 0;
    char *pos = (char*)internal_strrchr(buf, '\n');
    if (pos == 0) {
      TsanPrintf("Can't find [stack] in /proc/self/maps\n");
      Die();
    }
    pos = (char*)internal_strchr(pos, '-');
    if (pos == 0) {
      TsanPrintf("Can't find [stack] in /proc/self/maps\n");
      Die();
    }
    uptr stack = 0;
    for (; pos++;) {
      uptr num = 0;
      if (pos[0] >= '0' && pos[0] <= '9')
        num = pos[0] - '0';
      else if (pos[0] >= 'a' && pos[0] <= 'f')
        num = pos[0] - 'a' + 10;
      else
        break;
      stack = stack * 16 + num;
    }
    internal_close(maps);
    internal_munmap(buf, kBufSize);

    struct rlimit rl;
    CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
    *stk_addr = stack - rl.rlim_cur;
    *stk_size = rl.rlim_cur;
  } else {
    *stk_addr = 0;
    *stk_size = 0;
    pthread_attr_t attr;
    if (pthread_getattr_np(pthread_self(), &attr) == 0) {
      pthread_attr_getstack(&attr, (void**)stk_addr, (size_t*)stk_size);
      pthread_attr_destroy(&attr);
    }

    // If stack and tls intersect, make them non-intersecting.
    if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
      CHECK_GT(*tls_addr + *tls_size, *stk_addr);
      CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
      *stk_size -= *tls_size;
      *tls_addr = *stk_addr + *stk_size;
    }
  }
}

}  // namespace __tsan