asan_rtl.cc revision e0cff0bc20ae51790c8edfbceb817e18ebf5355e
1//===-- asan_rtl.cc -------------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// Main file of the ASan run-time library.
13//===----------------------------------------------------------------------===//
14#include "asan_allocator.h"
15#include "asan_interceptors.h"
16#include "asan_interface.h"
17#include "asan_internal.h"
18#include "asan_lock.h"
19#include "asan_mapping.h"
20#include "asan_stack.h"
21#include "asan_stats.h"
22#include "asan_thread.h"
23#include "asan_thread_registry.h"
24#include "sanitizer_common/sanitizer_libc.h"
25
26namespace __sanitizer {
27using namespace __asan;
28
29void Die() {
30  static int num_calls = 0;
31  if (AtomicInc(&num_calls) > 1) {
32    // Don't die twice - run a busy loop.
33    while (1) { }
34  }
35  if (FLAG_sleep_before_dying) {
36    Report("Sleeping for %zd second(s)\n", FLAG_sleep_before_dying);
37    SleepForSeconds(FLAG_sleep_before_dying);
38  }
39  if (FLAG_unmap_shadow_on_exit)
40    AsanUnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
41  if (death_callback)
42    death_callback();
43  if (FLAG_abort_on_error)
44    Abort();
45  Exit(FLAG_exitcode);
46}
47
48}  // namespace __sanitizer
49
50namespace __asan {
51
52// -------------------------- Flags ------------------------- {{{1
53static const uptr kMallocContextSize = 30;
54
55uptr  FLAG_malloc_context_size = kMallocContextSize;
56uptr  FLAG_max_malloc_fill_size = 0;
57s64 FLAG_v = 0;
58uptr  FLAG_redzone = (ASAN_LOW_MEMORY) ? 64 : 128;  // power of two, >= 32
59uptr  FLAG_quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 24 : 1UL << 28;
60static s64    FLAG_atexit = 0;
61bool    FLAG_poison_shadow = 1;
62s64 FLAG_report_globals = 1;
63bool    FLAG_handle_segv = ASAN_NEEDS_SEGV;
64bool    FLAG_use_sigaltstack = 0;
65bool    FLAG_symbolize = 0;
66s64 FLAG_demangle = 1;
67s64 FLAG_debug = 0;
68bool    FLAG_replace_cfallocator = 1;  // Used on Mac only.
69bool    FLAG_replace_str = 1;
70bool    FLAG_replace_intrin = 1;
71bool    FLAG_use_fake_stack = 1;
72s64 FLAG_exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
73bool    FLAG_allow_user_poisoning = 1;
74s64 FLAG_sleep_before_dying = 0;
75bool    FLAG_abort_on_error = 0;
76bool    FLAG_unmap_shadow_on_exit = 0;
77bool    FLAG_disable_core = __WORDSIZE == 64;
78bool    FLAG_check_malloc_usable_size = 1;
79
80// -------------------------- Globals --------------------- {{{1
81int asan_inited;
82bool asan_init_is_running;
83void (*death_callback)(void);
84static void (*error_report_callback)(const char*);
85char *error_message_buffer = 0;
86uptr error_message_buffer_pos = 0;
87uptr error_message_buffer_size = 0;
88
89// -------------------------- Misc ---------------- {{{1
90void ShowStatsAndAbort() {
91  __asan_print_accumulated_stats();
92  Die();
93}
94
95static void PrintBytes(const char *before, uptr *a) {
96  u8 *bytes = (u8*)a;
97  uptr byte_num = (__WORDSIZE) / 8;
98  AsanPrintf("%s%p:", before, (void*)a);
99  for (uptr i = 0; i < byte_num; i++) {
100    AsanPrintf(" %x%x", bytes[i] >> 4, bytes[i] & 15);
101  }
102  AsanPrintf("\n");
103}
104
105uptr ReadFileToBuffer(const char *file_name, char **buff,
106                         uptr *buff_size, uptr max_len) {
107  const uptr kMinFileLen = kPageSize;
108  uptr read_len = 0;
109  *buff = 0;
110  *buff_size = 0;
111  // The files we usually open are not seekable, so try different buffer sizes.
112  for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
113    fd_t fd = internal_open(file_name, /*write*/ false);
114    if (fd < 0) return 0;
115    AsanUnmapOrDie(*buff, *buff_size);
116    *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
117    *buff_size = size;
118    // Read up to one page at a time.
119    read_len = 0;
120    bool reached_eof = false;
121    while (read_len + kPageSize <= size) {
122      uptr just_read = internal_read(fd, *buff + read_len, kPageSize);
123      if (just_read == 0) {
124        reached_eof = true;
125        break;
126      }
127      read_len += just_read;
128    }
129    internal_close(fd);
130    if (reached_eof)  // We've read the whole file.
131      break;
132  }
133  return read_len;
134}
135
136void AppendToErrorMessageBuffer(const char *buffer) {
137  if (error_message_buffer) {
138    uptr length = (uptr)internal_strlen(buffer);
139    int remaining = error_message_buffer_size - error_message_buffer_pos;
140    internal_strncpy(error_message_buffer + error_message_buffer_pos,
141                     buffer, remaining);
142    error_message_buffer[error_message_buffer_size - 1] = '\0';
143    // FIXME: reallocate the buffer instead of truncating the message.
144    error_message_buffer_pos += remaining > length ? length : remaining;
145  }
146}
147
148// ---------------------- mmap -------------------- {{{1
149void OutOfMemoryMessageAndDie(const char *mem_type, uptr size) {
150  AsanReport("ERROR: AddressSanitizer failed to allocate "
151             "0x%zx (%zd) bytes of %s\n",
152             size, size, mem_type);
153  PRINT_CURRENT_STACK();
154  ShowStatsAndAbort();
155}
156
157// Reserve memory range [beg, end].
158static void ReserveShadowMemoryRange(uptr beg, uptr end) {
159  CHECK((beg % kPageSize) == 0);
160  CHECK(((end + 1) % kPageSize) == 0);
161  uptr size = end - beg + 1;
162  void *res = AsanMmapFixedNoReserve(beg, size);
163  CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
164}
165
166// ---------------------- LowLevelAllocator ------------- {{{1
167void *LowLevelAllocator::Allocate(uptr size) {
168  CHECK((size & (size - 1)) == 0 && "size must be a power of two");
169  if (allocated_end_ - allocated_current_ < size) {
170    uptr size_to_allocate = Max(size, kPageSize);
171    allocated_current_ =
172        (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
173    allocated_end_ = allocated_current_ + size_to_allocate;
174    PoisonShadow((uptr)allocated_current_, size_to_allocate,
175                 kAsanInternalHeapMagic);
176  }
177  CHECK(allocated_end_ - allocated_current_ >= size);
178  void *res = allocated_current_;
179  allocated_current_ += size;
180  return res;
181}
182
183// ---------------------- DescribeAddress -------------------- {{{1
184static bool DescribeStackAddress(uptr addr, uptr access_size) {
185  AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
186  if (!t) return false;
187  const sptr kBufSize = 4095;
188  char buf[kBufSize];
189  uptr offset = 0;
190  const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
191  // This string is created by the compiler and has the following form:
192  // "FunctioName n alloc_1 alloc_2 ... alloc_n"
193  // where alloc_i looks like "offset size len ObjectName ".
194  CHECK(frame_descr);
195  // Report the function name and the offset.
196  const char *name_end = internal_strchr(frame_descr, ' ');
197  CHECK(name_end);
198  buf[0] = 0;
199  internal_strncat(buf, frame_descr,
200                   Min(kBufSize,
201                       static_cast<sptr>(name_end - frame_descr)));
202  AsanPrintf("Address %p is located at offset %zu "
203             "in frame <%s> of T%d's stack:\n",
204             (void*)addr, offset, buf, t->tid());
205  // Report the number of stack objects.
206  char *p;
207  uptr n_objects = internal_simple_strtoll(name_end, &p, 10);
208  CHECK(n_objects > 0);
209  AsanPrintf("  This frame has %zu object(s):\n", n_objects);
210  // Report all objects in this frame.
211  for (uptr i = 0; i < n_objects; i++) {
212    uptr beg, size;
213    sptr len;
214    beg  = internal_simple_strtoll(p, &p, 10);
215    size = internal_simple_strtoll(p, &p, 10);
216    len  = internal_simple_strtoll(p, &p, 10);
217    if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
218      AsanPrintf("AddressSanitizer can't parse the stack frame "
219                 "descriptor: |%s|\n", frame_descr);
220      break;
221    }
222    p++;
223    buf[0] = 0;
224    internal_strncat(buf, p, Min(kBufSize, len));
225    p += len;
226    AsanPrintf("    [%zu, %zu) '%s'\n", beg, beg + size, buf);
227  }
228  AsanPrintf("HINT: this may be a false positive if your program uses "
229             "some custom stack unwind mechanism\n"
230             "      (longjmp and C++ exceptions *are* supported)\n");
231  t->summary()->Announce();
232  return true;
233}
234
235static NOINLINE void DescribeAddress(uptr addr, uptr access_size) {
236  // Check if this is a global.
237  if (DescribeAddrIfGlobal(addr))
238    return;
239
240  if (DescribeStackAddress(addr, access_size))
241    return;
242
243  // finally, check if this is a heap.
244  DescribeHeapAddress(addr, access_size);
245}
246
247// -------------------------- Run-time entry ------------------- {{{1
248// exported functions
249#define ASAN_REPORT_ERROR(type, is_write, size)                     \
250extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
251void __asan_report_ ## type ## size(uptr addr);                \
252void __asan_report_ ## type ## size(uptr addr) {               \
253  GET_CALLER_PC_BP_SP;                                              \
254  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
255}
256
257ASAN_REPORT_ERROR(load, false, 1)
258ASAN_REPORT_ERROR(load, false, 2)
259ASAN_REPORT_ERROR(load, false, 4)
260ASAN_REPORT_ERROR(load, false, 8)
261ASAN_REPORT_ERROR(load, false, 16)
262ASAN_REPORT_ERROR(store, true, 1)
263ASAN_REPORT_ERROR(store, true, 2)
264ASAN_REPORT_ERROR(store, true, 4)
265ASAN_REPORT_ERROR(store, true, 8)
266ASAN_REPORT_ERROR(store, true, 16)
267
268// Force the linker to keep the symbols for various ASan interface functions.
269// We want to keep those in the executable in order to let the instrumented
270// dynamic libraries access the symbol even if it is not used by the executable
271// itself. This should help if the build system is removing dead code at link
272// time.
273static NOINLINE void force_interface_symbols() {
274  volatile int fake_condition = 0;  // prevent dead condition elimination.
275  if (fake_condition) {
276    __asan_report_load1(0);
277    __asan_report_load2(0);
278    __asan_report_load4(0);
279    __asan_report_load8(0);
280    __asan_report_load16(0);
281    __asan_report_store1(0);
282    __asan_report_store2(0);
283    __asan_report_store4(0);
284    __asan_report_store8(0);
285    __asan_report_store16(0);
286    __asan_register_global(0, 0, 0);
287    __asan_register_globals(0, 0);
288    __asan_unregister_globals(0, 0);
289    __asan_set_death_callback(0);
290    __asan_set_error_report_callback(0);
291    __asan_handle_no_return();
292  }
293}
294
295// -------------------------- Init ------------------- {{{1
296static void IntFlagValue(const char *flags, const char *flag,
297                         s64 *out_val) {
298  if (!flags) return;
299  const char *str = internal_strstr(flags, flag);
300  if (!str) return;
301  *out_val = internal_atoll(str + internal_strlen(flag));
302}
303
304static void BoolFlagValue(const char *flags, const char *flag,
305                          bool *out_val) {
306  if (!flags) return;
307  const char *str = internal_strstr(flags, flag);
308  if (!str) return;
309  const char *suffix = str + internal_strlen(flag);
310  if (!internal_atoll(str + internal_strlen(flag))) {
311    if (suffix[0] == '0') {
312      *out_val = false;
313      return;
314    }
315  } else {
316    *out_val = true;
317    return;
318  }
319  switch (suffix[0]) {
320    case 'y':
321    case 't': {
322      *out_val = true;
323      break;
324    }
325    case 'n':
326    case 'f': {
327      *out_val = false;
328      break;
329    }
330    default: return;
331  }
332}
333
334static void asan_atexit() {
335  AsanPrintf("AddressSanitizer exit stats:\n");
336  __asan_print_accumulated_stats();
337}
338
339void CheckFailed(const char *cond, const char *file, int line) {
340  Report("CHECK failed: %s at %s:%d\n", cond, file, line);
341  PRINT_CURRENT_STACK();
342  ShowStatsAndAbort();
343}
344
345}  // namespace __asan
346
347// ---------------------- Interface ---------------- {{{1
348using namespace __asan;  // NOLINT
349
350int __asan_set_error_exit_code(int exit_code) {
351  int old = FLAG_exitcode;
352  FLAG_exitcode = exit_code;
353  return old;
354}
355
356void NOINLINE __asan_handle_no_return() {
357  int local_stack;
358  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
359  CHECK(curr_thread);
360  uptr top = curr_thread->stack_top();
361  uptr bottom = ((uptr)&local_stack - kPageSize) & ~(kPageSize-1);
362  PoisonShadow(bottom, top - bottom, 0);
363}
364
365void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
366  death_callback = callback;
367}
368
369void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
370  error_report_callback = callback;
371  if (callback) {
372    error_message_buffer_size = 1 << 16;
373    error_message_buffer =
374        (char*)AsanMmapSomewhereOrDie(error_message_buffer_size, __FUNCTION__);
375    error_message_buffer_pos = 0;
376  }
377}
378
379void __asan_report_error(uptr pc, uptr bp, uptr sp,
380                         uptr addr, bool is_write, uptr access_size) {
381  // Do not print more than one report, otherwise they will mix up.
382  static int num_calls = 0;
383  if (AtomicInc(&num_calls) > 1) return;
384
385  AsanPrintf("===================================================="
386             "=============\n");
387  const char *bug_descr = "unknown-crash";
388  if (AddrIsInMem(addr)) {
389    u8 *shadow_addr = (u8*)MemToShadow(addr);
390    // If we are accessing 16 bytes, look at the second shadow byte.
391    if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
392      shadow_addr++;
393    // If we are in the partial right redzone, look at the next shadow byte.
394    if (*shadow_addr > 0 && *shadow_addr < 128)
395      shadow_addr++;
396    switch (*shadow_addr) {
397      case kAsanHeapLeftRedzoneMagic:
398      case kAsanHeapRightRedzoneMagic:
399        bug_descr = "heap-buffer-overflow";
400        break;
401      case kAsanHeapFreeMagic:
402        bug_descr = "heap-use-after-free";
403        break;
404      case kAsanStackLeftRedzoneMagic:
405        bug_descr = "stack-buffer-underflow";
406        break;
407      case kAsanStackMidRedzoneMagic:
408      case kAsanStackRightRedzoneMagic:
409      case kAsanStackPartialRedzoneMagic:
410        bug_descr = "stack-buffer-overflow";
411        break;
412      case kAsanStackAfterReturnMagic:
413        bug_descr = "stack-use-after-return";
414        break;
415      case kAsanUserPoisonedMemoryMagic:
416        bug_descr = "use-after-poison";
417        break;
418      case kAsanGlobalRedzoneMagic:
419        bug_descr = "global-buffer-overflow";
420        break;
421    }
422  }
423
424  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
425  u32 curr_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
426
427  if (curr_thread) {
428    // We started reporting an error message. Stop using the fake stack
429    // in case we will call an instrumented function from a symbolizer.
430    curr_thread->fake_stack().StopUsingFakeStack();
431  }
432
433  AsanReport("ERROR: AddressSanitizer %s on address "
434             "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n",
435             bug_descr, (void*)addr, pc, bp, sp);
436
437  AsanPrintf("%s of size %zu at %p thread T%d\n",
438             access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
439             access_size, (void*)addr, curr_tid);
440
441  if (FLAG_debug) {
442    PrintBytes("PC: ", (uptr*)pc);
443  }
444
445  GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, pc, bp);
446  stack.PrintStack();
447
448  CHECK(AddrIsInMem(addr));
449
450  DescribeAddress(addr, access_size);
451
452  uptr shadow_addr = MemToShadow(addr);
453  AsanReport("ABORTING\n");
454  __asan_print_accumulated_stats();
455  AsanPrintf("Shadow byte and word:\n");
456  AsanPrintf("  %p: %x\n", (void*)shadow_addr, *(unsigned char*)shadow_addr);
457  uptr aligned_shadow = shadow_addr & ~(kWordSize - 1);
458  PrintBytes("  ", (uptr*)(aligned_shadow));
459  AsanPrintf("More shadow bytes:\n");
460  PrintBytes("  ", (uptr*)(aligned_shadow-4*kWordSize));
461  PrintBytes("  ", (uptr*)(aligned_shadow-3*kWordSize));
462  PrintBytes("  ", (uptr*)(aligned_shadow-2*kWordSize));
463  PrintBytes("  ", (uptr*)(aligned_shadow-1*kWordSize));
464  PrintBytes("=>", (uptr*)(aligned_shadow+0*kWordSize));
465  PrintBytes("  ", (uptr*)(aligned_shadow+1*kWordSize));
466  PrintBytes("  ", (uptr*)(aligned_shadow+2*kWordSize));
467  PrintBytes("  ", (uptr*)(aligned_shadow+3*kWordSize));
468  PrintBytes("  ", (uptr*)(aligned_shadow+4*kWordSize));
469  if (error_report_callback) {
470    error_report_callback(error_message_buffer);
471  }
472  Die();
473}
474
475static void ParseAsanOptions(const char *options) {
476  IntFlagValue(options, "malloc_context_size=",
477               (s64*)&FLAG_malloc_context_size);
478  CHECK(FLAG_malloc_context_size <= kMallocContextSize);
479
480  IntFlagValue(options, "max_malloc_fill_size=",
481               (s64*)&FLAG_max_malloc_fill_size);
482
483  IntFlagValue(options, "verbosity=", &FLAG_v);
484
485  IntFlagValue(options, "redzone=", (s64*)&FLAG_redzone);
486  CHECK(FLAG_redzone >= 32);
487  CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
488  IntFlagValue(options, "quarantine_size=", (s64*)&FLAG_quarantine_size);
489
490  IntFlagValue(options, "atexit=", &FLAG_atexit);
491  BoolFlagValue(options, "poison_shadow=", &FLAG_poison_shadow);
492  IntFlagValue(options, "report_globals=", &FLAG_report_globals);
493  BoolFlagValue(options, "handle_segv=", &FLAG_handle_segv);
494  BoolFlagValue(options, "use_sigaltstack=", &FLAG_use_sigaltstack);
495  BoolFlagValue(options, "symbolize=", &FLAG_symbolize);
496  IntFlagValue(options, "demangle=", &FLAG_demangle);
497  IntFlagValue(options, "debug=", &FLAG_debug);
498  BoolFlagValue(options, "replace_cfallocator=", &FLAG_replace_cfallocator);
499  BoolFlagValue(options, "replace_str=", &FLAG_replace_str);
500  BoolFlagValue(options, "replace_intrin=", &FLAG_replace_intrin);
501  BoolFlagValue(options, "use_fake_stack=", &FLAG_use_fake_stack);
502  IntFlagValue(options, "exitcode=", &FLAG_exitcode);
503  BoolFlagValue(options, "allow_user_poisoning=", &FLAG_allow_user_poisoning);
504  IntFlagValue(options, "sleep_before_dying=", &FLAG_sleep_before_dying);
505  BoolFlagValue(options, "abort_on_error=", &FLAG_abort_on_error);
506  BoolFlagValue(options, "unmap_shadow_on_exit=", &FLAG_unmap_shadow_on_exit);
507  // By default, disable core dumper on 64-bit --
508  // it makes little sense to dump 16T+ core.
509  BoolFlagValue(options, "disable_core=", &FLAG_disable_core);
510
511  // Allow the users to work around the bug in Nvidia drivers prior to 295.*.
512  BoolFlagValue(options, "check_malloc_usable_size=",
513                &FLAG_check_malloc_usable_size);
514}
515
516void __asan_init() {
517  if (asan_inited) return;
518  MiniLibcStub();  // FIXME: remove me once mini libc build is tested properly.
519  asan_init_is_running = true;
520
521  // Make sure we are not statically linked.
522  AsanDoesNotSupportStaticLinkage();
523
524#if !defined(_WIN32)
525  if (__asan_default_options) {
526    ParseAsanOptions(__asan_default_options);
527    if (FLAG_v) {
528      Report("Using the defaults from __asan_default_options: %s\n",
529             __asan_default_options);
530    }
531  }
532#endif
533  // flags
534  const char *options = AsanGetEnv("ASAN_OPTIONS");
535  ParseAsanOptions(options);
536
537  if (FLAG_v && options) {
538    Report("Parsed ASAN_OPTIONS: %s\n", options);
539  }
540
541  if (FLAG_atexit) {
542    Atexit(asan_atexit);
543  }
544
545  // interceptors
546  InitializeAsanInterceptors();
547
548  ReplaceSystemMalloc();
549  ReplaceOperatorsNewAndDelete();
550
551  if (FLAG_v) {
552    Printf("|| `[%p, %p]` || HighMem    ||\n",
553           (void*)kHighMemBeg, (void*)kHighMemEnd);
554    Printf("|| `[%p, %p]` || HighShadow ||\n",
555           (void*)kHighShadowBeg, (void*)kHighShadowEnd);
556    Printf("|| `[%p, %p]` || ShadowGap  ||\n",
557           (void*)kShadowGapBeg, (void*)kShadowGapEnd);
558    Printf("|| `[%p, %p]` || LowShadow  ||\n",
559           (void*)kLowShadowBeg, (void*)kLowShadowEnd);
560    Printf("|| `[%p, %p]` || LowMem     ||\n",
561           (void*)kLowMemBeg, (void*)kLowMemEnd);
562    Printf("MemToShadow(shadow): %p %p %p %p\n",
563           (void*)MEM_TO_SHADOW(kLowShadowBeg),
564           (void*)MEM_TO_SHADOW(kLowShadowEnd),
565           (void*)MEM_TO_SHADOW(kHighShadowBeg),
566           (void*)MEM_TO_SHADOW(kHighShadowEnd));
567    Printf("red_zone=%zu\n", (uptr)FLAG_redzone);
568    Printf("malloc_context_size=%zu\n", (uptr)FLAG_malloc_context_size);
569
570    Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE);
571    Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY);
572    Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET);
573    CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
574  }
575
576  if (FLAG_disable_core) {
577    AsanDisableCoreDumper();
578  }
579
580  if (AsanShadowRangeIsAvailable()) {
581    if (kLowShadowBeg != kLowShadowEnd) {
582      // mmap the low shadow plus at least one page.
583      ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd);
584    }
585    // mmap the high shadow.
586    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
587    // protect the gap
588    void *prot = AsanMprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
589    CHECK(prot == (void*)kShadowGapBeg);
590  } else {
591    Report("Shadow memory range interleaves with an existing memory mapping. "
592           "ASan cannot proceed correctly. ABORTING.\n");
593    AsanDumpProcessMap();
594    Die();
595  }
596
597  InstallSignalHandlers();
598
599  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
600  // should be set to 1 prior to initializing the threads.
601  asan_inited = 1;
602  asan_init_is_running = false;
603
604  asanThreadRegistry().Init();
605  asanThreadRegistry().GetMain()->ThreadStart();
606  force_interface_symbols();  // no-op.
607
608  if (FLAG_v) {
609    Report("AddressSanitizer Init done\n");
610  }
611}
612
613#if defined(ASAN_USE_PREINIT_ARRAY)
614  // On Linux, we force __asan_init to be called before anyone else
615  // by placing it into .preinit_array section.
616  // FIXME: do we have anything like this on Mac?
617  __attribute__((section(".preinit_array")))
618    typeof(__asan_init) *__asan_preinit =__asan_init;
619#elif defined(_WIN32) && defined(_DLL)
620  // On Windows, when using dynamic CRT (/MD), we can put a pointer
621  // to __asan_init into the global list of C initializers.
622  // See crt0dat.c in the CRT sources for the details.
623  #pragma section(".CRT$XIB", long, read)  // NOLINT
624  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
625#endif
626