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/ModuleList.h"
16 #include "lldb/Core/RegularExpression.h"
17 #include "lldb/Core/PluginInterface.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Stream.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/ValueObject.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Symbol/Symbol.h"
24 #include "lldb/Symbol/SymbolContext.h"
25 #include "lldb/Target/InstrumentationRuntimeStopInfo.h"
26 #include "lldb/Target/StopInfo.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 lldb::InstrumentationRuntimeSP
CreateInstance(const lldb::ProcessSP & process_sp)34 AddressSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp)
35 {
36     return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));
37 }
38 
39 void
Initialize()40 AddressSanitizerRuntime::Initialize()
41 {
42     PluginManager::RegisterPlugin (GetPluginNameStatic(),
43                                    "AddressSanitizer instrumentation runtime plugin.",
44                                    CreateInstance,
45                                    GetTypeStatic);
46 }
47 
48 void
Terminate()49 AddressSanitizerRuntime::Terminate()
50 {
51     PluginManager::UnregisterPlugin (CreateInstance);
52 }
53 
54 lldb_private::ConstString
GetPluginNameStatic()55 AddressSanitizerRuntime::GetPluginNameStatic()
56 {
57     return ConstString("AddressSanitizer");
58 }
59 
60 lldb::InstrumentationRuntimeType
GetTypeStatic()61 AddressSanitizerRuntime::GetTypeStatic()
62 {
63     return eInstrumentationRuntimeTypeAddressSanitizer;
64 }
65 
AddressSanitizerRuntime(const ProcessSP & process_sp)66 AddressSanitizerRuntime::AddressSanitizerRuntime(const ProcessSP &process_sp) :
67     m_is_active(false),
68     m_runtime_module(),
69     m_process(process_sp),
70     m_breakpoint_id(0)
71 {
72 }
73 
~AddressSanitizerRuntime()74 AddressSanitizerRuntime::~AddressSanitizerRuntime()
75 {
76     Deactivate();
77 }
78 
ModuleContainsASanRuntime(Module * module)79 bool ModuleContainsASanRuntime(Module * module)
80 {
81     SymbolContextList sc_list;
82     const bool include_symbols = true;
83     const bool append = true;
84     const bool include_inlines = true;
85 
86     size_t num_matches = module->FindFunctions(ConstString("__asan_get_alloc_stack"), NULL, eFunctionNameTypeAuto, include_symbols, include_inlines, append, sc_list);
87 
88     return num_matches > 0;
89 }
90 
91 void
ModulesDidLoad(lldb_private::ModuleList & module_list)92 AddressSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list)
93 {
94     if (IsActive())
95         return;
96 
97     if (m_runtime_module) {
98         Activate();
99         return;
100     }
101 
102     Mutex::Locker modules_locker(module_list.GetMutex());
103     const size_t num_modules = module_list.GetSize();
104     for (size_t i = 0; i < num_modules; ++i)
105     {
106         Module *module_pointer = module_list.GetModulePointerAtIndexUnlocked(i);
107         const FileSpec & file_spec = module_pointer->GetFileSpec();
108         if (! file_spec)
109             continue;
110 
111         static RegularExpression g_asan_runtime_regex("libclang_rt.asan_(.*)_dynamic\\.dylib");
112         if (g_asan_runtime_regex.Execute (file_spec.GetFilename().GetCString()) || module_pointer->IsExecutable())
113         {
114             if (ModuleContainsASanRuntime(module_pointer))
115             {
116                 m_runtime_module = module_pointer->shared_from_this();
117                 Activate();
118                 return;
119             }
120         }
121     }
122 }
123 
124 bool
IsActive()125 AddressSanitizerRuntime::IsActive()
126 {
127     return m_is_active;
128 }
129 
130 #define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000
131 
132 const char *
133 address_sanitizer_retrieve_report_data_command = R"(
134 int __asan_report_present();
135 void *__asan_get_report_pc();
136 void *__asan_get_report_bp();
137 void *__asan_get_report_sp();
138 void *__asan_get_report_address();
139 const char *__asan_get_report_description();
140 int __asan_get_report_access_type();
141 size_t __asan_get_report_access_size();
142 struct {
143     int present;
144     int access_type;
145     void *pc;
146     void *bp;
147     void *sp;
148     void *address;
149     size_t access_size;
150     const char *description;
151 } t;
152 
153 t.present = __asan_report_present();
154 t.access_type = __asan_get_report_access_type();
155 t.pc = __asan_get_report_pc();
156 t.bp = __asan_get_report_bp();
157 t.sp = __asan_get_report_sp();
158 t.address = __asan_get_report_address();
159 t.access_size = __asan_get_report_access_size();
160 t.description = __asan_get_report_description();
161 t
162 )";
163 
164 StructuredData::ObjectSP
RetrieveReportData()165 AddressSanitizerRuntime::RetrieveReportData()
166 {
167     ThreadSP thread_sp = m_process->GetThreadList().GetSelectedThread();
168     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
169 
170     if (!frame_sp)
171         return StructuredData::ObjectSP();
172 
173     EvaluateExpressionOptions options;
174     options.SetUnwindOnError(true);
175     options.SetTryAllThreads(true);
176     options.SetStopOthers(true);
177     options.SetIgnoreBreakpoints(true);
178     options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC);
179 
180     ValueObjectSP return_value_sp;
181     if (m_process->GetTarget().EvaluateExpression(address_sanitizer_retrieve_report_data_command, frame_sp.get(), return_value_sp, options) != eExpressionCompleted)
182         return StructuredData::ObjectSP();
183 
184     int present = return_value_sp->GetValueForExpressionPath(".present")->GetValueAsUnsigned(0);
185     if (present != 1)
186         return StructuredData::ObjectSP();
187 
188     addr_t pc = return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
189     /* commented out because rdar://problem/18533301
190     addr_t bp = return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
191     addr_t sp = return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
192     */
193     addr_t address = return_value_sp->GetValueForExpressionPath(".address")->GetValueAsUnsigned(0);
194     addr_t access_type = return_value_sp->GetValueForExpressionPath(".access_type")->GetValueAsUnsigned(0);
195     addr_t access_size = return_value_sp->GetValueForExpressionPath(".access_size")->GetValueAsUnsigned(0);
196     addr_t description_ptr = return_value_sp->GetValueForExpressionPath(".description")->GetValueAsUnsigned(0);
197     std::string description;
198     Error error;
199     m_process->ReadCStringFromMemory(description_ptr, description, error);
200 
201     StructuredData::Dictionary *dict = new StructuredData::Dictionary();
202     dict->AddStringItem("instrumentation_class", "AddressSanitizer");
203     dict->AddStringItem("stop_type", "fatal_error");
204     dict->AddIntegerItem("pc", pc);
205     /* commented out because rdar://problem/18533301
206     dict->AddIntegerItem("bp", bp);
207     dict->AddIntegerItem("sp", sp);
208     */
209     dict->AddIntegerItem("address", address);
210     dict->AddIntegerItem("access_type", access_type);
211     dict->AddIntegerItem("access_size", access_size);
212     dict->AddStringItem("description", description);
213 
214     return StructuredData::ObjectSP(dict);
215 }
216 
217 std::string
FormatDescription(StructuredData::ObjectSP report)218 AddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report)
219 {
220     std::string description = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue();
221     if (description == "heap-use-after-free") {
222         return "Use of deallocated memory detected";
223     } else if (description == "heap-buffer-overflow") {
224         return "Heap buffer overflow detected";
225     } else if (description == "stack-buffer-underflow") {
226         return "Stack buffer underflow detected";
227     } else if (description == "initialization-order-fiasco") {
228         return "Initialization order problem detected";
229     } else if (description == "stack-buffer-overflow") {
230         return "Stack buffer overflow detected";
231     } else if (description == "stack-use-after-return") {
232         return "Use of returned stack memory detected";
233     } else if (description == "use-after-poison") {
234         return "Use of poisoned memory detected";
235     } else if (description == "container-overflow") {
236         return "Container overflow detected";
237     } else if (description == "stack-use-after-scope") {
238         return "Use of out-of-scope stack memory detected";
239     } else if (description == "global-buffer-overflow") {
240         return "Global buffer overflow detected";
241     } else if (description == "unknown-crash") {
242         return "Invalid memory access detected";
243     }
244 
245     // for unknown report codes just show the code
246     return description;
247 }
248 
249 bool
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)250 AddressSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id)
251 {
252     assert (baton && "null baton");
253     if (!baton)
254         return false;
255 
256     AddressSanitizerRuntime *const instance = static_cast<AddressSanitizerRuntime*>(baton);
257 
258     StructuredData::ObjectSP report = instance->RetrieveReportData();
259     std::string description;
260     if (report) {
261         description = instance->FormatDescription(report);
262     }
263     ThreadSP thread = context->exe_ctx_ref.GetThreadSP();
264     thread->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread, description.c_str(), report));
265 
266     if (instance->m_process)
267     {
268         StreamFileSP stream_sp (instance->m_process->GetTarget().GetDebugger().GetOutputFile());
269         if (stream_sp)
270         {
271             stream_sp->Printf ("AddressSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n");
272         }
273     }
274     // Return true to stop the target, false to just let the target run.
275     return true;
276 }
277 
278 void
Activate()279 AddressSanitizerRuntime::Activate()
280 {
281     if (m_is_active)
282         return;
283 
284     ConstString symbol_name ("__asan::AsanDie()");
285     const Symbol *symbol = m_runtime_module->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode);
286 
287     if (symbol == NULL)
288         return;
289 
290     if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
291         return;
292 
293     Target &target = m_process->GetTarget();
294     addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
295 
296     if (symbol_address == LLDB_INVALID_ADDRESS)
297         return;
298 
299     bool internal = true;
300     bool hardware = false;
301     Breakpoint *breakpoint = m_process->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get();
302     breakpoint->SetCallback (AddressSanitizerRuntime::NotifyBreakpointHit, this, true);
303     breakpoint->SetBreakpointKind ("address-sanitizer-report");
304     m_breakpoint_id = breakpoint->GetID();
305 
306     if (m_process)
307     {
308         StreamFileSP stream_sp (m_process->GetTarget().GetDebugger().GetOutputFile());
309         if (stream_sp)
310         {
311                 stream_sp->Printf ("AddressSanitizer debugger support is active. Memory error breakpoint has been installed and you can now use the 'memory history' command.\n");
312         }
313     }
314 
315     m_is_active = true;
316 }
317 
318 void
Deactivate()319 AddressSanitizerRuntime::Deactivate()
320 {
321     if (m_breakpoint_id != LLDB_INVALID_BREAK_ID)
322     {
323         m_process->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
324         m_breakpoint_id = LLDB_INVALID_BREAK_ID;
325     }
326     m_is_active = false;
327 }
328