1 //===-- AddressSanitizerRuntime.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "AddressSanitizerRuntime.h"
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"
29 #include "llvm/ADT/StringSwitch.h"
32 using namespace lldb_private;
34 lldb::InstrumentationRuntimeSP
35 AddressSanitizerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
36 return InstrumentationRuntimeSP(new AddressSanitizerRuntime(process_sp));
39 void AddressSanitizerRuntime::Initialize() {
40 PluginManager::RegisterPlugin(
41 GetPluginNameStatic(), "AddressSanitizer instrumentation runtime plugin.",
42 CreateInstance, GetTypeStatic);
45 void AddressSanitizerRuntime::Terminate() {
46 PluginManager::UnregisterPlugin(CreateInstance);
49 lldb_private::ConstString AddressSanitizerRuntime::GetPluginNameStatic() {
50 return ConstString("AddressSanitizer");
53 lldb::InstrumentationRuntimeType AddressSanitizerRuntime::GetTypeStatic() {
54 return eInstrumentationRuntimeTypeAddressSanitizer;
57 AddressSanitizerRuntime::~AddressSanitizerRuntime() { Deactivate(); }
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"));
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);
72 return symbol != nullptr;
75 static constexpr std::chrono::seconds g_retrieve_report_data_function_timeout(2);
76 const char *address_sanitizer_retrieve_report_data_prefix = R"(
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();
90 const char *address_sanitizer_retrieve_report_data_command = R"(
99 const char *description;
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();
113 StructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() {
114 ProcessSP process_sp = GetProcessSP();
116 return StructuredData::ObjectSP();
119 process_sp->GetThreadList().GetExpressionExecutionThread();
120 StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
123 return StructuredData::ObjectSP();
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);
135 ValueObjectSP return_value_sp;
136 ExecutionContext exe_ctx;
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();
149 int present = return_value_sp->GetValueForExpressionPath(".present")
150 ->GetValueAsUnsigned(0);
152 return StructuredData::ObjectSP();
155 return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
156 /* commented out because rdar://problem/18533301
158 return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
160 return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
162 addr_t address = return_value_sp->GetValueForExpressionPath(".address")
163 ->GetValueAsUnsigned(0);
165 return_value_sp->GetValueForExpressionPath(".access_type")
166 ->GetValueAsUnsigned(0);
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;
175 process_sp->ReadCStringFromMemory(description_ptr, description, error);
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);
185 dict->AddIntegerItem("address", address);
186 dict->AddIntegerItem("access_type", access_type);
187 dict->AddIntegerItem("access_size", access_size);
188 dict->AddStringItem("description", description);
190 return StructuredData::ObjectSP(dict);
194 AddressSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) {
195 std::string description = report->GetAsDictionary()
196 ->GetValueForKey("description")
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")
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);
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");
247 AddressSanitizerRuntime *const instance =
248 static_cast<AddressSanitizerRuntime *>(baton);
250 StructuredData::ObjectSP report = instance->RetrieveReportData();
251 std::string description;
253 description = instance->FormatDescription(report);
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();
260 thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::
261 CreateStopReasonWithInstrumentationData(
262 *thread_sp, description, report));
264 StreamFileSP stream_sp(
265 process_sp->GetTarget().GetDebugger().GetOutputFile());
267 stream_sp->Printf("AddressSanitizer report breakpoint hit. Use 'thread "
268 "info -s' to get extended information about the "
271 return true; // Return true to stop the target
273 return false; // Let target run
276 void AddressSanitizerRuntime::Activate() {
280 ProcessSP process_sp = GetProcessSP();
284 ConstString symbol_name("__asan::AsanDie()");
285 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
286 symbol_name, eSymbolTypeCode);
291 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
294 Target &target = process_sp->GetTarget();
295 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
297 if (symbol_address == LLDB_INVALID_ADDRESS)
300 bool internal = true;
301 bool hardware = false;
302 Breakpoint *breakpoint =
303 process_sp->GetTarget()
304 .CreateBreakpoint(symbol_address, internal, hardware)
306 breakpoint->SetCallback(AddressSanitizerRuntime::NotifyBreakpointHit, this,
308 breakpoint->SetBreakpointKind("address-sanitizer-report");
309 SetBreakpointID(breakpoint->GetID());
311 StreamFileSP stream_sp(process_sp->GetTarget().GetDebugger().GetOutputFile());
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");
321 void AddressSanitizerRuntime::Deactivate() {
322 if (GetBreakpointID() != LLDB_INVALID_BREAK_ID) {
323 ProcessSP process_sp = GetProcessSP();
325 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
326 SetBreakpointID(LLDB_INVALID_BREAK_ID);