1//===-- asan_linux.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 a part of AddressSanitizer, an address sanity checker.
10//
11// Linux-specific details.
12//===----------------------------------------------------------------------===//
13
14#include "sanitizer_common/sanitizer_platform.h"
15#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
16    SANITIZER_SOLARIS
17
18#  include <dlfcn.h>
19#  include <fcntl.h>
20#  include <limits.h>
21#  include <pthread.h>
22#  include <stdio.h>
23#  include <sys/mman.h>
24#  include <sys/resource.h>
25#  include <sys/syscall.h>
26#  include <sys/time.h>
27#  include <sys/types.h>
28#  include <unistd.h>
29#  include <unwind.h>
30
31#  include "asan_interceptors.h"
32#  include "asan_internal.h"
33#  include "asan_premap_shadow.h"
34#  include "asan_thread.h"
35#  include "sanitizer_common/sanitizer_flags.h"
36#  include "sanitizer_common/sanitizer_freebsd.h"
37#  include "sanitizer_common/sanitizer_hash.h"
38#  include "sanitizer_common/sanitizer_libc.h"
39#  include "sanitizer_common/sanitizer_procmaps.h"
40
41#  if SANITIZER_FREEBSD
42#    include <sys/link_elf.h>
43#  endif
44
45#  if SANITIZER_SOLARIS
46#    include <link.h>
47#  endif
48
49#  if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS
50#    include <ucontext.h>
51extern "C" void *_DYNAMIC;
52#  elif SANITIZER_NETBSD
53#    include <link_elf.h>
54#    include <ucontext.h>
55extern Elf_Dyn _DYNAMIC;
56#  else
57#    include <link.h>
58#    include <sys/ucontext.h>
59extern ElfW(Dyn) _DYNAMIC[];
60#  endif
61
62// x86-64 FreeBSD 9.2 and older define 'ucontext_t' incorrectly in
63// 32-bit mode.
64#  if SANITIZER_FREEBSD && (SANITIZER_WORDSIZE == 32) && \
65      __FreeBSD_version <= 902001  // v9.2
66#    define ucontext_t xucontext_t
67#  endif
68
69typedef enum {
70  ASAN_RT_VERSION_UNDEFINED = 0,
71  ASAN_RT_VERSION_DYNAMIC,
72  ASAN_RT_VERSION_STATIC,
73} asan_rt_version_t;
74
75// FIXME: perhaps also store abi version here?
76extern "C" {
77SANITIZER_INTERFACE_ATTRIBUTE
78asan_rt_version_t __asan_rt_version;
79}
80
81namespace __asan {
82
83void InitializePlatformInterceptors() {}
84void InitializePlatformExceptionHandlers() {}
85bool IsSystemHeapAddress(uptr addr) { return false; }
86
87void *AsanDoesNotSupportStaticLinkage() {
88  // This will fail to link with -static.
89  return &_DYNAMIC;
90}
91
92#  if ASAN_PREMAP_SHADOW
93uptr FindPremappedShadowStart(uptr shadow_size_bytes) {
94  uptr granularity = GetMmapGranularity();
95  uptr shadow_start = reinterpret_cast<uptr>(&__asan_shadow);
96  uptr premap_shadow_size = PremapShadowSize();
97  uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
98  // We may have mapped too much. Release extra memory.
99  UnmapFromTo(shadow_start + shadow_size, shadow_start + premap_shadow_size);
100  return shadow_start;
101}
102#  endif
103
104uptr FindDynamicShadowStart() {
105  uptr shadow_size_bytes = MemToShadowSize(kHighMemEnd);
106#  if ASAN_PREMAP_SHADOW
107  if (!PremapShadowFailed())
108    return FindPremappedShadowStart(shadow_size_bytes);
109#  endif
110
111  return MapDynamicShadow(shadow_size_bytes, ASAN_SHADOW_SCALE,
112                          /*min_shadow_base_alignment*/ 0, kHighMemEnd);
113}
114
115void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
116  UNIMPLEMENTED();
117}
118
119void FlushUnneededASanShadowMemory(uptr p, uptr size) {
120  // Since asan's mapping is compacting, the shadow chunk may be
121  // not page-aligned, so we only flush the page-aligned portion.
122  ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
123}
124
125#  if SANITIZER_ANDROID
126// FIXME: should we do anything for Android?
127void AsanCheckDynamicRTPrereqs() {}
128void AsanCheckIncompatibleRT() {}
129#  else
130static int FindFirstDSOCallback(struct dl_phdr_info *info, size_t size,
131                                void *data) {
132  VReport(2, "info->dlpi_name = %s\tinfo->dlpi_addr = %p\n", info->dlpi_name,
133          (void *)info->dlpi_addr);
134
135  const char **name = (const char **)data;
136
137  // Ignore first entry (the main program)
138  if (!*name) {
139    *name = "";
140    return 0;
141  }
142
143#    if SANITIZER_LINUX
144  // Ignore vDSO. glibc versions earlier than 2.15 (and some patched
145  // by distributors) return an empty name for the vDSO entry, so
146  // detect this as well.
147  if (!info->dlpi_name[0] ||
148      internal_strncmp(info->dlpi_name, "linux-", sizeof("linux-") - 1) == 0)
149    return 0;
150#    endif
151
152  *name = info->dlpi_name;
153  return 1;
154}
155
156static bool IsDynamicRTName(const char *libname) {
157  return internal_strstr(libname, "libclang_rt.asan") ||
158         internal_strstr(libname, "libasan.so");
159}
160
161static void ReportIncompatibleRT() {
162  Report("Your application is linked against incompatible ASan runtimes.\n");
163  Die();
164}
165
166void AsanCheckDynamicRTPrereqs() {
167  if (!ASAN_DYNAMIC || !flags()->verify_asan_link_order)
168    return;
169
170  // Ensure that dynamic RT is the first DSO in the list
171  const char *first_dso_name = nullptr;
172  dl_iterate_phdr(FindFirstDSOCallback, &first_dso_name);
173  if (first_dso_name && first_dso_name[0] && !IsDynamicRTName(first_dso_name)) {
174    Report(
175        "ASan runtime does not come first in initial library list; "
176        "you should either link runtime to your application or "
177        "manually preload it with LD_PRELOAD.\n");
178    Die();
179  }
180}
181
182void AsanCheckIncompatibleRT() {
183  if (ASAN_DYNAMIC) {
184    if (__asan_rt_version == ASAN_RT_VERSION_UNDEFINED) {
185      __asan_rt_version = ASAN_RT_VERSION_DYNAMIC;
186    } else if (__asan_rt_version != ASAN_RT_VERSION_DYNAMIC) {
187      ReportIncompatibleRT();
188    }
189  } else {
190    if (__asan_rt_version == ASAN_RT_VERSION_UNDEFINED) {
191      // Ensure that dynamic runtime is not present. We should detect it
192      // as early as possible, otherwise ASan interceptors could bind to
193      // the functions in dynamic ASan runtime instead of the functions in
194      // system libraries, causing crashes later in ASan initialization.
195      MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
196      char filename[PATH_MAX];
197      MemoryMappedSegment segment(filename, sizeof(filename));
198      while (proc_maps.Next(&segment)) {
199        if (IsDynamicRTName(segment.filename)) {
200          Report(
201              "Your application is linked against "
202              "incompatible ASan runtimes.\n");
203          Die();
204        }
205      }
206      __asan_rt_version = ASAN_RT_VERSION_STATIC;
207    } else if (__asan_rt_version != ASAN_RT_VERSION_STATIC) {
208      ReportIncompatibleRT();
209    }
210  }
211}
212#  endif  // SANITIZER_ANDROID
213
214#  if ASAN_INTERCEPT_SWAPCONTEXT
215constexpr u32 kAsanContextStackFlagsMagic = 0x51260eea;
216
217static int HashContextStack(const ucontext_t &ucp) {
218  MurMur2Hash64Builder hash(kAsanContextStackFlagsMagic);
219  hash.add(reinterpret_cast<uptr>(ucp.uc_stack.ss_sp));
220  hash.add(ucp.uc_stack.ss_size);
221  return static_cast<int>(hash.get());
222}
223
224void SignContextStack(void *context) {
225  ucontext_t *ucp = reinterpret_cast<ucontext_t *>(context);
226  ucp->uc_stack.ss_flags = HashContextStack(*ucp);
227}
228
229void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
230  const ucontext_t *ucp = reinterpret_cast<const ucontext_t *>(context);
231  if (HashContextStack(*ucp) == ucp->uc_stack.ss_flags) {
232    *stack = reinterpret_cast<uptr>(ucp->uc_stack.ss_sp);
233    *ssize = ucp->uc_stack.ss_size;
234    return;
235  }
236  *stack = 0;
237  *ssize = 0;
238}
239#  endif  // ASAN_INTERCEPT_SWAPCONTEXT
240
241void *AsanDlSymNext(const char *sym) { return dlsym(RTLD_NEXT, sym); }
242
243bool HandleDlopenInit() {
244  // Not supported on this platform.
245  static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
246                "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
247  return false;
248}
249
250}  // namespace __asan
251
252#endif  // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||
253        // SANITIZER_SOLARIS
254