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 =
117       thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
118 
119   if (!frame_sp)
120     return StructuredData::ObjectSP();
121 
122   EvaluateExpressionOptions options;
123   options.SetUnwindOnError(true);
124   options.SetTryAllThreads(true);
125   options.SetStopOthers(true);
126   options.SetIgnoreBreakpoints(true);
127   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
128   options.SetPrefix(address_sanitizer_retrieve_report_data_prefix);
129   options.SetAutoApplyFixIts(false);
130   options.SetLanguage(eLanguageTypeObjC_plus_plus);
131 
132   ValueObjectSP return_value_sp;
133   ExecutionContext exe_ctx;
134   Status eval_error;
135   frame_sp->CalculateExecutionContext(exe_ctx);
136   ExpressionResults result = UserExpression::Evaluate(
137       exe_ctx, options, address_sanitizer_retrieve_report_data_command, "",
138       return_value_sp, eval_error);
139   if (result != eExpressionCompleted) {
140     StreamString ss;
141     ss << "cannot evaluate AddressSanitizer expression:\n";
142     ss << eval_error.AsCString();
143     Debugger::ReportWarning(ss.GetString().str(),
144                             process_sp->GetTarget().GetDebugger().GetID());
145     return StructuredData::ObjectSP();
146   }
147 
148   int present = return_value_sp->GetValueForExpressionPath(".present")
149                     ->GetValueAsUnsigned(0);
150   if (present != 1)
151     return StructuredData::ObjectSP();
152 
153   addr_t pc =
154       return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
155   /* commented out because rdar://problem/18533301
156   addr_t bp =
157   return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
158   addr_t sp =
159   return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
160   */
161   addr_t address = return_value_sp->GetValueForExpressionPath(".address")
162                        ->GetValueAsUnsigned(0);
163   addr_t access_type =
164       return_value_sp->GetValueForExpressionPath(".access_type")
165           ->GetValueAsUnsigned(0);
166   addr_t access_size =
167       return_value_sp->GetValueForExpressionPath(".access_size")
168           ->GetValueAsUnsigned(0);
169   addr_t description_ptr =
170       return_value_sp->GetValueForExpressionPath(".description")
171           ->GetValueAsUnsigned(0);
172   std::string description;
173   Status error;
174   process_sp->ReadCStringFromMemory(description_ptr, description, error);
175 
176   StructuredData::Dictionary *dict = new StructuredData::Dictionary();
177   dict->AddStringItem("instrumentation_class", "AddressSanitizer");
178   dict->AddStringItem("stop_type", "fatal_error");
179   dict->AddIntegerItem("pc", pc);
180   /* commented out because rdar://problem/18533301
181   dict->AddIntegerItem("bp", bp);
182   dict->AddIntegerItem("sp", sp);
183   */
184   dict->AddIntegerItem("address", address);
185   dict->AddIntegerItem("access_type", access_type);
186   dict->AddIntegerItem("access_size", access_size);
187   dict->AddStringItem("description", description);
188 
189   return StructuredData::ObjectSP(dict);
190 }
191 
192 std::string
193 InstrumentationRuntimeASan::FormatDescription(StructuredData::ObjectSP report) {
194   std::string description = std::string(report->GetAsDictionary()
195                                             ->GetValueForKey("description")
196                                             ->GetAsString()
197                                             ->GetValue());
198   return llvm::StringSwitch<std::string>(description)
199       .Case("heap-use-after-free", "Use of deallocated memory")
200       .Case("heap-buffer-overflow", "Heap buffer overflow")
201       .Case("stack-buffer-underflow", "Stack buffer underflow")
202       .Case("initialization-order-fiasco", "Initialization order problem")
203       .Case("stack-buffer-overflow", "Stack buffer overflow")
204       .Case("stack-use-after-return", "Use of stack memory after return")
205       .Case("use-after-poison", "Use of poisoned memory")
206       .Case("container-overflow", "Container overflow")
207       .Case("stack-use-after-scope", "Use of out-of-scope stack memory")
208       .Case("global-buffer-overflow", "Global buffer overflow")
209       .Case("unknown-crash", "Invalid memory access")
210       .Case("stack-overflow", "Stack space exhausted")
211       .Case("null-deref", "Dereference of null pointer")
212       .Case("wild-jump", "Jump to non-executable address")
213       .Case("wild-addr-write", "Write through wild pointer")
214       .Case("wild-addr-read", "Read from wild pointer")
215       .Case("wild-addr", "Access through wild pointer")
216       .Case("signal", "Deadly signal")
217       .Case("double-free", "Deallocation of freed memory")
218       .Case("new-delete-type-mismatch",
219             "Deallocation size different from allocation size")
220       .Case("bad-free", "Deallocation of non-allocated memory")
221       .Case("alloc-dealloc-mismatch",
222             "Mismatch between allocation and deallocation APIs")
223       .Case("bad-malloc_usable_size", "Invalid argument to malloc_usable_size")
224       .Case("bad-__sanitizer_get_allocated_size",
225             "Invalid argument to __sanitizer_get_allocated_size")
226       .Case("param-overlap",
227             "Call to function disallowing overlapping memory ranges")
228       .Case("negative-size-param", "Negative size used when accessing memory")
229       .Case("bad-__sanitizer_annotate_contiguous_container",
230             "Invalid argument to __sanitizer_annotate_contiguous_container")
231       .Case("odr-violation", "Symbol defined in multiple translation units")
232       .Case(
233           "invalid-pointer-pair",
234           "Comparison or arithmetic on pointers from different memory regions")
235       // for unknown report codes just show the code
236       .Default("AddressSanitizer detected: " + description);
237 }
238 
239 bool InstrumentationRuntimeASan::NotifyBreakpointHit(
240     void *baton, StoppointCallbackContext *context, user_id_t break_id,
241     user_id_t break_loc_id) {
242   assert(baton && "null baton");
243   if (!baton)
244     return false;
245 
246   InstrumentationRuntimeASan *const instance =
247       static_cast<InstrumentationRuntimeASan *>(baton);
248 
249   ProcessSP process_sp = instance->GetProcessSP();
250 
251   if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
252     return false;
253 
254   StructuredData::ObjectSP report = instance->RetrieveReportData();
255   std::string description;
256   if (report) {
257     description = instance->FormatDescription(report);
258   }
259   // Make sure this is the right process
260   if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
261     ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
262     if (thread_sp)
263       thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::
264                                  CreateStopReasonWithInstrumentationData(
265                                      *thread_sp, description, report));
266 
267     StreamFileSP stream_sp(
268         process_sp->GetTarget().GetDebugger().GetOutputStreamSP());
269     if (stream_sp) {
270       stream_sp->Printf("AddressSanitizer report breakpoint hit. Use 'thread "
271                         "info -s' to get extended information about the "
272                         "report.\n");
273     }
274     return true; // Return true to stop the target
275   } else
276     return false; // Let target run
277 }
278 
279 void InstrumentationRuntimeASan::Activate() {
280   if (IsActive())
281     return;
282 
283   ProcessSP process_sp = GetProcessSP();
284   if (!process_sp)
285     return;
286 
287   ConstString symbol_name("_ZN6__asanL7AsanDieEv");
288   const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
289       symbol_name, eSymbolTypeCode);
290 
291   if (symbol == nullptr)
292     return;
293 
294   if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
295     return;
296 
297   Target &target = process_sp->GetTarget();
298   addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
299 
300   if (symbol_address == LLDB_INVALID_ADDRESS)
301     return;
302 
303   const bool internal = true;
304   const bool hardware = false;
305   const bool sync = false;
306   Breakpoint *breakpoint =
307       process_sp->GetTarget()
308           .CreateBreakpoint(symbol_address, internal, hardware)
309           .get();
310   breakpoint->SetCallback(InstrumentationRuntimeASan::NotifyBreakpointHit, this,
311                           sync);
312   breakpoint->SetBreakpointKind("address-sanitizer-report");
313   SetBreakpointID(breakpoint->GetID());
314 
315   SetActive(true);
316 }
317 
318 void InstrumentationRuntimeASan::Deactivate() {
319   if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
320     ProcessSP process_sp = GetProcessSP();
321     if (process_sp) {
322       process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
323       SetBreakpointID(LLDB_INVALID_BREAK_ID);
324     }
325   }
326   SetActive(false);
327 }
328