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