LLDB mainline
InstrumentationRuntimeUBSan.cpp
Go to the documentation of this file.
1//===-- InstrumentationRuntimeUBSan.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
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
20#include "lldb/Symbol/Symbol.h"
27#include "lldb/Target/Target.h"
28#include "lldb/Target/Thread.h"
30#include "lldb/Utility/Stream.h"
32#include <cctype>
33
34#include <memory>
35
36using namespace lldb;
37using namespace lldb_private;
38
40
42
47
51 "UndefinedBehaviorSanitizer instrumentation runtime plugin.",
53}
54
58
62
64extern "C" {
65void
66__ubsan_get_current_report_data(const char **OutIssueKind,
67 const char **OutMessage, const char **OutFilename, unsigned *OutLine,
68 unsigned *OutCol, char **OutMemoryAddr);
69}
70)";
71
73struct {
74 const char *issue_kind;
75 const char *message;
76 const char *filename;
77 unsigned line;
78 unsigned col;
79 char *memory_addr;
80} t;
81
82__ubsan_get_current_report_data(&t.issue_kind, &t.message, &t.filename, &t.line,
83 &t.col, &t.memory_addr);
84t;
85)";
86
87static addr_t RetrieveUnsigned(ValueObjectSP return_value_sp,
88 ProcessSP process_sp,
89 const std::string &expression_path) {
90 return return_value_sp->GetValueForExpressionPath(expression_path.c_str())
91 ->GetValueAsUnsigned(0);
92}
93
94static std::string RetrieveString(ValueObjectSP return_value_sp,
95 ProcessSP process_sp,
96 const std::string &expression_path) {
97 addr_t ptr = RetrieveUnsigned(return_value_sp, process_sp, expression_path);
98 std::string str;
100 process_sp->ReadCStringFromMemory(ptr, str, error);
101 return str;
102}
103
105 ExecutionContextRef exe_ctx_ref) {
106 ProcessSP process_sp = GetProcessSP();
107 if (!process_sp)
109
110 ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
111 StackFrameSP frame_sp =
112 thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
113 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
114 Target &target = process_sp->GetTarget();
115
116 if (!frame_sp)
118
120 options.SetUnwindOnError(true);
121 options.SetTryAllThreads(true);
122 options.SetStopOthers(true);
123 options.SetIgnoreBreakpoints(true);
124 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
126 options.SetAutoApplyFixIts(false);
128
129 ValueObjectSP main_value;
130 ExecutionContext exe_ctx;
131 frame_sp->CalculateExecutionContext(exe_ctx);
133 exe_ctx, options, ub_sanitizer_retrieve_report_data_command, "",
134 main_value);
135 if (result != eExpressionCompleted) {
136 StreamString ss;
137 ss << "cannot evaluate UndefinedBehaviorSanitizer expression:\n";
138 if (main_value)
139 ss << main_value->GetError().AsCString();
141 process_sp->GetTarget().GetDebugger().GetID());
143 }
144
145 // Gather the PCs of the user frames in the backtrace.
147 auto trace_sp = StructuredData::ObjectSP(trace);
148 for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
149 const Address FCA = thread_sp->GetStackFrameAtIndex(I)
150 ->GetFrameCodeAddressForSymbolication();
151 if (FCA.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
152 continue;
153
154 lldb::addr_t PC = FCA.GetLoadAddress(&target);
155 trace->AddIntegerItem(PC);
156 }
157
158 std::string IssueKind = RetrieveString(main_value, process_sp, ".issue_kind");
159 std::string ErrMessage = RetrieveString(main_value, process_sp, ".message");
160 std::string Filename = RetrieveString(main_value, process_sp, ".filename");
161 unsigned Line = RetrieveUnsigned(main_value, process_sp, ".line");
162 unsigned Col = RetrieveUnsigned(main_value, process_sp, ".col");
163 uintptr_t MemoryAddr =
164 RetrieveUnsigned(main_value, process_sp, ".memory_addr");
165
166 auto *d = new StructuredData::Dictionary();
167 auto dict_sp = StructuredData::ObjectSP(d);
168 d->AddStringItem("instrumentation_class", "UndefinedBehaviorSanitizer");
169 d->AddStringItem("description", IssueKind);
170 d->AddStringItem("summary", ErrMessage);
171 d->AddStringItem("filename", Filename);
172 d->AddIntegerItem("line", Line);
173 d->AddIntegerItem("col", Col);
174 d->AddIntegerItem("memory_address", MemoryAddr);
175 d->AddIntegerItem("tid", thread_sp->GetID());
176 d->AddItem("trace", trace_sp);
177 return dict_sp;
178}
179
181 llvm::StringRef stop_reason_description_ref;
182 report->GetAsDictionary()->GetValueForKeyAsString(
183 "description", stop_reason_description_ref);
184 std::string stop_reason_description =
185 std::string(stop_reason_description_ref);
186
187 if (!stop_reason_description.size()) {
188 stop_reason_description = "Undefined behavior detected";
189 } else {
190 stop_reason_description[0] = toupper(stop_reason_description[0]);
191 for (unsigned I = 1; I < stop_reason_description.size(); ++I)
192 if (stop_reason_description[I] == '-')
193 stop_reason_description[I] = ' ';
194 }
195 return stop_reason_description;
196}
197
199 void *baton, StoppointCallbackContext *context, user_id_t break_id,
200 user_id_t break_loc_id) {
201 assert(baton && "null baton");
202 if (!baton)
203 return false; ///< false => resume execution.
204
205 InstrumentationRuntimeUBSan *const instance =
206 static_cast<InstrumentationRuntimeUBSan *>(baton);
207
208 ProcessSP process_sp = instance->GetProcessSP();
209 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
210 if (!process_sp || !thread_sp ||
211 process_sp != context->exe_ctx_ref.GetProcessSP())
212 return false;
213
214 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
215 return false;
216
218 instance->RetrieveReportData(context->exe_ctx_ref);
219
220 if (report) {
221 thread_sp->SetStopInfo(
223 *thread_sp, GetStopReasonDescription(report), report));
224 return true;
225 }
226
227 return false;
228}
229
230const RegularExpression &
232 static RegularExpression regex(llvm::StringRef("libclang_rt\\.(a|t|ub)san_"));
233 return regex;
234}
235
237 const lldb::ModuleSP module_sp) {
238 static ConstString ubsan_test_sym("__ubsan_on_report");
239 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
240 ubsan_test_sym, lldb::eSymbolTypeAny);
241 return symbol != nullptr;
242}
243
244// FIXME: Factor out all the logic we have in common with the {a,t}san plugins.
246 if (IsActive())
247 return;
248
249 ProcessSP process_sp = GetProcessSP();
250 if (!process_sp)
251 return;
252
253 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
254
255 ConstString symbol_name("__ubsan_on_report");
256 const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
257 symbol_name, eSymbolTypeCode);
258
259 if (symbol == nullptr)
260 return;
261
262 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
263 return;
264
265 Target &target = process_sp->GetTarget();
266 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
267
268 if (symbol_address == LLDB_INVALID_ADDRESS)
269 return;
270
271 Breakpoint *breakpoint =
272 process_sp->GetTarget()
273 .CreateBreakpoint(symbol_address, /*internal=*/true,
274 /*hardware=*/false)
275 .get();
276 const bool sync = false;
278 this, sync);
279 breakpoint->SetBreakpointKind("undefined-behavior-sanitizer-report");
280 SetBreakpointID(breakpoint->GetID());
281
282 SetActive(true);
283}
284
286 SetActive(false);
287
288 auto BID = GetBreakpointID();
289 if (BID == LLDB_INVALID_BREAK_ID)
290 return;
291
292 if (ProcessSP process_sp = GetProcessSP()) {
293 process_sp->GetTarget().RemoveBreakpointByID(BID);
295 }
296}
297
301 ThreadCollectionSP threads;
302 threads = std::make_shared<ThreadCollection>();
303
304 ProcessSP process_sp = GetProcessSP();
305
306 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
307 ->GetStringValue() != "UndefinedBehaviorSanitizer")
308 return threads;
309
310 std::vector<lldb::addr_t> PCs;
311 auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
312 trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
313 PCs.push_back(PC->GetUnsignedIntegerValue());
314 return true;
315 });
316
317 if (PCs.empty())
318 return threads;
319
320 StructuredData::ObjectSP thread_id_obj =
321 info->GetObjectForDotSeparatedPath("tid");
322 lldb::tid_t tid =
323 thread_id_obj ? thread_id_obj->GetUnsignedIntegerValue() : 0;
324
325 // We gather symbolication addresses above, so no need for HistoryThread to
326 // try to infer the call addresses.
327 auto pc_type = HistoryPCType::Calls;
328 ThreadSP new_thread_sp =
329 std::make_shared<HistoryThread>(*process_sp, tid, PCs, pc_type);
330 std::string stop_reason_description = GetStopReasonDescription(info);
331 new_thread_sp->SetName(stop_reason_description.c_str());
332
333 // Save this in the Process' ExtendedThreadList so a strong pointer retains
334 // the object
335 process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
336 threads->AddThread(new_thread_sp);
337
338 return threads;
339}
static llvm::raw_ostream & error(Stream &strm)
static std::string RetrieveString(ValueObjectSP return_value_sp, ProcessSP process_sp, const std::string &expression_path)
static addr_t RetrieveUnsigned(ValueObjectSP return_value_sp, ProcessSP process_sp, const std::string &expression_path)
static const char * ub_sanitizer_retrieve_report_data_command
static std::string GetStopReasonDescription(StructuredData::ObjectSP report)
static const char * ub_sanitizer_retrieve_report_data_prefix
#define LLDB_PLUGIN_DEFINE(PluginName)
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
lldb::addr_t GetOpcodeLoadAddress(Target *target, AddressClass addr_class=AddressClass::eInvalid) const
Get the load address as an opcode load address.
Definition Address.cpp:358
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:273
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:81
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition Breakpoint.h:448
Target & GetTarget()
Accessor for the breakpoint Target.
Definition Breakpoint.h:459
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 SetUnwindOnError(bool unwind=false)
Definition Target.h:371
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:335
void SetPrefix(const char *prefix)
Definition Target.h:360
void SetTryAllThreads(bool try_others=true)
Definition Target.h:404
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:392
void SetStopOthers(bool stop_others=true)
Definition Target.h:408
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:375
Execution context objects refer to objects in the execution of the program that is being debugged.
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::StopInfoSP CreateStopReasonWithInstrumentationData(Thread &thread, std::string description, StructuredData::ObjectSP additional_data)
InstrumentationRuntimeUBSan(const lldb::ProcessSP &process_sp)
void Activate() override
Register a breakpoint in the runtime library and perform any other necessary initialization.
static lldb::InstrumentationRuntimeType GetTypeStatic()
static bool NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
bool CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp) override
Check whether module_sp corresponds to a valid runtime library.
StructuredData::ObjectSP RetrieveReportData(ExecutionContextRef exe_ctx_ref)
lldb::ThreadCollectionSP GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info) override
const RegularExpression & GetPatternForRuntimeLibrary() override
Return a regular expression which can be used to identify a valid version of the runtime library.
static lldb::InstrumentationRuntimeSP CreateInstance(const lldb::ProcessSP &process_sp)
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
uint64_t GetUnsignedIntegerValue(uint64_t fail_value=0)
std::shared_ptr< Object > ObjectSP
bool ValueIsAddress() const
Definition Symbol.cpp:165
Address & GetAddressRef()
Definition Symbol.h:73
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:481
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
#define LLDB_INVALID_ADDRESS
@ DoNoSelectMostRelevantFrame
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
@ eLanguageTypeObjC_plus_plus
Objective-C++.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Process > ProcessSP
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer
uint64_t user_id_t
Definition lldb-types.h:82
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::InstrumentationRuntime > InstrumentationRuntimeSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::ThreadCollection > ThreadCollectionSP