1//===-- asan_rtems.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 a part of AddressSanitizer, an address sanity checker.
9//
10// RTEMS-specific details.
11//===----------------------------------------------------------------------===//
12
13#include "sanitizer_common/sanitizer_rtems.h"
14#if SANITIZER_RTEMS
15
16#include "asan_internal.h"
17#include "asan_interceptors.h"
18#include "asan_mapping.h"
19#include "asan_poisoning.h"
20#include "asan_report.h"
21#include "asan_stack.h"
22#include "sanitizer_common/sanitizer_common.h"
23#include "sanitizer_common/sanitizer_libc.h"
24
25#include <pthread.h>
26#include <stdlib.h>
27
28namespace __asan {
29
30static void ResetShadowMemory() {
31  uptr shadow_start = SHADOW_OFFSET;
32  uptr shadow_end = MEM_TO_SHADOW(kMyriadMemoryEnd32);
33  uptr gap_start = MEM_TO_SHADOW(shadow_start);
34  uptr gap_end = MEM_TO_SHADOW(shadow_end);
35
36  REAL(memset)((void *)shadow_start, 0, shadow_end - shadow_start);
37  REAL(memset)((void *)gap_start, kAsanShadowGap, gap_end - gap_start);
38}
39
40void InitializeShadowMemory() {
41  kHighMemEnd = 0;
42  kMidMemBeg =  0;
43  kMidMemEnd =  0;
44
45  ResetShadowMemory();
46}
47
48void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
49  UNIMPLEMENTED();
50}
51
52void AsanCheckDynamicRTPrereqs() {}
53void AsanCheckIncompatibleRT() {}
54void InitializeAsanInterceptors() {}
55void InitializePlatformInterceptors() {}
56void InitializePlatformExceptionHandlers() {}
57
58// RTEMS only support static linking; it sufficies to return with no
59// error.
60void *AsanDoesNotSupportStaticLinkage() { return nullptr; }
61
62void AsanOnDeadlySignal(int signo, void *siginfo, void *context) {
63  UNIMPLEMENTED();
64}
65
66void EarlyInit() {
67  // Provide early initialization of shadow memory so that
68  // instrumented code running before full initialzation will not
69  // report spurious errors.
70  ResetShadowMemory();
71}
72
73// We can use a plain thread_local variable for TSD.
74static thread_local void *per_thread;
75
76void *AsanTSDGet() { return per_thread; }
77
78void AsanTSDSet(void *tsd) { per_thread = tsd; }
79
80// There's no initialization needed, and the passed-in destructor
81// will never be called.  Instead, our own thread destruction hook
82// (below) will call AsanThread::TSDDtor directly.
83void AsanTSDInit(void (*destructor)(void *tsd)) {
84  DCHECK(destructor == &PlatformTSDDtor);
85}
86
87void PlatformTSDDtor(void *tsd) { UNREACHABLE(__func__); }
88
89//
90// Thread registration.  We provide an API similar to the Fushia port.
91//
92
93struct AsanThread::InitOptions {
94  uptr stack_bottom, stack_size, tls_bottom, tls_size;
95};
96
97// Shared setup between thread creation and startup for the initial thread.
98static AsanThread *CreateAsanThread(StackTrace *stack, u32 parent_tid,
99                                    uptr user_id, bool detached,
100                                    uptr stack_bottom, uptr stack_size,
101                                    uptr tls_bottom, uptr tls_size) {
102  // In lieu of AsanThread::Create.
103  AsanThread *thread = (AsanThread *)MmapOrDie(sizeof(AsanThread), __func__);
104  AsanThreadContext::CreateThreadContextArgs args = {thread, stack};
105  asanThreadRegistry().CreateThread(user_id, detached, parent_tid, &args);
106
107  // On other systems, AsanThread::Init() is called from the new
108  // thread itself.  But on RTEMS we already know the stack address
109  // range beforehand, so we can do most of the setup right now.
110  const AsanThread::InitOptions options = {stack_bottom, stack_size,
111                                           tls_bottom, tls_size};
112  thread->Init(&options);
113  return thread;
114}
115
116// This gets the same arguments passed to Init by CreateAsanThread, above.
117// We're in the creator thread before the new thread is actually started, but
118// its stack and tls address range are already known.
119void AsanThread::SetThreadStackAndTls(const AsanThread::InitOptions *options) {
120  DCHECK_NE(GetCurrentThread(), this);
121  DCHECK_NE(GetCurrentThread(), nullptr);
122  CHECK_NE(options->stack_bottom, 0);
123  CHECK_NE(options->stack_size, 0);
124  stack_bottom_ = options->stack_bottom;
125  stack_top_ = options->stack_bottom + options->stack_size;
126  tls_begin_ = options->tls_bottom;
127  tls_end_ = options->tls_bottom + options->tls_size;
128}
129
130// Called by __asan::AsanInitInternal (asan_rtl.c).  Unlike other ports, the
131// main thread on RTEMS does not require special treatment; its AsanThread is
132// already created by the provided hooks.  This function simply looks up and
133// returns the created thread.
134AsanThread *CreateMainThread() {
135  return GetThreadContextByTidLocked(0)->thread;
136}
137
138// This is called before each thread creation is attempted.  So, in
139// its first call, the calling thread is the initial and sole thread.
140static void *BeforeThreadCreateHook(uptr user_id, bool detached,
141                                    uptr stack_bottom, uptr stack_size,
142                                    uptr tls_bottom, uptr tls_size) {
143  EnsureMainThreadIDIsCorrect();
144  // Strict init-order checking is thread-hostile.
145  if (flags()->strict_init_order) StopInitOrderChecking();
146
147  GET_STACK_TRACE_THREAD;
148  u32 parent_tid = GetCurrentTidOrInvalid();
149
150  return CreateAsanThread(&stack, parent_tid, user_id, detached,
151                          stack_bottom, stack_size, tls_bottom, tls_size);
152}
153
154// This is called after creating a new thread (in the creating thread),
155// with the pointer returned by BeforeThreadCreateHook (above).
156static void ThreadCreateHook(void *hook, bool aborted) {
157  AsanThread *thread = static_cast<AsanThread *>(hook);
158  if (!aborted) {
159    // The thread was created successfully.
160    // ThreadStartHook is already running in the new thread.
161  } else {
162    // The thread wasn't created after all.
163    // Clean up everything we set up in BeforeThreadCreateHook.
164    asanThreadRegistry().FinishThread(thread->tid());
165    UnmapOrDie(thread, sizeof(AsanThread));
166  }
167}
168
169// This is called (1) in the newly-created thread before it runs anything else,
170// with the pointer returned by BeforeThreadCreateHook (above).  (2) before a
171// thread restart.
172static void ThreadStartHook(void *hook, uptr os_id) {
173  if (!hook)
174    return;
175
176  AsanThread *thread = static_cast<AsanThread *>(hook);
177  SetCurrentThread(thread);
178
179  ThreadStatus status =
180      asanThreadRegistry().GetThreadLocked(thread->tid())->status;
181  DCHECK(status == ThreadStatusCreated || status == ThreadStatusRunning);
182  // Determine whether we are starting or restarting the thread.
183  if (status == ThreadStatusCreated)
184    // In lieu of AsanThread::ThreadStart.
185    asanThreadRegistry().StartThread(thread->tid(), os_id,
186                                     /*workerthread*/ false, nullptr);
187  else {
188    // In a thread restart, a thread may resume execution at an
189    // arbitrary function entry point, with its stack and TLS state
190    // reset.  We unpoison the stack in that case.
191    PoisonShadow(thread->stack_bottom(), thread->stack_size(), 0);
192  }
193}
194
195// Each thread runs this just before it exits,
196// with the pointer returned by BeforeThreadCreateHook (above).
197// All per-thread destructors have already been called.
198static void ThreadExitHook(void *hook, uptr os_id) {
199  AsanThread *thread = static_cast<AsanThread *>(hook);
200  if (thread)
201    AsanThread::TSDDtor(thread->context());
202}
203
204static void HandleExit() {
205  // Disable ASan by setting it to uninitialized.  Also reset the
206  // shadow memory to avoid reporting errors after the run-time has
207  // been desroyed.
208  if (asan_inited) {
209    asan_inited = false;
210    ResetShadowMemory();
211  }
212}
213
214}  // namespace __asan
215
216// These are declared (in extern "C") by <some_path/sanitizer.h>.
217// The system runtime will call our definitions directly.
218
219extern "C" {
220void __sanitizer_early_init() {
221  __asan::EarlyInit();
222}
223
224void *__sanitizer_before_thread_create_hook(uptr thread, bool detached,
225                                            const char *name,
226                                            void *stack_base, size_t stack_size,
227                                            void *tls_base, size_t tls_size) {
228  return __asan::BeforeThreadCreateHook(
229      thread, detached,
230      reinterpret_cast<uptr>(stack_base), stack_size,
231      reinterpret_cast<uptr>(tls_base), tls_size);
232}
233
234void __sanitizer_thread_create_hook(void *handle, uptr thread, int status) {
235  __asan::ThreadCreateHook(handle, status != 0);
236}
237
238void __sanitizer_thread_start_hook(void *handle, uptr self) {
239  __asan::ThreadStartHook(handle, self);
240}
241
242void __sanitizer_thread_exit_hook(void *handle, uptr self) {
243  __asan::ThreadExitHook(handle, self);
244}
245
246void __sanitizer_exit() {
247  __asan::HandleExit();
248}
249}  // "C"
250
251#endif  // SANITIZER_RTEMS
252