From: Kuba Brecka Date: Wed, 23 Mar 2016 15:36:22 +0000 (+0000) Subject: Add ThreadSanitizer debugging support. X-Git-Tag: llvmorg-3.9.0-rc1~11155 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=6a83143650aeb02e9c53bd5f7b7b5253a6c8b157;p=platform%2Fupstream%2Fllvm.git Add ThreadSanitizer debugging support. This patch adds ThreadSanitizer support into LLDB: - Adding a new InstrumentationRuntime plugin, ThreadSanitizerRuntime, in the same way ASan is implemented. - A breakpoint stops in `__tsan_on_report`, then we extract all sorts of information by evaluating an expression. We then populate this into StopReasonExtendedInfo. - SBThread gets a new API, SBThread::GetStopReasonExtendedBacktraces(), which returns TSan’s backtraces in the form of regular SBThreads. Non-TSan stop reasons return an empty collection. - Added some test cases. Reviewed by Greg Clayton. llvm-svn: 264162 --- diff --git a/lldb/include/lldb/API/SBThread.h b/lldb/include/lldb/API/SBThread.h index f05febe..37e60b0 100644 --- a/lldb/include/lldb/API/SBThread.h +++ b/lldb/include/lldb/API/SBThread.h @@ -82,6 +82,9 @@ public: bool GetStopReasonExtendedInfoAsJSON (lldb::SBStream &stream); + SBThreadCollection + GetStopReasonExtendedBacktraces (InstrumentationRuntimeType type); + size_t GetStopDescription (char *dst, size_t dst_len); diff --git a/lldb/include/lldb/API/SBThreadCollection.h b/lldb/include/lldb/API/SBThreadCollection.h index 996ee3c..79f9774 100644 --- a/lldb/include/lldb/API/SBThreadCollection.h +++ b/lldb/include/lldb/API/SBThreadCollection.h @@ -58,6 +58,7 @@ protected: private: friend class SBProcess; + friend class SBThread; lldb::ThreadCollectionSP m_opaque_sp; }; diff --git a/lldb/include/lldb/lldb-enumerations.h b/lldb/include/lldb/lldb-enumerations.h index da6c979..89dbeb3 100644 --- a/lldb/include/lldb/lldb-enumerations.h +++ b/lldb/include/lldb/lldb-enumerations.h @@ -434,6 +434,7 @@ namespace lldb { enum InstrumentationRuntimeType { eInstrumentationRuntimeTypeAddressSanitizer = 0x0000, + eInstrumentationRuntimeTypeThreadSanitizer = 0x0001, eNumInstrumentationRuntimeTypes }; diff --git a/lldb/lldb.xcodeproj/project.pbxproj b/lldb/lldb.xcodeproj/project.pbxproj index a13610f..763dce5 100644 --- a/lldb/lldb.xcodeproj/project.pbxproj +++ b/lldb/lldb.xcodeproj/project.pbxproj @@ -724,6 +724,7 @@ 6D99A3631BBC2F3200979793 /* ArmUnwindInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6D99A3621BBC2F3200979793 /* ArmUnwindInfo.cpp */; }; 6D9AB3DD1BB2B74E003F2289 /* TypeMap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6D9AB3DC1BB2B74E003F2289 /* TypeMap.cpp */; }; 6DEC6F391BD66D750091ABA6 /* TaskPool.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6DEC6F381BD66D750091ABA6 /* TaskPool.cpp */; }; + 8C26C4261C3EA5F90031DF7C /* ThreadSanitizerRuntime.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C26C4241C3EA4340031DF7C /* ThreadSanitizerRuntime.cpp */; }; 8C2D6A53197A1EAF006989C9 /* MemoryHistory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C2D6A52197A1EAF006989C9 /* MemoryHistory.cpp */; }; 8C2D6A5E197A250F006989C9 /* MemoryHistoryASan.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8C2D6A5A197A1FDC006989C9 /* MemoryHistoryASan.cpp */; }; 8CCB017E19BA28A80009FD44 /* ThreadCollection.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8CCB017A19BA283D0009FD44 /* ThreadCollection.cpp */; }; @@ -2454,6 +2455,8 @@ 6D9AB3DE1BB2B76B003F2289 /* TypeMap.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = TypeMap.h; path = include/lldb/Symbol/TypeMap.h; sourceTree = ""; }; 6DEC6F381BD66D750091ABA6 /* TaskPool.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TaskPool.cpp; path = source/Utility/TaskPool.cpp; sourceTree = ""; }; 6DEC6F3A1BD66D950091ABA6 /* TaskPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TaskPool.h; path = include/lldb/Utility/TaskPool.h; sourceTree = ""; }; + 8C26C4241C3EA4340031DF7C /* ThreadSanitizerRuntime.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = ThreadSanitizerRuntime.cpp; path = ThreadSanitizer/ThreadSanitizerRuntime.cpp; sourceTree = ""; }; + 8C26C4251C3EA4340031DF7C /* ThreadSanitizerRuntime.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = ThreadSanitizerRuntime.h; path = ThreadSanitizer/ThreadSanitizerRuntime.h; sourceTree = ""; }; 8C2D6A52197A1EAF006989C9 /* MemoryHistory.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = MemoryHistory.cpp; path = source/Target/MemoryHistory.cpp; sourceTree = ""; }; 8C2D6A54197A1EBE006989C9 /* MemoryHistory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = MemoryHistory.h; path = include/lldb/Target/MemoryHistory.h; sourceTree = ""; }; 8C2D6A5A197A1FDC006989C9 /* MemoryHistoryASan.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MemoryHistoryASan.cpp; sourceTree = ""; }; @@ -5482,6 +5485,15 @@ path = Android; sourceTree = ""; }; + 8C26C4221C3EA4050031DF7C /* ThreadSanitizer */ = { + isa = PBXGroup; + children = ( + 8C26C4241C3EA4340031DF7C /* ThreadSanitizerRuntime.cpp */, + 8C26C4251C3EA4340031DF7C /* ThreadSanitizerRuntime.h */, + ); + name = ThreadSanitizer; + sourceTree = ""; + }; 8C2D6A58197A1FB9006989C9 /* MemoryHistory */ = { isa = PBXGroup; children = ( @@ -5502,6 +5514,7 @@ 8CF02ADD19DCBEC200B14BE0 /* InstrumentationRuntime */ = { isa = PBXGroup; children = ( + 8C26C4221C3EA4050031DF7C /* ThreadSanitizer */, 8CF02ADE19DCBEE600B14BE0 /* AddressSanitizer */, ); path = InstrumentationRuntime; @@ -6926,6 +6939,7 @@ 2642FBAE13D003B400ED6808 /* CommunicationKDP.cpp in Sources */, 2642FBB013D003B400ED6808 /* ProcessKDP.cpp in Sources */, 23D4007E1C210201000C3885 /* DebugMacros.cpp in Sources */, + 8C26C4261C3EA5F90031DF7C /* ThreadSanitizerRuntime.cpp in Sources */, 2642FBB213D003B400ED6808 /* ProcessKDPLog.cpp in Sources */, 263641191B34AEE200145B2F /* ABISysV_mips64.cpp in Sources */, 26957D9813D381C900670048 /* RegisterContextDarwin_arm.cpp in Sources */, diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile new file mode 100644 index 0000000..c930ae5 --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile @@ -0,0 +1,6 @@ +LEVEL = ../../../make + +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include $(LEVEL)/Makefile.rules diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py new file mode 100644 index 0000000..eb0c5df --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py @@ -0,0 +1,112 @@ +""" +Tests basic ThreadSanitizer support (detecting a data race). +""" + +import os, time +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + +class TsanBasicTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessCompilerRt + def test (self): + self.build () + self.tsan_tests () + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_malloc = line_number('main.c', '// malloc line') + self.line_thread1 = line_number('main.c', '// thread1 line') + self.line_thread2 = line_number('main.c', '// thread2 line') + + def tsan_tests (self): + exe = os.path.join (os.getcwd(), "a.out") + self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + + self.runCmd("run") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A data race should be detected", + substrs = ['stopped', 'stop reason = Data race detected']) + + self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) + + # test that the TSan dylib is present + self.expect("image lookup -n __tsan_get_current_report", "__tsan_get_current_report should be present", + substrs = ['1 match found']) + + # We should be stopped in __tsan_on_report + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + self.assertTrue("__tsan_on_report" in frame.GetFunctionName()) + + # The stopped thread backtrace should contain either line1 or line2 from main.c. + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", + substrs = ["instrumentation_class", "description", "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + self.assertEqual(data["description"], "data-race") + self.assertEqual(len(data["mops"]), 2) + + backtraces = thread.GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeAddressSanitizer) + self.assertEqual(backtraces.GetSize(), 0) + + backtraces = thread.GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeThreadSanitizer) + self.assertTrue(backtraces.GetSize() >= 2) + + # First backtrace is a memory operation + thread = backtraces.GetThreadAtIndex(0) + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + # Second backtrace is a memory operation + thread = backtraces.GetThreadAtIndex(1) + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + self.runCmd("continue") + + # the stop reason of the thread should be a SIGABRT. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs = ['stopped', 'stop reason = signal SIGABRT']) + + # test that we're in pthread_kill now (TSan abort the process) + self.expect("thread list", "We should be stopped in pthread_kill", + substrs = ['pthread_kill']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c new file mode 100644 index 0000000..c082b01 --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c @@ -0,0 +1,37 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include +#include +#include + +char *pointer; + +void *f1(void *p) { + pointer[0] = 'x'; // thread1 line + return NULL; +} + +void *f2(void *p) { + pointer[0] = 'y'; // thread2 line + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pointer = (char *)malloc(10); // malloc line + + pthread_t t1, t2; + pthread_create(&t1, NULL, f1, NULL); + pthread_create(&t2, NULL, f2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + return 0; +} diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile new file mode 100644 index 0000000..c930ae5 --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile @@ -0,0 +1,6 @@ +LEVEL = ../../../make + +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include $(LEVEL)/Makefile.rules diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py new file mode 100644 index 0000000..3d8e645 --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py @@ -0,0 +1,34 @@ +""" +Tests ThreadSanitizer's support to detect a leaked thread. +""" + +import os, time +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + +class TsanThreadLeakTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessCompilerRt + def test (self): + self.build () + self.tsan_tests () + + def tsan_tests (self): + exe = os.path.join (os.getcwd(), "a.out") + self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + + self.runCmd("run") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A thread leak should be detected", + substrs = ['stopped', 'stop reason = Thread leak detected']) + + self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c new file mode 100644 index 0000000..3c17e22 --- /dev/null +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c @@ -0,0 +1,24 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include +#include +#include + +void *f1(void *p) { + printf("hello\n"); + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pthread_t t1; + pthread_create(&t1, NULL, f1, NULL); + + return 0; +} diff --git a/lldb/scripts/interface/SBThread.i b/lldb/scripts/interface/SBThread.i index 5016059..3dcb848 100644 --- a/lldb/scripts/interface/SBThread.i +++ b/lldb/scripts/interface/SBThread.i @@ -118,6 +118,15 @@ public: ") GetStopReasonExtendedInfoAsJSON; bool GetStopReasonExtendedInfoAsJSON (lldb::SBStream &stream); + + %feature("autodoc", " + Returns a collection of historical stack traces that are significant to the + current stop reason. Used by ThreadSanitizer, where we provide various stack + traces that were involved in a data race or other type of detected issue. + ") GetStopReasonExtendedBacktraces; + SBThreadCollection + GetStopReasonExtendedBacktraces (InstrumentationRuntimeType type); + %feature("autodoc", " Pass only an (int)length and expect to get a Python string describing the diff --git a/lldb/source/API/SBThread.cpp b/lldb/source/API/SBThread.cpp index 3d2f15d..e954781 100644 --- a/lldb/source/API/SBThread.cpp +++ b/lldb/source/API/SBThread.cpp @@ -34,13 +34,14 @@ #include "lldb/Target/ThreadPlanStepOut.h" #include "lldb/Target/ThreadPlanStepRange.h" #include "lldb/Target/ThreadPlanStepInRange.h" - +#include "Plugins/Process/Utility/HistoryThread.h" #include "lldb/API/SBAddress.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBFrame.h" #include "lldb/API/SBProcess.h" +#include "lldb/API/SBThreadCollection.h" #include "lldb/API/SBThreadPlan.h" #include "lldb/API/SBValue.h" @@ -328,6 +329,62 @@ SBThread::GetStopReasonExtendedInfoAsJSON (lldb::SBStream &stream) return true; } +static void +AddThreadsForPath(std::string path, ThreadCollectionSP threads, ProcessSP process_sp, StructuredData::ObjectSP info) +{ + info->GetObjectForDotSeparatedPath(path)->GetAsArray()->ForEach([process_sp, threads] (StructuredData::Object *o) -> bool { + std::vector pcs; + o->GetObjectForDotSeparatedPath("trace")->GetAsArray()->ForEach([&pcs] (StructuredData::Object *pc) -> bool { + pcs.push_back(pc->GetAsInteger()->GetValue()); + return true; + }); + + tid_t tid = o->GetObjectForDotSeparatedPath("thread_id")->GetIntegerValue(); + uint32_t stop_id = 0; + bool stop_id_is_valid = false; + HistoryThread *history_thread = new HistoryThread(*process_sp, tid, pcs, stop_id, stop_id_is_valid); + ThreadSP new_thread_sp(history_thread); + // Save this in the Process' ExtendedThreadList so a strong pointer retains the object + process_sp->GetExtendedThreadList().AddThread(new_thread_sp); + threads->AddThread(new_thread_sp); + + return true; + }); +} + +SBThreadCollection +SBThread::GetStopReasonExtendedBacktraces (InstrumentationRuntimeType type) +{ + ThreadCollectionSP threads; + threads.reset(new ThreadCollection()); + + // We currently only support ThreadSanitizer. + if (type != eInstrumentationRuntimeTypeThreadSanitizer) + return threads; + + ExecutionContext exe_ctx (m_opaque_sp.get()); + if (! exe_ctx.HasThreadScope()) + return SBThreadCollection(threads); + + ProcessSP process_sp = exe_ctx.GetProcessSP(); + + StopInfoSP stop_info = exe_ctx.GetThreadPtr()->GetStopInfo(); + StructuredData::ObjectSP info = stop_info->GetExtendedInfo(); + if (! info) + return threads; + + if (info->GetObjectForDotSeparatedPath("instrumentation_class")->GetStringValue() != "ThreadSanitizer") + return threads; + + AddThreadsForPath("stacks", threads, process_sp, info); + AddThreadsForPath("mops", threads, process_sp, info); + AddThreadsForPath("locs", threads, process_sp, info); + AddThreadsForPath("mutexes", threads, process_sp, info); + AddThreadsForPath("threads", threads, process_sp, info); + + return threads; +} + size_t SBThread::GetStopDescription (char *dst, size_t dst_len) { diff --git a/lldb/source/API/SystemInitializerFull.cpp b/lldb/source/API/SystemInitializerFull.cpp index 5cf4b65..4d44834 100644 --- a/lldb/source/API/SystemInitializerFull.cpp +++ b/lldb/source/API/SystemInitializerFull.cpp @@ -44,6 +44,7 @@ #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h" #include "Plugins/Instruction/ARM64/EmulateInstructionARM64.h" #include "Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.h" +#include "Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.h" #include "Plugins/JITLoader/GDB/JITLoaderGDB.h" #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" #include "Plugins/Language/Go/GoLanguage.h" @@ -306,6 +307,7 @@ SystemInitializerFull::Initialize() #endif MemoryHistoryASan::Initialize(); AddressSanitizerRuntime::Initialize(); + ThreadSanitizerRuntime::Initialize(); SymbolVendorELF::Initialize(); SymbolFileDWARF::Initialize(); @@ -429,6 +431,7 @@ SystemInitializerFull::Terminate() #endif MemoryHistoryASan::Terminate(); AddressSanitizerRuntime::Terminate(); + ThreadSanitizerRuntime::Terminate(); SymbolVendorELF::Terminate(); SymbolFileDWARF::Terminate(); SymbolFilePDB::Terminate(); diff --git a/lldb/source/Plugins/InstrumentationRuntime/CMakeLists.txt b/lldb/source/Plugins/InstrumentationRuntime/CMakeLists.txt index 8ee303b..ae7c6e5 100644 --- a/lldb/source/Plugins/InstrumentationRuntime/CMakeLists.txt +++ b/lldb/source/Plugins/InstrumentationRuntime/CMakeLists.txt @@ -1 +1,2 @@ add_subdirectory(AddressSanitizer) +add_subdirectory(ThreadSanitizer) diff --git a/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/CMakeLists.txt b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/CMakeLists.txt new file mode 100644 index 0000000..6ef7943 --- /dev/null +++ b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/CMakeLists.txt @@ -0,0 +1,3 @@ +add_lldb_library(lldbPluginInstrumentationRuntimeThreadSanitizer + ThreadSanitizerRuntime.cpp + ) diff --git a/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp new file mode 100644 index 0000000..c6ee6af --- /dev/null +++ b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp @@ -0,0 +1,538 @@ +//===-- ThreadSanitizerRuntime.cpp ------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "ThreadSanitizerRuntime.h" + +#include "lldb/Breakpoint/StoppointCallbackContext.h" +#include "lldb/Core/Debugger.h" +#include "lldb/Core/Module.h" +#include "lldb/Core/ModuleList.h" +#include "lldb/Core/RegularExpression.h" +#include "lldb/Core/PluginInterface.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Core/Stream.h" +#include "lldb/Core/StreamFile.h" +#include "lldb/Core/ValueObject.h" +#include "lldb/Expression/UserExpression.h" +#include "lldb/Interpreter/CommandReturnObject.h" +#include "lldb/Symbol/Symbol.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Target/InstrumentationRuntimeStopInfo.h" +#include "lldb/Target/StopInfo.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" + +using namespace lldb; +using namespace lldb_private; + +lldb::InstrumentationRuntimeSP +ThreadSanitizerRuntime::CreateInstance (const lldb::ProcessSP &process_sp) +{ + return InstrumentationRuntimeSP(new ThreadSanitizerRuntime(process_sp)); +} + +void +ThreadSanitizerRuntime::Initialize() +{ + PluginManager::RegisterPlugin (GetPluginNameStatic(), + "ThreadSanitizer instrumentation runtime plugin.", + CreateInstance, + GetTypeStatic); +} + +void +ThreadSanitizerRuntime::Terminate() +{ + PluginManager::UnregisterPlugin (CreateInstance); +} + +lldb_private::ConstString +ThreadSanitizerRuntime::GetPluginNameStatic() +{ + return ConstString("ThreadSanitizer"); +} + +lldb::InstrumentationRuntimeType +ThreadSanitizerRuntime::GetTypeStatic() +{ + return eInstrumentationRuntimeTypeThreadSanitizer; +} + +ThreadSanitizerRuntime::ThreadSanitizerRuntime(const ProcessSP &process_sp) : +m_is_active(false), +m_runtime_module_wp(), +m_process_wp(), +m_breakpoint_id(0) +{ + if (process_sp) + m_process_wp = process_sp; +} + +ThreadSanitizerRuntime::~ThreadSanitizerRuntime() +{ + Deactivate(); +} + +static bool +ModuleContainsTSanRuntime(ModuleSP module_sp) +{ + static ConstString g_tsan_get_current_report("__tsan_get_current_report"); + const Symbol* symbol = module_sp->FindFirstSymbolWithNameAndType(g_tsan_get_current_report, lldb::eSymbolTypeAny); + return symbol != nullptr; +} + +void +ThreadSanitizerRuntime::ModulesDidLoad(lldb_private::ModuleList &module_list) +{ + if (IsActive()) + return; + + if (GetRuntimeModuleSP()) { + Activate(); + return; + } + + module_list.ForEach ([this](const lldb::ModuleSP module_sp) -> bool + { + const FileSpec & file_spec = module_sp->GetFileSpec(); + if (! file_spec) + return true; // Keep iterating through modules + + llvm::StringRef module_basename(file_spec.GetFilename().GetStringRef()); + if (module_sp->IsExecutable() || module_basename.startswith("libclang_rt.tsan_")) + { + if (ModuleContainsTSanRuntime(module_sp)) + { + m_runtime_module_wp = module_sp; + Activate(); + return false; // Stop iterating + } + } + + return true; // Keep iterating through modules + }); +} + +bool +ThreadSanitizerRuntime::IsActive() +{ + return m_is_active; +} + +#define RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC 2*1000*1000 + +const char * +thread_sanitizer_retrieve_report_data_prefix = R"( +extern "C" +{ + void *__tsan_get_current_report(); + int __tsan_get_report_data(void *report, const char **description, int *count, + int *stack_count, int *mop_count, int *loc_count, + int *mutex_count, int *thread_count, + int *unique_tid_count, void **sleep_trace, + unsigned long trace_size); + int __tsan_get_report_stack(void *report, unsigned long idx, void **trace, + unsigned long trace_size); + int __tsan_get_report_mop(void *report, unsigned long idx, int *tid, void **addr, + int *size, int *write, int *atomic, void **trace, + unsigned long trace_size); + int __tsan_get_report_loc(void *report, unsigned long idx, const char **type, + void **addr, unsigned long *start, unsigned long *size, int *tid, + int *fd, int *suppressable, void **trace, + unsigned long trace_size); + int __tsan_get_report_mutex(void *report, unsigned long idx, unsigned long *mutex_id, void **addr, + int *destroyed, void **trace, unsigned long trace_size); + int __tsan_get_report_thread(void *report, unsigned long idx, int *tid, unsigned long *pid, + int *running, const char **name, int *parent_tid, + void **trace, unsigned long trace_size); + int __tsan_get_report_unique_tid(void *report, unsigned long idx, int *tid); +} + +const int REPORT_TRACE_SIZE = 128; +const int REPORT_ARRAY_SIZE = 4; + +struct data { + void *report; + const char *description; + int report_count; + + void *sleep_trace[REPORT_TRACE_SIZE]; + + int stack_count; + struct { + int idx; + void *trace[REPORT_TRACE_SIZE]; + } stacks[REPORT_ARRAY_SIZE]; + + int mop_count; + struct { + int idx; + int tid; + int size; + int write; + int atomic; + void *addr; + void *trace[REPORT_TRACE_SIZE]; + } mops[REPORT_ARRAY_SIZE]; + + int loc_count; + struct { + int idx; + const char *type; + void *addr; + unsigned long start; + unsigned long size; + int tid; + int fd; + int suppressable; + void *trace[REPORT_TRACE_SIZE]; + } locs[REPORT_ARRAY_SIZE]; + + int mutex_count; + struct { + int idx; + unsigned long mutex_id; + void *addr; + int destroyed; + void *trace[REPORT_TRACE_SIZE]; + } mutexes[REPORT_ARRAY_SIZE]; + + int thread_count; + struct { + int idx; + int tid; + unsigned long pid; + int running; + const char *name; + int parent_tid; + void *trace[REPORT_TRACE_SIZE]; + } threads[REPORT_ARRAY_SIZE]; + + int unique_tid_count; + struct { + int idx; + int tid; + } unique_tids[REPORT_ARRAY_SIZE]; +}; +)"; + +const char * +thread_sanitizer_retrieve_report_data_command = R"( +data t = {0}; + +t.report = __tsan_get_current_report(); +__tsan_get_report_data(t.report, &t.description, &t.report_count, &t.stack_count, &t.mop_count, &t.loc_count, &t.mutex_count, &t.thread_count, &t.unique_tid_count, t.sleep_trace, REPORT_TRACE_SIZE); + +if (t.stack_count > REPORT_ARRAY_SIZE) t.stack_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.stack_count; i++) { + t.stacks[i].idx = i; + __tsan_get_report_stack(t.report, i, t.stacks[i].trace, REPORT_TRACE_SIZE); +} + +if (t.mop_count > REPORT_ARRAY_SIZE) t.mop_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.mop_count; i++) { + t.mops[i].idx = i; + __tsan_get_report_mop(t.report, i, &t.mops[i].tid, &t.mops[i].addr, &t.mops[i].size, &t.mops[i].write, &t.mops[i].atomic, t.mops[i].trace, REPORT_TRACE_SIZE); +} + +if (t.loc_count > REPORT_ARRAY_SIZE) t.loc_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.loc_count; i++) { + t.locs[i].idx = i; + __tsan_get_report_loc(t.report, i, &t.locs[i].type, &t.locs[i].addr, &t.locs[i].start, &t.locs[i].size, &t.locs[i].tid, &t.locs[i].fd, &t.locs[i].suppressable, t.locs[i].trace, REPORT_TRACE_SIZE); +} + +if (t.mutex_count > REPORT_ARRAY_SIZE) t.mutex_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.mutex_count; i++) { + t.mutexes[i].idx = i; + __tsan_get_report_mutex(t.report, i, &t.mutexes[i].mutex_id, &t.mutexes[i].addr, &t.mutexes[i].destroyed, t.mutexes[i].trace, REPORT_TRACE_SIZE); +} + +if (t.thread_count > REPORT_ARRAY_SIZE) t.thread_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.thread_count; i++) { + t.threads[i].idx = i; + __tsan_get_report_thread(t.report, i, &t.threads[i].tid, &t.threads[i].pid, &t.threads[i].running, &t.threads[i].name, &t.threads[i].parent_tid, t.threads[i].trace, REPORT_TRACE_SIZE); +} + +if (t.unique_tid_count > REPORT_ARRAY_SIZE) t.unique_tid_count = REPORT_ARRAY_SIZE; +for (int i = 0; i < t.unique_tid_count; i++) { + t.unique_tids[i].idx = i; + __tsan_get_report_unique_tid(t.report, i, &t.unique_tids[i].tid); +} + +t; +)"; + +static StructuredData::Array * +CreateStackTrace(ValueObjectSP o, std::string trace_item_name = ".trace") { + StructuredData::Array *trace = new StructuredData::Array(); + ValueObjectSP trace_value_object = o->GetValueForExpressionPath(trace_item_name.c_str()); + for (int j = 0; j < 8; j++) { + addr_t trace_addr = trace_value_object->GetChildAtIndex(j, true)->GetValueAsUnsigned(0); + if (trace_addr == 0) + break; + trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(trace_addr))); + } + return trace; +} + +static StructuredData::Array * +ConvertToStructuredArray(ValueObjectSP return_value_sp, std::string items_name, std::string count_name, std::function const &callback) +{ + StructuredData::Array *array = new StructuredData::Array(); + unsigned int count = return_value_sp->GetValueForExpressionPath(count_name.c_str())->GetValueAsUnsigned(0); + ValueObjectSP objects = return_value_sp->GetValueForExpressionPath(items_name.c_str()); + for (int i = 0; i < count; i++) { + ValueObjectSP o = objects->GetChildAtIndex(i, true); + StructuredData::Dictionary *dict = new StructuredData::Dictionary(); + + callback(o, dict); + + array->AddItem(StructuredData::ObjectSP(dict)); + } + return array; +} + +static std::string +RetrieveString(ValueObjectSP return_value_sp, ProcessSP process_sp, std::string expression_path) +{ + addr_t ptr = return_value_sp->GetValueForExpressionPath(expression_path.c_str())->GetValueAsUnsigned(0); + std::string str; + Error error; + process_sp->ReadCStringFromMemory(ptr, str, error); + return str; +} + +StructuredData::ObjectSP +ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) +{ + ProcessSP process_sp = GetProcessSP(); + if (!process_sp) + return StructuredData::ObjectSP(); + + ThreadSP thread_sp = exe_ctx_ref.GetThreadSP(); + StackFrameSP frame_sp = thread_sp->GetSelectedFrame(); + + if (!frame_sp) + return StructuredData::ObjectSP(); + + EvaluateExpressionOptions options; + options.SetUnwindOnError(true); + options.SetTryAllThreads(true); + options.SetStopOthers(true); + options.SetIgnoreBreakpoints(true); + options.SetTimeoutUsec(RETRIEVE_REPORT_DATA_FUNCTION_TIMEOUT_USEC); + options.SetPrefix(thread_sanitizer_retrieve_report_data_prefix); + + ValueObjectSP main_value; + ExecutionContext exe_ctx; + Error eval_error; + frame_sp->CalculateExecutionContext(exe_ctx); + ExpressionResults result = UserExpression::Evaluate (exe_ctx, + options, + thread_sanitizer_retrieve_report_data_command, + "", + main_value, + eval_error); + if (result != eExpressionCompleted) { + process_sp->GetTarget().GetDebugger().GetAsyncOutputStream()->Printf("Warning: Cannot evaluate ThreadSanitizer expression:\n%s\n", eval_error.AsCString()); + return StructuredData::ObjectSP(); + } + + StructuredData::Dictionary *dict = new StructuredData::Dictionary(); + dict->AddStringItem("instrumentation_class", "ThreadSanitizer"); + dict->AddStringItem("description", RetrieveString(main_value, process_sp, ".description")); + dict->AddIntegerItem("report_count", main_value->GetValueForExpressionPath(".report_count")->GetValueAsUnsigned(0)); + dict->AddItem("sleep_trace", StructuredData::ObjectSP(CreateStackTrace(main_value, ".sleep_trace"))); + + StructuredData::Array *stacks = ConvertToStructuredArray(main_value, ".stacks", ".stack_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o))); + }); + dict->AddItem("stacks", StructuredData::ObjectSP(stacks)); + + StructuredData::Array *mops = ConvertToStructuredArray(main_value, ".mops", ".mop_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0)); + dict->AddBooleanItem("is_write", o->GetValueForExpressionPath(".write")->GetValueAsUnsigned(0)); + dict->AddBooleanItem("is_atomic", o->GetValueForExpressionPath(".atomic")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0)); + dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o))); + }); + dict->AddItem("mops", StructuredData::ObjectSP(mops)); + + StructuredData::Array *locs = ConvertToStructuredArray(main_value, ".locs", ".loc_count", [process_sp] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddStringItem("type", RetrieveString(o, process_sp, ".type")); + dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("start", o->GetValueForExpressionPath(".start")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("size", o->GetValueForExpressionPath(".size")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("file_descriptor", o->GetValueForExpressionPath(".fd")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("suppressable", o->GetValueForExpressionPath(".suppressable")->GetValueAsUnsigned(0)); + dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o))); + }); + dict->AddItem("locs", StructuredData::ObjectSP(locs)); + + StructuredData::Array *mutexes = ConvertToStructuredArray(main_value, ".mutexes", ".mutex_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("mutex_id", o->GetValueForExpressionPath(".mutex_id")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("address", o->GetValueForExpressionPath(".addr")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("destroyed", o->GetValueForExpressionPath(".destroyed")->GetValueAsUnsigned(0)); + dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o))); + }); + dict->AddItem("mutexes", StructuredData::ObjectSP(mutexes)); + + StructuredData::Array *threads = ConvertToStructuredArray(main_value, ".threads", ".thread_count", [process_sp] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("thread_id", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("process_id", o->GetValueForExpressionPath(".pid")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("running", o->GetValueForExpressionPath(".running")->GetValueAsUnsigned(0)); + dict->AddStringItem("name", RetrieveString(o, process_sp, ".name")); + dict->AddIntegerItem("parent_thread_id", o->GetValueForExpressionPath(".parent_tid")->GetValueAsUnsigned(0)); + dict->AddItem("trace", StructuredData::ObjectSP(CreateStackTrace(o))); + }); + dict->AddItem("threads", StructuredData::ObjectSP(threads)); + + StructuredData::Array *unique_tids = ConvertToStructuredArray(main_value, ".unique_tids", ".unique_tid_count", [] (ValueObjectSP o, StructuredData::Dictionary *dict) { + dict->AddIntegerItem("index", o->GetValueForExpressionPath(".idx")->GetValueAsUnsigned(0)); + dict->AddIntegerItem("tid", o->GetValueForExpressionPath(".tid")->GetValueAsUnsigned(0)); + }); + dict->AddItem("unique_tids", StructuredData::ObjectSP(unique_tids)); + + return StructuredData::ObjectSP(dict); +} + +std::string +ThreadSanitizerRuntime::FormatDescription(StructuredData::ObjectSP report) +{ + std::string description = report->GetAsDictionary()->GetValueForKey("description")->GetAsString()->GetValue(); + + if (description == "data-race") { + return "Data race detected"; + } else if (description == "data-race-vptr") { + return "Data race on C++ virtual pointer detected"; + } else if (description == "heap-use-after-free") { + return "Use of deallocated memory detected"; + } else if (description == "heap-use-after-free-vptr") { + return "Use of deallocated C++ virtual pointer detected"; + } else if (description == "thread-leak") { + return "Thread leak detected"; + } else if (description == "locked-mutex-destroy") { + return "Destruction of a locked mutex detected"; + } else if (description == "mutex-double-lock") { + return "Double lock of a mutex detected"; + } else if (description == "mutex-invalid-access") { + return "Use of an invalid mutex (e.g. uninitialized or destroyed) detected"; + } else if (description == "mutex-bad-unlock") { + return "Unlock of an unlocked mutex (or by a wrong thread) detected"; + } else if (description == "mutex-bad-read-lock") { + return "Read lock of a write locked mutex detected"; + } else if (description == "mutex-bad-read-unlock") { + return "Read unlock of a write locked mutex detected"; + } else if (description == "signal-unsafe-call") { + return "Signal-unsafe call inside a signal handler detected"; + } else if (description == "errno-in-signal-handler") { + return "Overwrite of errno in a signal handler detected"; + } else if (description == "lock-order-inversion") { + return "Lock order inversion (potential deadlock) detected"; + } + + // for unknown report codes just show the code + return description; +} + +bool +ThreadSanitizerRuntime::NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) +{ + assert (baton && "null baton"); + if (!baton) + return false; + + ThreadSanitizerRuntime *const instance = static_cast(baton); + + StructuredData::ObjectSP report = instance->RetrieveReportData(context->exe_ctx_ref); + std::string description; + if (report) { + description = instance->FormatDescription(report); + } + ProcessSP process_sp = instance->GetProcessSP(); + // Make sure this is the right process + if (process_sp && process_sp == context->exe_ctx_ref.GetProcessSP()) + { + ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP(); + if (thread_sp) + thread_sp->SetStopInfo(InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(*thread_sp, description.c_str(), report)); + + StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile()); + if (stream_sp) + { + stream_sp->Printf ("ThreadSanitizer report breakpoint hit. Use 'thread info -s' to get extended information about the report.\n"); + } + return true; // Return true to stop the target + } + else + return false; // Let target run +} + +void +ThreadSanitizerRuntime::Activate() +{ + if (m_is_active) + return; + + ProcessSP process_sp = GetProcessSP(); + if (!process_sp) + return; + + ConstString symbol_name ("__tsan_on_report"); + const Symbol *symbol = GetRuntimeModuleSP()->FindFirstSymbolWithNameAndType (symbol_name, eSymbolTypeCode); + + if (symbol == NULL) + return; + + if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid()) + return; + + Target &target = process_sp->GetTarget(); + addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target); + + if (symbol_address == LLDB_INVALID_ADDRESS) + return; + + bool internal = true; + bool hardware = false; + Breakpoint *breakpoint = process_sp->GetTarget().CreateBreakpoint(symbol_address, internal, hardware).get(); + breakpoint->SetCallback (ThreadSanitizerRuntime::NotifyBreakpointHit, this, true); + breakpoint->SetBreakpointKind ("thread-sanitizer-report"); + m_breakpoint_id = breakpoint->GetID(); + + StreamFileSP stream_sp (process_sp->GetTarget().GetDebugger().GetOutputFile()); + if (stream_sp) + { + stream_sp->Printf ("ThreadSanitizer debugger support is active.\n"); + } + + m_is_active = true; +} + +void +ThreadSanitizerRuntime::Deactivate() +{ + if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) + { + ProcessSP process_sp = GetProcessSP(); + if (process_sp) + { + process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id); + m_breakpoint_id = LLDB_INVALID_BREAK_ID; + } + } + m_is_active = false; +} diff --git a/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.h b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.h new file mode 100644 index 0000000..922d429 --- /dev/null +++ b/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.h @@ -0,0 +1,104 @@ +//===-- ThreadSanitizerRuntime.h --------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef liblldb_ThreadSanitizerRuntime_h_ +#define liblldb_ThreadSanitizerRuntime_h_ + +// C Includes +// C++ Includes +// Other libraries and framework includes +// Project includes +#include "lldb/lldb-private.h" +#include "lldb/Target/ABI.h" +#include "lldb/Target/InstrumentationRuntime.h" +#include "lldb/Target/Process.h" +#include "lldb/Core/StructuredData.h" + +namespace lldb_private { + +class ThreadSanitizerRuntime : public lldb_private::InstrumentationRuntime +{ +public: + ~ThreadSanitizerRuntime() override; + + static lldb::InstrumentationRuntimeSP + CreateInstance (const lldb::ProcessSP &process_sp); + + static void + Initialize(); + + static void + Terminate(); + + static lldb_private::ConstString + GetPluginNameStatic(); + + static lldb::InstrumentationRuntimeType + GetTypeStatic(); + + lldb_private::ConstString + GetPluginName() override + { + return GetPluginNameStatic(); + } + + virtual lldb::InstrumentationRuntimeType + GetType() { return GetTypeStatic(); } + + uint32_t + GetPluginVersion() override + { + return 1; + } + + void + ModulesDidLoad(lldb_private::ModuleList &module_list) override; + + bool + IsActive() override; + +private: + ThreadSanitizerRuntime(const lldb::ProcessSP &process_sp); + + lldb::ProcessSP + GetProcessSP () + { + return m_process_wp.lock(); + } + + lldb::ModuleSP + GetRuntimeModuleSP () + { + return m_runtime_module_wp.lock(); + } + + void + Activate(); + + void + Deactivate(); + + static bool + NotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id); + + StructuredData::ObjectSP + RetrieveReportData(ExecutionContextRef exe_ctx_ref); + + std::string + FormatDescription(StructuredData::ObjectSP report); + + bool m_is_active; + lldb::ModuleWP m_runtime_module_wp; + lldb::ProcessWP m_process_wp; + lldb::user_id_t m_breakpoint_id; +}; + +} // namespace lldb_private + +#endif // liblldb_ThreadSanitizerRuntime_h_