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