1"""
2Tests basic ThreadSanitizer support (detecting a data race).
3"""
4
5import lldb
6from lldbsuite.test.lldbtest import *
7from lldbsuite.test.decorators import *
8import lldbsuite.test.lldbutil as lldbutil
9import json
10
11
12class TsanBasicTestCase(TestBase):
13
14    mydir = TestBase.compute_mydir(__file__)
15
16    @expectedFailureAll(
17        oslist=["linux"],
18        bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)")
19    @expectedFailureNetBSD
20    @skipIfFreeBSD  # llvm.org/pr21136 runtimes not yet available by default
21    @skipIfRemote
22    @skipUnlessThreadSanitizer
23    @no_debug_info_test
24    def test(self):
25        self.build()
26        self.tsan_tests()
27
28    def setUp(self):
29        # Call super's setUp().
30        TestBase.setUp(self)
31        self.line_malloc = line_number('main.c', '// malloc line')
32        self.line_thread1 = line_number('main.c', '// thread1 line')
33        self.line_thread2 = line_number('main.c', '// thread2 line')
34
35    def tsan_tests(self):
36        exe = self.getBuildArtifact("a.out")
37        self.expect(
38            "file " + exe,
39            patterns=["Current executable set to .*a.out"])
40
41        self.runCmd("run")
42
43        stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason()
44        if stop_reason == lldb.eStopReasonExec:
45            # On OS X 10.10 and older, we need to re-exec to enable
46            # interceptors.
47            self.runCmd("continue")
48
49        # the stop reason of the thread should be breakpoint.
50        self.expect("thread list", "A data race should be detected",
51                    substrs=['stopped', 'stop reason = Data race detected'])
52
53        self.assertEqual(
54            self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(),
55            lldb.eStopReasonInstrumentation)
56
57        # test that the TSan dylib is present
58        self.expect(
59            "image lookup -n __tsan_get_current_report",
60            "__tsan_get_current_report should be present",
61            substrs=['1 match found'])
62
63        # We should be stopped in __tsan_on_report
64        process = self.dbg.GetSelectedTarget().process
65        thread = process.GetSelectedThread()
66        frame = thread.GetSelectedFrame()
67        self.assertIn("__tsan_on_report", frame.GetFunctionName())
68
69        # The stopped thread backtrace should contain either line1 or line2
70        # from main.c.
71        found = False
72        for i in range(0, thread.GetNumFrames()):
73            frame = thread.GetFrameAtIndex(i)
74            if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c":
75                if frame.GetLineEntry().GetLine() == self.line_thread1:
76                    found = True
77                if frame.GetLineEntry().GetLine() == self.line_thread2:
78                    found = True
79        self.assertTrue(found)
80
81        self.expect(
82            "thread info -s",
83            "The extended stop info should contain the TSan provided fields",
84            substrs=[
85                "instrumentation_class",
86                "description",
87                "mops"])
88
89        output_lines = self.res.GetOutput().split('\n')
90        json_line = '\n'.join(output_lines[2:])
91        data = json.loads(json_line)
92        self.assertEqual(data["instrumentation_class"], "ThreadSanitizer")
93        self.assertEqual(data["issue_type"], "data-race")
94        self.assertEqual(len(data["mops"]), 2)
95
96        backtraces = thread.GetStopReasonExtendedBacktraces(
97            lldb.eInstrumentationRuntimeTypeAddressSanitizer)
98        self.assertEqual(backtraces.GetSize(), 0)
99
100        backtraces = thread.GetStopReasonExtendedBacktraces(
101            lldb.eInstrumentationRuntimeTypeThreadSanitizer)
102        self.assertTrue(backtraces.GetSize() >= 2)
103
104        # First backtrace is a memory operation
105        thread = backtraces.GetThreadAtIndex(0)
106        found = False
107        for i in range(0, thread.GetNumFrames()):
108            frame = thread.GetFrameAtIndex(i)
109            if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c":
110                if frame.GetLineEntry().GetLine() == self.line_thread1:
111                    found = True
112                if frame.GetLineEntry().GetLine() == self.line_thread2:
113                    found = True
114        self.assertTrue(found)
115
116        # Second backtrace is a memory operation
117        thread = backtraces.GetThreadAtIndex(1)
118        found = False
119        for i in range(0, thread.GetNumFrames()):
120            frame = thread.GetFrameAtIndex(i)
121            if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c":
122                if frame.GetLineEntry().GetLine() == self.line_thread1:
123                    found = True
124                if frame.GetLineEntry().GetLine() == self.line_thread2:
125                    found = True
126        self.assertTrue(found)
127
128        self.runCmd("continue")
129
130        # the stop reason of the thread should be a SIGABRT.
131        self.expect("thread list", "We should be stopped due a SIGABRT",
132                    substrs=['stopped', 'stop reason = signal SIGABRT'])
133
134        # test that we're in pthread_kill now (TSan abort the process)
135        self.expect("thread list", "We should be stopped in pthread_kill",
136                    substrs=['pthread_kill'])
137