ASanRuntime.cpp revision 360784
1//===-- ASanRuntime.cpp -----------------------------------------*- C++ -*-===//
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#include "ASanRuntime.h"
10
11#include "lldb/Breakpoint/StoppointCallbackContext.h"
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/Module.h"
14#include "lldb/Core/PluginInterface.h"
15#include "lldb/Core/PluginManager.h"
16#include "lldb/Core/StreamFile.h"
17#include "lldb/Core/ValueObject.h"
18#include "lldb/Expression/UserExpression.h"
19#include "lldb/Interpreter/CommandReturnObject.h"
20#include "lldb/Symbol/Symbol.h"
21#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
22#include "lldb/Target/StopInfo.h"
23#include "lldb/Target/Target.h"
24#include "lldb/Target/Thread.h"
25#include "lldb/Utility/RegularExpression.h"
26#include "lldb/Utility/Stream.h"
27
28#include "llvm/ADT/StringSwitch.h"
29
30using namespace lldb;
31using namespace lldb_private;
32
33lldb::InstrumentationRuntimeSP
34AddressSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
35  return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));
36}
37
38void AddressSanitizerRuntime::Initialize() {
39  PluginManager::RegisterPlugin(
40      GetPluginNameStatic(), "AddressSanitizer instrumentation runtime plugin.",
41      CreateInstance, GetTypeStatic);
42}
43
44void AddressSanitizerRuntime::Terminate() {
45  PluginManager::UnregisterPlugin(CreateInstance);
46}
47
48lldb_private::ConstString AddressSanitizerRuntime::GetPluginNameStatic() {
49  return ConstString("AddressSanitizer");
50}
51
52lldb::InstrumentationRuntimeType AddressSanitizerRuntime::GetTypeStatic() {
53  return eInstrumentationRuntimeTypeAddressSanitizer;
54}
55
56AddressSanitizerRuntime::~AddressSanitizerRuntime() { Deactivate(); }
57
58const RegularExpression &
59AddressSanitizerRuntime::GetPatternForRuntimeLibrary() {
60  // FIXME: This shouldn't include the "dylib" suffix.
61  static RegularExpression regex(
62      llvm::StringRef("libclang_rt.asan_(.*)_dynamic\\.dylib"));
63  return regex;
64}
65
66bool AddressSanitizerRuntime::CheckIfRuntimeIsValid(
67    const lldb::ModuleSP module_sp) {
68  const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
69      ConstString("__asan_get_alloc_stack"), lldb::eSymbolTypeAny);
70
71  return symbol != nullptr;
72}
73
74const char *address_sanitizer_retrieve_report_data_prefix = R"(
75extern "C"
76{
77int __asan_report_present();
78void *__asan_get_report_pc();
79void *__asan_get_report_bp();
80void *__asan_get_report_sp();
81void *__asan_get_report_address();
82const char *__asan_get_report_description();
83int __asan_get_report_access_type();
84size_t __asan_get_report_access_size();
85}
86)";
87
88const char *address_sanitizer_retrieve_report_data_command = R"(
89struct {
90    int present;
91    int access_type;
92    void *pc;
93    void *bp;
94    void *sp;
95    void *address;
96    size_t access_size;
97    const char *description;
98} t;
99
100t.present = __asan_report_present();
101t.access_type = __asan_get_report_access_type();
102t.pc = __asan_get_report_pc();
103t.bp = __asan_get_report_bp();
104t.sp = __asan_get_report_sp();
105t.address = __asan_get_report_address();
106t.access_size = __asan_get_report_access_size();
107t.description = __asan_get_report_description();
108t
109)";
110
111StructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() {
112  ProcessSP process_sp = GetProcessSP();
113  if (!process_sp)
114    return StructuredData::ObjectSP();
115
116  ThreadSP thread_sp =
117      process_sp->GetThreadList().GetExpressionExecutionThread();
118  StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
119
120  if (!frame_sp)
121    return StructuredData::ObjectSP();
122
123  EvaluateExpressionOptions options;
124  options.SetUnwindOnError(true);
125  options.SetTryAllThreads(true);
126  options.SetStopOthers(true);
127  options.SetIgnoreBreakpoints(true);
128  options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
129  options.SetPrefix(address_sanitizer_retrieve_report_data_prefix);
130  options.SetAutoApplyFixIts(false);
131  options.SetLanguage(eLanguageTypeObjC_plus_plus);
132
133  ValueObjectSP return_value_sp;
134  ExecutionContext exe_ctx;
135  Status eval_error;
136  frame_sp->CalculateExecutionContext(exe_ctx);
137  ExpressionResults result = UserExpression::Evaluate(
138      exe_ctx, options, address_sanitizer_retrieve_report_data_command, "",
139      return_value_sp, eval_error);
140  if (result != eExpressionCompleted) {
141    process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf(
142        "Warning: Cannot evaluate AddressSanitizer expression:\n%s\n",
143        eval_error.AsCString());
144    return StructuredData::ObjectSP();
145  }
146
147  int present = return_value_sp->GetValueForExpressionPath(".present")
148                    ->GetValueAsUnsigned(0);
149  if (present != 1)
150    return StructuredData::ObjectSP();
151
152  addr_t pc =
153      return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
154  /* commented out because rdar://problem/18533301
155  addr_t bp =
156  return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
157  addr_t sp =
158  return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
159  */
160  addr_t address = return_value_sp->GetValueForExpressionPath(".address")
161                       ->GetValueAsUnsigned(0);
162  addr_t access_type =
163      return_value_sp->GetValueForExpressionPath(".access_type")
164          ->GetValueAsUnsigned(0);
165  addr_t access_size =
166      return_value_sp->GetValueForExpressionPath(".access_size")
167          ->GetValueAsUnsigned(0);
168  addr_t description_ptr =
169      return_value_sp->GetValueForExpressionPath(".description")
170          ->GetValueAsUnsigned(0);
171  std::string description;
172  Status error;
173  process_sp->ReadCStringFromMemory(description_ptr, description, error);
174
175  StructuredData::Dictionary *dict = new StructuredData::Dictionary();
176  dict->AddStringItem("instrumentation_class", "AddressSanitizer");
177  dict->AddStringItem("stop_type", "fatal_error");
178  dict->AddIntegerItem("pc", pc);
179  /* commented out because rdar://problem/18533301
180  dict->AddIntegerItem("bp", bp);
181  dict->AddIntegerItem("sp", sp);
182  */
183  dict->AddIntegerItem("address", address);
184  dict->AddIntegerItem("access_type", access_type);
185  dict->AddIntegerItem("access_size", access_size);
186  dict->AddStringItem("description", description);
187
188  return StructuredData::ObjectSP(dict);
189}
190
191std::string
192AddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {
193  std::string description = report->GetAsDictionary()
194                                ->GetValueForKey("description")
195                                ->GetAsString()
196                                ->GetValue();
197  return llvm::StringSwitch<std::string>(description)
198      .Case("heap-use-after-free", "Use of deallocated memory")
199      .Case("heap-buffer-overflow", "Heap buffer overflow")
200      .Case("stack-buffer-underflow", "Stack buffer underflow")
201      .Case("initialization-order-fiasco", "Initialization order problem")
202      .Case("stack-buffer-overflow", "Stack buffer overflow")
203      .Case("stack-use-after-return", "Use of stack memory after return")
204      .Case("use-after-poison", "Use of poisoned memory")
205      .Case("container-overflow", "Container overflow")
206      .Case("stack-use-after-scope", "Use of out-of-scope stack memory")
207      .Case("global-buffer-overflow", "Global buffer overflow")
208      .Case("unknown-crash", "Invalid memory access")
209      .Case("stack-overflow", "Stack space exhausted")
210      .Case("null-deref", "Dereference of null pointer")
211      .Case("wild-jump", "Jump to non-executable address")
212      .Case("wild-addr-write", "Write through wild pointer")
213      .Case("wild-addr-read", "Read from wild pointer")
214      .Case("wild-addr", "Access through wild pointer")
215      .Case("signal", "Deadly signal")
216      .Case("double-free", "Deallocation of freed memory")
217      .Case("new-delete-type-mismatch",
218            "Deallocation size different from allocation size")
219      .Case("bad-free", "Deallocation of non-allocated memory")
220      .Case("alloc-dealloc-mismatch",
221            "Mismatch between allocation and deallocation APIs")
222      .Case("bad-malloc_usable_size", "Invalid argument to malloc_usable_size")
223      .Case("bad-__sanitizer_get_allocated_size",
224            "Invalid argument to __sanitizer_get_allocated_size")
225      .Case("param-overlap",
226            "Call to function disallowing overlapping memory ranges")
227      .Case("negative-size-param", "Negative size used when accessing memory")
228      .Case("bad-__sanitizer_annotate_contiguous_container",
229            "Invalid argument to __sanitizer_annotate_contiguous_container")
230      .Case("odr-violation", "Symbol defined in multiple translation units")
231      .Case(
232          "invalid-pointer-pair",
233          "Comparison or arithmetic on pointers from different memory regions")
234      // for unknown report codes just show the code
235      .Default("AddressSanitizer detected: " + description);
236}
237
238bool AddressSanitizerRuntime::NotifyBreakpointHit(
239    void *baton, StoppointCallbackContext *context, user_id_t break_id,
240    user_id_t break_loc_id) {
241  assert(baton && "null baton");
242  if (!baton)
243    return false;
244
245  AddressSanitizerRuntime *const instance =
246      static_cast<AddressSanitizerRuntime *>(baton);
247
248  ProcessSP process_sp = instance->GetProcessSP();
249
250  if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
251    return false;
252
253  StructuredData::ObjectSP report = instance->RetrieveReportData();
254  std::string description;
255  if (report) {
256    description = instance->FormatDescription(report);
257  }
258  // Make sure this is the right process
259  if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
260    ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
261    if (thread_sp)
262      thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::
263                                 CreateStopReasonWithInstrumentationData(
264                                     *thread_sp, description, report));
265
266    StreamFileSP stream_sp(
267        process_sp->GetTarget().GetDebugger().GetOutputStreamSP());
268    if (stream_sp) {
269      stream_sp->Printf("AddressSanitizer report breakpoint hit. Use 'thread "
270                        "info -s' to get extended information about the "
271                        "report.\n");
272    }
273    return true; // Return true to stop the target
274  } else
275    return false; // Let target run
276}
277
278void AddressSanitizerRuntime::Activate() {
279  if (IsActive())
280    return;
281
282  ProcessSP process_sp = GetProcessSP();
283  if (!process_sp)
284    return;
285
286  ConstString symbol_name("__asan::AsanDie()");
287  const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
288      symbol_name, eSymbolTypeCode);
289
290  if (symbol == nullptr)
291    return;
292
293  if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
294    return;
295
296  Target &target = process_sp->GetTarget();
297  addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
298
299  if (symbol_address == LLDB_INVALID_ADDRESS)
300    return;
301
302  bool internal = true;
303  bool hardware = false;
304  Breakpoint *breakpoint =
305      process_sp->GetTarget()
306          .CreateBreakpoint(symbol_address, internal, hardware)
307          .get();
308  breakpoint->SetCallback(AddressSanitizerRuntime::NotifyBreakpointHit, this,
309                          true);
310  breakpoint->SetBreakpointKind("address-sanitizer-report");
311  SetBreakpointID(breakpoint->GetID());
312
313  SetActive(true);
314}
315
316void AddressSanitizerRuntime::Deactivate() {
317  if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
318    ProcessSP process_sp = GetProcessSP();
319    if (process_sp) {
320      process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
321      SetBreakpointID(LLDB_INVALID_BREAK_ID);
322    }
323  }
324  SetActive(false);
325}
326