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"
20#include "lldb/Symbol/Symbol.h"
23#include "lldb/Target/Target.h"
24#include "lldb/Target/Thread.h"
26#include "lldb/Utility/Stream.h"
27
28#include "llvm/ADT/StringSwitch.h"
29
30using namespace lldb;
31using namespace lldb_private;
32
34
38}
39
42 GetPluginNameStatic(), "AddressSanitizer instrumentation runtime plugin.",
44}
45
48}
49
52}
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 StackFrameSP frame_sp =
117 thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
118
119 if (!frame_sp)
121
123 options.SetUnwindOnError(true);
124 options.SetTryAllThreads(true);
125 options.SetStopOthers(true);
126 options.SetIgnoreBreakpoints(true);
127 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
129 options.SetAutoApplyFixIts(false);
131
132 ValueObjectSP return_value_sp;
133 ExecutionContext exe_ctx;
134 Status eval_error;
135 frame_sp->CalculateExecutionContext(exe_ctx);
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();
144 process_sp->GetTarget().GetDebugger().GetID());
146 }
147
148 int present = return_value_sp->GetValueForExpressionPath(".present")
149 ->GetValueAsUnsigned(0);
150 if (present != 1)
152
153 addr_t pc =
154 return_value_sp->GetValueForExpressionPath(".pc")->GetValueAsUnsigned(0);
155 addr_t bp =
156 return_value_sp->GetValueForExpressionPath(".bp")->GetValueAsUnsigned(0);
157 addr_t sp =
158 return_value_sp->GetValueForExpressionPath(".sp")->GetValueAsUnsigned(0);
159 addr_t address = return_value_sp->GetValueForExpressionPath(".address")
160 ->GetValueAsUnsigned(0);
161 addr_t access_type =
162 return_value_sp->GetValueForExpressionPath(".access_type")
163 ->GetValueAsUnsigned(0);
164 addr_t access_size =
165 return_value_sp->GetValueForExpressionPath(".access_size")
166 ->GetValueAsUnsigned(0);
167 addr_t description_ptr =
168 return_value_sp->GetValueForExpressionPath(".description")
169 ->GetValueAsUnsigned(0);
170 std::string description;
172 process_sp->ReadCStringFromMemory(description_ptr, description, error);
173
175 dict->AddStringItem("instrumentation_class", "AddressSanitizer");
176 dict->AddStringItem("stop_type", "fatal_error");
177 dict->AddIntegerItem("pc", pc);
178 dict->AddIntegerItem("bp", bp);
179 dict->AddIntegerItem("sp", sp);
180 dict->AddIntegerItem("address", address);
181 dict->AddIntegerItem("access_type", access_type);
182 dict->AddIntegerItem("access_size", access_size);
183 dict->AddStringItem("description", description);
184
185 return StructuredData::ObjectSP(dict);
186}
187
188std::string
190 std::string description = std::string(report->GetAsDictionary()
191 ->GetValueForKey("description")
192 ->GetAsString()
193 ->GetValue());
194 return llvm::StringSwitch<std::string>(description)
195 .Case("heap-use-after-free", "Use of deallocated memory")
196 .Case("heap-buffer-overflow", "Heap buffer overflow")
197 .Case("stack-buffer-underflow", "Stack buffer underflow")
198 .Case("initialization-order-fiasco", "Initialization order problem")
199 .Case("stack-buffer-overflow", "Stack buffer overflow")
200 .Case("stack-use-after-return", "Use of stack memory after return")
201 .Case("use-after-poison", "Use of poisoned memory")
202 .Case("container-overflow", "Container overflow")
203 .Case("stack-use-after-scope", "Use of out-of-scope stack memory")
204 .Case("global-buffer-overflow", "Global buffer overflow")
205 .Case("unknown-crash", "Invalid memory access")
206 .Case("stack-overflow", "Stack space exhausted")
207 .Case("null-deref", "Dereference of null pointer")
208 .Case("wild-jump", "Jump to non-executable address")
209 .Case("wild-addr-write", "Write through wild pointer")
210 .Case("wild-addr-read", "Read from wild pointer")
211 .Case("wild-addr", "Access through wild pointer")
212 .Case("signal", "Deadly signal")
213 .Case("double-free", "Deallocation of freed memory")
214 .Case("new-delete-type-mismatch",
215 "Deallocation size different from allocation size")
216 .Case("bad-free", "Deallocation of non-allocated memory")
217 .Case("alloc-dealloc-mismatch",
218 "Mismatch between allocation and deallocation APIs")
219 .Case("bad-malloc_usable_size", "Invalid argument to malloc_usable_size")
220 .Case("bad-__sanitizer_get_allocated_size",
221 "Invalid argument to __sanitizer_get_allocated_size")
222 .Case("param-overlap",
223 "Call to function disallowing overlapping memory ranges")
224 .Case("negative-size-param", "Negative size used when accessing memory")
225 .Case("bad-__sanitizer_annotate_contiguous_container",
226 "Invalid argument to __sanitizer_annotate_contiguous_container")
227 .Case("odr-violation", "Symbol defined in multiple translation units")
228 .Case(
229 "invalid-pointer-pair",
230 "Comparison or arithmetic on pointers from different memory regions")
231 // for unknown report codes just show the code
232 .Default("AddressSanitizer detected: " + description);
233}
234
236 void *baton, StoppointCallbackContext *context, user_id_t break_id,
237 user_id_t break_loc_id) {
238 assert(baton && "null baton");
239 if (!baton)
240 return false;
241
242 InstrumentationRuntimeASan *const instance =
243 static_cast<InstrumentationRuntimeASan *>(baton);
244
245 ProcessSP process_sp = instance->GetProcessSP();
246
247 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
248 return false;
249
250 StructuredData::ObjectSP report = instance->RetrieveReportData();
251 std::string description;
252 if (report) {
253 description = instance->FormatDescription(report);
254 }
255 // Make sure this is the right process
256 if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) {
257 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
258 if (thread_sp)
259 thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::
260 CreateStopReasonWithInstrumentationData(
261 *thread_sp, description, report));
262
263 StreamFileSP stream_sp(
264 process_sp->GetTarget().GetDebugger().GetOutputStreamSP());
265 if (stream_sp) {
266 stream_sp->Printf("AddressSanitizer report breakpoint hit. Use 'thread "
267 "info -s' to get extended information about the "
268 "report.\n");
269 }
270 return true; // Return true to stop the target
271 } else
272 return false; // Let target run
273}
274
276 if (IsActive())
277 return;
278
279 ProcessSP process_sp = GetProcessSP();
280 if (!process_sp)
281 return;
282
283 ConstString symbol_name("_ZN6__asanL7AsanDieEv");
284 const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType(
285 symbol_name, eSymbolTypeCode);
286
287 if (symbol == nullptr)
288 return;
289
290 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
291 return;
292
293 Target &target = process_sp->GetTarget();
294 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
295
296 if (symbol_address == LLDB_INVALID_ADDRESS)
297 return;
298
299 const bool internal = true;
300 const bool hardware = false;
301 const bool sync = false;
302 Breakpoint *breakpoint =
303 process_sp->GetTarget()
304 .CreateBreakpoint(symbol_address, internal, hardware)
305 .get();
307 sync);
308 breakpoint->SetBreakpointKind("address-sanitizer-report");
309 SetBreakpointID(breakpoint->GetID());
310
311 SetActive(true);
312}
313
316 ProcessSP process_sp = GetProcessSP();
317 if (process_sp) {
318 process_sp->GetTarget().RemoveBreakpointByID(GetBreakpointID());
320 }
321 }
322 SetActive(false);
323}
static llvm::raw_ostream & error(Stream &strm)
const char * address_sanitizer_retrieve_report_data_command
const char * address_sanitizer_retrieve_report_data_prefix
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition: Address.cpp:368
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:345
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:81
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:452
Target & GetTarget()
Accessor for the breakpoint Target.
Definition: Breakpoint.h:463
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:413
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.
Definition: Debugger.cpp:1532
void SetLanguage(lldb::LanguageType language)
Definition: Target.h:313
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:332
void SetPrefix(const char *prefix)
Definition: Target.h:321
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:365
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:353
void SetStopOthers(bool stop_others=true)
Definition: Target.h:369
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:336
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)
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)
std::string FormatDescription(StructuredData::ObjectSP report)
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 bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An error handling class.
Definition: Status.h:44
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
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
void AddIntegerItem(llvm::StringRef key, T value)
void AddStringItem(llvm::StringRef key, llvm::StringRef value)
std::shared_ptr< Object > ObjectSP
bool ValueIsAddress() const
Definition: Symbol.cpp:167
Address & GetAddressRef()
Definition: Symbol.h:71
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition: Target.cpp:355
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, Status &error, 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
Definition: lldb-defines.h:37
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:76
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:399
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:425
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:458
@ eLanguageTypeObjC_plus_plus
Objective-C++.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:368
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeAddressSanitizer
std::shared_ptr< lldb_private::StreamFile > StreamFileSP
Definition: lldb-forward.h:408
uint64_t user_id_t
Definition: lldb-types.h:80
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
Definition: lldb-forward.h:341
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:354