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"
21#include "lldb/Symbol/Symbol.h"
28#include "lldb/Target/Target.h"
29#include "lldb/Target/Thread.h"
31#include "lldb/Utility/Stream.h"
32#include <cctype>
33
34#include <memory>
35
36using namespace lldb;
37using namespace lldb_private;
38
40
42
43lldb::InstrumentationRuntimeSP
44InstrumentationRuntimeUBSan::CreateInstance(const lldb::ProcessSP &process_sp) {
45 return InstrumentationRuntimeSP(new InstrumentationRuntimeUBSan(process_sp));
46}
47
51 "UndefinedBehaviorSanitizer instrumentation runtime plugin.",
53}
54
57}
58
61}
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 = thread_sp->GetSelectedFrame();
112 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
113 Target &target = process_sp->GetTarget();
114
115 if (!frame_sp)
117
118 StreamFileSP Stream = target.GetDebugger().GetOutputStreamSP();
119
121 options.SetUnwindOnError(true);
122 options.SetTryAllThreads(true);
123 options.SetStopOthers(true);
124 options.SetIgnoreBreakpoints(true);
125 options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
127 options.SetAutoApplyFixIts(false);
129
130 ValueObjectSP main_value;
131 ExecutionContext exe_ctx;
132 Status eval_error;
133 frame_sp->CalculateExecutionContext(exe_ctx);
135 exe_ctx, options, ub_sanitizer_retrieve_report_data_command, "",
136 main_value, eval_error);
137 if (result != eExpressionCompleted) {
138 StreamString ss;
139 ss << "cannot evaluate UndefinedBehaviorSanitizer expression:\n";
140 ss << eval_error.AsCString();
142 process_sp->GetTarget().GetDebugger().GetID());
144 }
145
146 // Gather the PCs of the user frames in the backtrace.
148 auto trace_sp = StructuredData::ObjectSP(trace);
149 for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
150 const Address FCA = thread_sp->GetStackFrameAtIndex(I)
151 ->GetFrameCodeAddressForSymbolication();
152 if (FCA.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
153 continue;
154
155 lldb::addr_t PC = FCA.GetLoadAddress(&target);
157 }
158
159 std::string IssueKind = RetrieveString(main_value, process_sp, ".issue_kind");
160 std::string ErrMessage = RetrieveString(main_value, process_sp, ".message");
161 std::string Filename = RetrieveString(main_value, process_sp, ".filename");
162 unsigned Line = RetrieveUnsigned(main_value, process_sp, ".line");
163 unsigned Col = RetrieveUnsigned(main_value, process_sp, ".col");
164 uintptr_t MemoryAddr =
165 RetrieveUnsigned(main_value, process_sp, ".memory_addr");
166
167 auto *d = new StructuredData::Dictionary();
168 auto dict_sp = StructuredData::ObjectSP(d);
169 d->AddStringItem("instrumentation_class", "UndefinedBehaviorSanitizer");
170 d->AddStringItem("description", IssueKind);
171 d->AddStringItem("summary", ErrMessage);
172 d->AddStringItem("filename", Filename);
173 d->AddIntegerItem("line", Line);
174 d->AddIntegerItem("col", Col);
175 d->AddIntegerItem("memory_address", MemoryAddr);
176 d->AddIntegerItem("tid", thread_sp->GetID());
177 d->AddItem("trace", trace_sp);
178 return dict_sp;
179}
180
182 llvm::StringRef stop_reason_description_ref;
183 report->GetAsDictionary()->GetValueForKeyAsString(
184 "description", stop_reason_description_ref);
185 std::string stop_reason_description =
186 std::string(stop_reason_description_ref);
187
188 if (!stop_reason_description.size()) {
189 stop_reason_description = "Undefined behavior detected";
190 } else {
191 stop_reason_description[0] = toupper(stop_reason_description[0]);
192 for (unsigned I = 1; I < stop_reason_description.size(); ++I)
193 if (stop_reason_description[I] == '-')
194 stop_reason_description[I] = ' ';
195 }
196 return stop_reason_description;
197}
198
200 void *baton, StoppointCallbackContext *context, user_id_t break_id,
201 user_id_t break_loc_id) {
202 assert(baton && "null baton");
203 if (!baton)
204 return false; ///< false => resume execution.
205
206 InstrumentationRuntimeUBSan *const instance =
207 static_cast<InstrumentationRuntimeUBSan *>(baton);
208
209 ProcessSP process_sp = instance->GetProcessSP();
210 ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
211 if (!process_sp || !thread_sp ||
212 process_sp != context->exe_ctx_ref.GetProcessSP())
213 return false;
214
215 if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
216 return false;
217
219 instance->RetrieveReportData(context->exe_ctx_ref);
220
221 if (report) {
222 thread_sp->SetStopInfo(
224 *thread_sp, GetStopReasonDescription(report), report));
225 return true;
226 }
227
228 return false;
229}
230
231const RegularExpression &
233 static RegularExpression regex(llvm::StringRef("libclang_rt\\.(a|t|ub)san_"));
234 return regex;
235}
236
238 const lldb::ModuleSP module_sp) {
239 static ConstString ubsan_test_sym("__ubsan_on_report");
240 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
241 ubsan_test_sym, lldb::eSymbolTypeAny);
242 return symbol != nullptr;
243}
244
245// FIXME: Factor out all the logic we have in common with the {a,t}san plugins.
247 if (IsActive())
248 return;
249
250 ProcessSP process_sp = GetProcessSP();
251 if (!process_sp)
252 return;
253
254 ModuleSP runtime_module_sp = GetRuntimeModuleSP();
255
256 ConstString symbol_name("__ubsan_on_report");
257 const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
258 symbol_name, eSymbolTypeCode);
259
260 if (symbol == nullptr)
261 return;
262
263 if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
264 return;
265
266 Target &target = process_sp->GetTarget();
267 addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
268
269 if (symbol_address == LLDB_INVALID_ADDRESS)
270 return;
271
272 Breakpoint *breakpoint =
273 process_sp->GetTarget()
274 .CreateBreakpoint(symbol_address, /*internal=*/true,
275 /*hardware=*/false)
276 .get();
277 const bool sync = false;
279 this, sync);
280 breakpoint->SetBreakpointKind("undefined-behavior-sanitizer-report");
281 SetBreakpointID(breakpoint->GetID());
282
283 SetActive(true);
284}
285
287 SetActive(false);
288
289 auto BID = GetBreakpointID();
290 if (BID == LLDB_INVALID_BREAK_ID)
291 return;
292
293 if (ProcessSP process_sp = GetProcessSP()) {
294 process_sp->GetTarget().RemoveBreakpointByID(BID);
296 }
297}
298
299lldb::ThreadCollectionSP
302 ThreadCollectionSP threads;
303 threads = std::make_shared<ThreadCollection>();
304
305 ProcessSP process_sp = GetProcessSP();
306
307 if (info->GetObjectForDotSeparatedPath("instrumentation_class")
308 ->GetStringValue() != "UndefinedBehaviorSanitizer")
309 return threads;
310
311 std::vector<lldb::addr_t> PCs;
312 auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
313 trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
314 PCs.push_back(PC->GetAsInteger()->GetValue());
315 return true;
316 });
317
318 if (PCs.empty())
319 return threads;
320
321 StructuredData::ObjectSP thread_id_obj =
322 info->GetObjectForDotSeparatedPath("tid");
323 tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
324
325 // We gather symbolication addresses above, so no need for HistoryThread to
326 // try to infer the call addresses.
327 bool pcs_are_call_addresses = true;
328 ThreadSP new_thread_sp = std::make_shared<HistoryThread>(
329 *process_sp, tid, PCs, pcs_are_call_addresses);
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)
Definition: PluginManager.h:31
A section + offset based address class.
Definition: Address.h:59
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:311
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
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:283
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:453
Target & GetTarget()
Accessor for the breakpoint Target.
Definition: Breakpoint.h:464
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:418
A uniqued constant string class.
Definition: ConstString.h:39
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:1460
lldb::StreamFileSP GetOutputStreamSP()
Definition: Debugger.h:139
void SetLanguage(lldb::LanguageType language)
Definition: Target.h:305
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:324
void SetPrefix(const char *prefix)
Definition: Target.h:313
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:357
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:345
void SetStopOthers(bool stop_others=true)
Definition: Target.h:361
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:328
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)
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: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
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
void AddItem(const ObjectSP &item)
std::shared_ptr< Object > ObjectSP
bool ValueIsAddress() const
Definition: Symbol.cpp:167
Address & GetAddressRef()
Definition: Symbol.h:71
Debugger & GetDebugger()
Definition: Target.h:1031
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:352
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:74
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Definition: SBAddress.h:15
@ eLanguageTypeObjC_plus_plus
Objective-C++.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
InstrumentationRuntimeType
@ eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer
uint64_t user_id_t
Definition: lldb-types.h:80
uint64_t addr_t
Definition: lldb-types.h:79
uint64_t tid_t
Definition: lldb-types.h:82