Path: blob/main/contrib/llvm-project/lldb/source/Plugins/InstrumentationRuntime/UBSan/InstrumentationRuntimeUBSan.cpp
39653 views
//===-- InstrumentationRuntimeUBSan.cpp -----------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "InstrumentationRuntimeUBSan.h"910#include "Plugins/Process/Utility/HistoryThread.h"11#include "lldb/Breakpoint/StoppointCallbackContext.h"12#include "lldb/Core/Debugger.h"13#include "lldb/Core/Module.h"14#include "lldb/Core/PluginInterface.h"15#include "lldb/Core/PluginManager.h"16#include "lldb/Core/ValueObject.h"17#include "lldb/Expression/UserExpression.h"18#include "lldb/Host/StreamFile.h"19#include "lldb/Interpreter/CommandReturnObject.h"20#include "lldb/Symbol/Symbol.h"21#include "lldb/Symbol/SymbolContext.h"22#include "lldb/Symbol/Variable.h"23#include "lldb/Symbol/VariableList.h"24#include "lldb/Target/InstrumentationRuntimeStopInfo.h"25#include "lldb/Target/SectionLoadList.h"26#include "lldb/Target/StopInfo.h"27#include "lldb/Target/Target.h"28#include "lldb/Target/Thread.h"29#include "lldb/Utility/RegularExpression.h"30#include "lldb/Utility/Stream.h"31#include <cctype>3233#include <memory>3435using namespace lldb;36using namespace lldb_private;3738LLDB_PLUGIN_DEFINE(InstrumentationRuntimeUBSan)3940InstrumentationRuntimeUBSan::~InstrumentationRuntimeUBSan() { Deactivate(); }4142lldb::InstrumentationRuntimeSP43InstrumentationRuntimeUBSan::CreateInstance(const lldb::ProcessSP &process_sp) {44return InstrumentationRuntimeSP(new InstrumentationRuntimeUBSan(process_sp));45}4647void InstrumentationRuntimeUBSan::Initialize() {48PluginManager::RegisterPlugin(49GetPluginNameStatic(),50"UndefinedBehaviorSanitizer instrumentation runtime plugin.",51CreateInstance, GetTypeStatic);52}5354void InstrumentationRuntimeUBSan::Terminate() {55PluginManager::UnregisterPlugin(CreateInstance);56}5758lldb::InstrumentationRuntimeType InstrumentationRuntimeUBSan::GetTypeStatic() {59return eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer;60}6162static const char *ub_sanitizer_retrieve_report_data_prefix = R"(63extern "C" {64void65__ubsan_get_current_report_data(const char **OutIssueKind,66const char **OutMessage, const char **OutFilename, unsigned *OutLine,67unsigned *OutCol, char **OutMemoryAddr);68}69)";7071static const char *ub_sanitizer_retrieve_report_data_command = R"(72struct {73const char *issue_kind;74const char *message;75const char *filename;76unsigned line;77unsigned col;78char *memory_addr;79} t;8081__ubsan_get_current_report_data(&t.issue_kind, &t.message, &t.filename, &t.line,82&t.col, &t.memory_addr);83t;84)";8586static addr_t RetrieveUnsigned(ValueObjectSP return_value_sp,87ProcessSP process_sp,88const std::string &expression_path) {89return return_value_sp->GetValueForExpressionPath(expression_path.c_str())90->GetValueAsUnsigned(0);91}9293static std::string RetrieveString(ValueObjectSP return_value_sp,94ProcessSP process_sp,95const std::string &expression_path) {96addr_t ptr = RetrieveUnsigned(return_value_sp, process_sp, expression_path);97std::string str;98Status error;99process_sp->ReadCStringFromMemory(ptr, str, error);100return str;101}102103StructuredData::ObjectSP InstrumentationRuntimeUBSan::RetrieveReportData(104ExecutionContextRef exe_ctx_ref) {105ProcessSP process_sp = GetProcessSP();106if (!process_sp)107return StructuredData::ObjectSP();108109ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();110StackFrameSP frame_sp =111thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);112ModuleSP runtime_module_sp = GetRuntimeModuleSP();113Target &target = process_sp->GetTarget();114115if (!frame_sp)116return StructuredData::ObjectSP();117118StreamFileSP Stream = target.GetDebugger().GetOutputStreamSP();119120EvaluateExpressionOptions options;121options.SetUnwindOnError(true);122options.SetTryAllThreads(true);123options.SetStopOthers(true);124options.SetIgnoreBreakpoints(true);125options.SetTimeout(process_sp->GetUtilityExpressionTimeout());126options.SetPrefix(ub_sanitizer_retrieve_report_data_prefix);127options.SetAutoApplyFixIts(false);128options.SetLanguage(eLanguageTypeObjC_plus_plus);129130ValueObjectSP main_value;131ExecutionContext exe_ctx;132Status eval_error;133frame_sp->CalculateExecutionContext(exe_ctx);134ExpressionResults result = UserExpression::Evaluate(135exe_ctx, options, ub_sanitizer_retrieve_report_data_command, "",136main_value, eval_error);137if (result != eExpressionCompleted) {138StreamString ss;139ss << "cannot evaluate UndefinedBehaviorSanitizer expression:\n";140ss << eval_error.AsCString();141Debugger::ReportWarning(ss.GetString().str(),142process_sp->GetTarget().GetDebugger().GetID());143return StructuredData::ObjectSP();144}145146// Gather the PCs of the user frames in the backtrace.147StructuredData::Array *trace = new StructuredData::Array();148auto trace_sp = StructuredData::ObjectSP(trace);149for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {150const Address FCA = thread_sp->GetStackFrameAtIndex(I)151->GetFrameCodeAddressForSymbolication();152if (FCA.GetModule() == runtime_module_sp) // Skip PCs from the runtime.153continue;154155lldb::addr_t PC = FCA.GetLoadAddress(&target);156trace->AddIntegerItem(PC);157}158159std::string IssueKind = RetrieveString(main_value, process_sp, ".issue_kind");160std::string ErrMessage = RetrieveString(main_value, process_sp, ".message");161std::string Filename = RetrieveString(main_value, process_sp, ".filename");162unsigned Line = RetrieveUnsigned(main_value, process_sp, ".line");163unsigned Col = RetrieveUnsigned(main_value, process_sp, ".col");164uintptr_t MemoryAddr =165RetrieveUnsigned(main_value, process_sp, ".memory_addr");166167auto *d = new StructuredData::Dictionary();168auto dict_sp = StructuredData::ObjectSP(d);169d->AddStringItem("instrumentation_class", "UndefinedBehaviorSanitizer");170d->AddStringItem("description", IssueKind);171d->AddStringItem("summary", ErrMessage);172d->AddStringItem("filename", Filename);173d->AddIntegerItem("line", Line);174d->AddIntegerItem("col", Col);175d->AddIntegerItem("memory_address", MemoryAddr);176d->AddIntegerItem("tid", thread_sp->GetID());177d->AddItem("trace", trace_sp);178return dict_sp;179}180181static std::string GetStopReasonDescription(StructuredData::ObjectSP report) {182llvm::StringRef stop_reason_description_ref;183report->GetAsDictionary()->GetValueForKeyAsString(184"description", stop_reason_description_ref);185std::string stop_reason_description =186std::string(stop_reason_description_ref);187188if (!stop_reason_description.size()) {189stop_reason_description = "Undefined behavior detected";190} else {191stop_reason_description[0] = toupper(stop_reason_description[0]);192for (unsigned I = 1; I < stop_reason_description.size(); ++I)193if (stop_reason_description[I] == '-')194stop_reason_description[I] = ' ';195}196return stop_reason_description;197}198199bool InstrumentationRuntimeUBSan::NotifyBreakpointHit(200void *baton, StoppointCallbackContext *context, user_id_t break_id,201user_id_t break_loc_id) {202assert(baton && "null baton");203if (!baton)204return false; ///< false => resume execution.205206InstrumentationRuntimeUBSan *const instance =207static_cast<InstrumentationRuntimeUBSan *>(baton);208209ProcessSP process_sp = instance->GetProcessSP();210ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();211if (!process_sp || !thread_sp ||212process_sp != context->exe_ctx_ref.GetProcessSP())213return false;214215if (process_sp->GetModIDRef().IsLastResumeForUserExpression())216return false;217218StructuredData::ObjectSP report =219instance->RetrieveReportData(context->exe_ctx_ref);220221if (report) {222thread_sp->SetStopInfo(223InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(224*thread_sp, GetStopReasonDescription(report), report));225return true;226}227228return false;229}230231const RegularExpression &232InstrumentationRuntimeUBSan::GetPatternForRuntimeLibrary() {233static RegularExpression regex(llvm::StringRef("libclang_rt\\.(a|t|ub)san_"));234return regex;235}236237bool InstrumentationRuntimeUBSan::CheckIfRuntimeIsValid(238const lldb::ModuleSP module_sp) {239static ConstString ubsan_test_sym("__ubsan_on_report");240const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(241ubsan_test_sym, lldb::eSymbolTypeAny);242return symbol != nullptr;243}244245// FIXME: Factor out all the logic we have in common with the {a,t}san plugins.246void InstrumentationRuntimeUBSan::Activate() {247if (IsActive())248return;249250ProcessSP process_sp = GetProcessSP();251if (!process_sp)252return;253254ModuleSP runtime_module_sp = GetRuntimeModuleSP();255256ConstString symbol_name("__ubsan_on_report");257const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(258symbol_name, eSymbolTypeCode);259260if (symbol == nullptr)261return;262263if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())264return;265266Target &target = process_sp->GetTarget();267addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);268269if (symbol_address == LLDB_INVALID_ADDRESS)270return;271272Breakpoint *breakpoint =273process_sp->GetTarget()274.CreateBreakpoint(symbol_address, /*internal=*/true,275/*hardware=*/false)276.get();277const bool sync = false;278breakpoint->SetCallback(InstrumentationRuntimeUBSan::NotifyBreakpointHit,279this, sync);280breakpoint->SetBreakpointKind("undefined-behavior-sanitizer-report");281SetBreakpointID(breakpoint->GetID());282283SetActive(true);284}285286void InstrumentationRuntimeUBSan::Deactivate() {287SetActive(false);288289auto BID = GetBreakpointID();290if (BID == LLDB_INVALID_BREAK_ID)291return;292293if (ProcessSP process_sp = GetProcessSP()) {294process_sp->GetTarget().RemoveBreakpointByID(BID);295SetBreakpointID(LLDB_INVALID_BREAK_ID);296}297}298299lldb::ThreadCollectionSP300InstrumentationRuntimeUBSan::GetBacktracesFromExtendedStopInfo(301StructuredData::ObjectSP info) {302ThreadCollectionSP threads;303threads = std::make_shared<ThreadCollection>();304305ProcessSP process_sp = GetProcessSP();306307if (info->GetObjectForDotSeparatedPath("instrumentation_class")308->GetStringValue() != "UndefinedBehaviorSanitizer")309return threads;310311std::vector<lldb::addr_t> PCs;312auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();313trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {314PCs.push_back(PC->GetUnsignedIntegerValue());315return true;316});317318if (PCs.empty())319return threads;320321StructuredData::ObjectSP thread_id_obj =322info->GetObjectForDotSeparatedPath("tid");323tid_t tid = thread_id_obj ? thread_id_obj->GetUnsignedIntegerValue() : 0;324325// We gather symbolication addresses above, so no need for HistoryThread to326// try to infer the call addresses.327bool pcs_are_call_addresses = true;328ThreadSP new_thread_sp = std::make_shared<HistoryThread>(329*process_sp, tid, PCs, pcs_are_call_addresses);330std::string stop_reason_description = GetStopReasonDescription(info);331new_thread_sp->SetName(stop_reason_description.c_str());332333// Save this in the Process' ExtendedThreadList so a strong pointer retains334// the object335process_sp->GetExtendedThreadList().AddThread(new_thread_sp);336threads->AddThread(new_thread_sp);337338return threads;339}340341342