LLDB mainline
InstrumentationRuntimeASan.cpp
Go to the documentation of this file.
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
10
12#include "lldb/Core/Debugger.h"
13#include "lldb/Core/Module.h"
17#include "lldb/Symbol/Symbol.h"
20#include "lldb/Target/Process.h"
21#include "lldb/Target/Target.h"
25
27
28#include "llvm/ADT/StringSwitch.h"
29
30using namespace lldb;
31using namespace lldb_private;
32
34
39
42 GetPluginNameStatic(), "AddressSanitizer instrumentation runtime plugin.",
44}
45
49
53
55
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
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
73extern "C"
74{
75int __asan_report_present();
76void *__asan_get_report_pc();
77void *__asan_get_report_bp();
78void *__asan_get_report_sp();
79void *__asan_get_report_address();
80const char *__asan_get_report_description();
81int __asan_get_report_access_type();
82size_t __asan_get_report_access_size();
83}
84)";
85
87struct {
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
98t.present = __asan_report_present();
99t.access_type = __asan_get_report_access_type();
100t.pc = __asan_get_report_pc();
101t.bp = __asan_get_report_bp();
102t.sp = __asan_get_report_sp();
103t.address = __asan_get_report_address();
104t.access_size = __asan_get_report_access_size();
105t.description = __asan_get_report_description();
106t
107)";
108
110 ProcessSP process_sp = GetProcessSP();
111 if (!process_sp)
113
114 ThreadSP thread_sp =
115 process_sp->GetThreadList().GetExpressionExecutionThread();
116
117 if (!thread_sp)
119
120 StackFrameSP frame_sp =
121 thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
122
123 if (!frame_sp)
125
127 options.SetUnwindOnError(true);
128 options.SetTryAllThreads(true);
129 options.SetStopOthers(true);
130 options.SetIgnoreBreakpoints(true);
131 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
133 options.SetAutoApplyFixIts(false);
135
136 if (auto [m, _] = GetPreferredAsanModule(process_sp->GetTarget()); m) {
137 SymbolContextList sc_list;
138 sc_list.Append(SymbolContext(std::move(m)));
139 options.SetPreferredSymbolContexts(std::move(sc_list));
140 }
141
142 ValueObjectSP return_value_sp;
143 ExecutionContext exe_ctx;
144 frame_sp->CalculateExecutionContext(exe_ctx);
147 return_value_sp);
148 if (result != eExpressionCompleted) {
149 StreamString ss;
150 ss << "cannot evaluate AddressSanitizer expression:\n";
151 if (return_value_sp)
152 ss << return_value_sp->GetError().AsCString();
154 process_sp->GetTarget().GetDebugger().GetID());
156 }
157
158 int present = return_value_sp->GetValueForExpressionPath(".present")
159 ->GetValueAsUnsigned(0);
160 if (present != 1)
162
163 addr_t pc =
164 return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
165 addr_t bp =
166 return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
167 addr_t sp =
168 return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
169 addr_t address = return_value_sp->GetValueForExpressionPath(".address")
170 ->GetValueAsUnsigned(0);
171 addr_t access_type =
172 return_value_sp->GetValueForExpressionPath(".access_type")
173 ->GetValueAsUnsigned(0);
174 addr_t access_size =
175 return_value_sp->GetValueForExpressionPath(".access_size")
176 ->GetValueAsUnsigned(0);
177 addr_t description_ptr =
178 return_value_sp->GetValueForExpressionPath(".description")
179 ->GetValueAsUnsigned(0);
180 std::string description;
182 process_sp->ReadCStringFromMemory(description_ptr, description, error);
183
184 auto dict = std::make_shared<StructuredData::Dictionary>();
185 if (!dict)
187
188 dict->AddStringItem("instrumentation_class", "AddressSanitizer");
189 dict->AddStringItem("stop_type", "fatal_error");
190 dict->AddIntegerItem("pc", pc);
191 dict->AddIntegerItem("bp", bp);
192 dict->AddIntegerItem("sp", sp);
193 dict->AddIntegerItem("address", address);
194 dict->AddIntegerItem("access_type", access_type);
195 dict->AddIntegerItem("access_size", access_size);
196 dict->AddStringItem("description", description);
197
198 return StructuredData::ObjectSP(dict);
199}
200
201static std::string FormatDescription(StructuredData::ObjectSP report) {
202 std::string description = std::string(report->GetAsDictionary()
203 ->GetValueForKey("description")
204 ->GetAsString()
205 ->GetValue());
206 return llvm::StringSwitch<std::string>(description)
207 .Case("heap-use-after-free", "Use of deallocated memory")
208 .Case("heap-buffer-overflow", "Heap buffer overflow")
209 .Case("stack-buffer-underflow", "Stack buffer underflow")
210 .Case("initialization-order-fiasco", "Initialization order problem")
211 .Case("stack-buffer-overflow", "Stack buffer overflow")
212 .Case("stack-use-after-return", "Use of stack memory after return")
213 .Case("use-after-poison", "Use of poisoned memory")
214 .Case("container-overflow", "Container overflow")
215 .Case("stack-use-after-scope", "Use of out-of-scope stack memory")
216 .Case("global-buffer-overflow", "Global buffer overflow")
217 .Case("unknown-crash", "Invalid memory access")
218 .Case("stack-overflow", "Stack space exhausted")
219 .Case("null-deref", "Dereference of null pointer")
220 .Case("wild-jump", "Jump to non-executable address")
221 .Case("wild-addr-write", "Write through wild pointer")
222 .Case("wild-addr-read", "Read from wild pointer")
223 .Case("wild-addr", "Access through wild pointer")
224 .Case("signal", "Deadly signal")
225 .Case("double-free", "Deallocation of freed memory")
226 .Case("new-delete-type-mismatch",
227 "Deallocation size different from allocation size")
228 .Case("bad-free", "Deallocation of non-allocated memory")
229 .Case("alloc-dealloc-mismatch",
230 "Mismatch between allocation and deallocation APIs")
231 .Case("bad-malloc_usable_size", "Invalid argument to malloc_usable_size")
232 .Case("bad-__sanitizer_get_allocated_size",
233 "Invalid argument to __sanitizer_get_allocated_size")
234 .Case("param-overlap",
235 "Call to function disallowing overlapping memory ranges")
236 .Case("negative-size-param", "Negative size used when accessing memory")
237 .Case("bad-__sanitizer_annotate_contiguous_container",
238 "Invalid argument to __sanitizer_annotate_contiguous_container")
239 .Case("odr-violation", "Symbol defined in multiple translation units")
240 .Case(
241 "invalid-pointer-pair",
242 "Comparison or arithmetic on pointers from different memory regions")
243 // for unknown report codes just show the code
244 .Default("AddressSanitizer detected: " + description);
245}
246
248 void *baton, StoppointCallbackContext *context, user_id_t break_id,
249 user_id_t break_loc_id) {
250 assert(baton && "null baton");
251 if (!baton)
252 return false;
253
254 InstrumentationRuntimeASan *const instance =
255 static_cast<InstrumentationRuntimeASan *>(baton);
256
257 ProcessSP process_sp = instance->GetProcessSP();
258
259 // Make sure this is the right process
260 if (!process_sp || process_sp != context->exe_ctx_ref.GetProcessSP())
261 return false;
262
263 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
264 return false;
265
266 StructuredData::ObjectSP report = instance->RetrieveReportData();
267 if (!report || report->GetType() != lldb::eStructuredDataTypeDictionary) {
269 "InstrumentationRuntimeASan::RetrieveReportData() failed");
270 return false;
271 }
272
273 std::string description = FormatDescription(report);
274
275 if (ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP())
276 thread_sp->SetStopInfo(
278 *thread_sp, description, report));
279
280 if (StreamSP stream_sp =
281 process_sp->GetTarget().GetDebugger().GetAsyncOutputStream())
282 stream_sp->Printf("AddressSanitizer report breakpoint hit. Use 'thread "
283 "info -s' to get extended information about the "
284 "report.\n");
285
286 return true; // Return true to stop the target
287}
288
290 if (IsActive())
291 return;
292
293 ProcessSP process_sp = GetProcessSP();
294 if (!process_sp)
295 return;
296
297 ModuleSP module_sp = GetRuntimeModuleSP();
298 if (!module_sp)
299 return;
300
301 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
302 ConstString("_ZN6__asanL7AsanDieEv"), eSymbolTypeCode);
303 if (!symbol)
304 return;
305
306 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
307 return;
308
309 const bool internal = true;
310 const bool hardware = false;
311 Breakpoint *breakpoint =
312 process_sp->GetTarget()
313 .CreateBreakpoint(symbol->GetAddressRef(), internal, hardware)
314 .get();
315 if (!breakpoint)
316 return;
317
318 const bool sync = false;
319
321 sync);
322 breakpoint->SetBreakpointKind("address-sanitizer-report");
323 SetBreakpointID(breakpoint->GetID());
324
325 SetActive(true);
326}
327
329 SetActive(false);
330
332 return;
333
334 if (ProcessSP process_sp = GetProcessSP()) {
335 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
337 }
338}
static llvm::raw_ostream & error(Stream &strm)
static const char * address_sanitizer_retrieve_report_data_command
static const char * address_sanitizer_retrieve_report_data_prefix
static std::string FormatDescription(StructuredData::ObjectSP report)
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_PLUGIN_DEFINE(PluginName)
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition Breakpoint.h:83
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition Breakpoint.h:484
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
A uniqued constant string class.
Definition ConstString.h:40
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
void SetPreferredSymbolContexts(SymbolContextList contexts)
Definition Target.h:370
void SetUnwindOnError(bool unwind=false)
Definition Target.h:402
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:366
void SetPrefix(const char *prefix)
Definition Target.h:391
void SetTryAllThreads(bool try_others=true)
Definition Target.h:435
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:423
void SetStopOthers(bool stop_others=true)
Definition Target.h:439
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:406
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object.
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
static lldb::InstrumentationRuntimeType GetTypeStatic()
static bool NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
InstrumentationRuntimeASan(const lldb::ProcessSP &process_sp)
void Activate() override
Register a breakpoint in the runtime library and perform any other necessary initialization.
static lldb::InstrumentationRuntimeSP CreateInstance(const lldb::ProcessSP &process_sp)
const RegularExpression & GetPatternForRuntimeLibrary() override
Return a regular expression which can be used to identify a valid version of the runtime library.
bool CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp) override
Check whether module_sp corresponds to a valid runtime library.
static lldb::StopInfoSP CreateStopReasonWithInstrumentationData(Thread &thread, std::string description, StructuredData::ObjectSP additional_data)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An error handling class.
Definition Status.h:118
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
Definition Stoppoint.cpp:22
llvm::StringRef GetString() const
std::shared_ptr< Object > ObjectSP
Defines a list of symbol context objects.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
Defines a symbol context baton that can be handed other debug core functions.
bool ValueIsAddress() const
Definition Symbol.cpp:191
Address & GetAddressRef()
Definition Symbol.h:78
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
#define LLDB_INVALID_BREAK_ID
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::tuple< lldb::ModuleSP, HistoryPCType > GetPreferredAsanModule(const Target &target)
On Darwin, if LLDB loaded libclang_rt, it's coming from a locally built compiler-rt,...
Definition Utility.cpp:17
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Stream > StreamSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Process > ProcessSP
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeAddressSanitizer
uint64_t user_id_t
Definition lldb-types.h:83
uint64_t addr_t
Definition lldb-types.h:80
@ eStructuredDataTypeDictionary
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
std::shared_ptr< lldb_private::Module > ModuleSP