1import lldb
2import json
3from lldbsuite.test.decorators import *
4from lldbsuite.test.lldbtest import *
5from lldbsuite.test import lldbutil
6
7class TestCase(TestBase):
8
9    mydir = TestBase.compute_mydir(__file__)
10
11    def setUp(self):
12        TestBase.setUp(self)
13        self.build()
14
15    NO_DEBUG_INFO_TESTCASE = True
16
17    def test_enable_disable(self):
18        """
19        Test "statistics disable" and "statistics enable". These don't do
20        anything anymore for cheap to gather statistics. In the future if
21        statistics are expensive to gather, we can enable the feature inside
22        of LLDB and test that enabling and disabling stops expesive information
23        from being gathered.
24        """
25        target = self.createTestTarget()
26
27        self.expect("statistics disable", substrs=['need to enable statistics before disabling'], error=True)
28        self.expect("statistics enable")
29        self.expect("statistics enable", substrs=['already enabled'], error=True)
30        self.expect("statistics disable")
31        self.expect("statistics disable", substrs=['need to enable statistics before disabling'], error=True)
32
33    def verify_key_in_dict(self, key, d, description):
34        self.assertEqual(key in d, True,
35            'make sure key "%s" is in dictionary %s' % (key, description))
36
37    def verify_key_not_in_dict(self, key, d, description):
38        self.assertEqual(key in d, False,
39            'make sure key "%s" is in dictionary %s' % (key, description))
40
41    def verify_keys(self, dict, description, keys_exist, keys_missing=None):
42        """
43            Verify that all keys in "keys_exist" list are top level items in
44            "dict", and that all keys in "keys_missing" do not exist as top
45            level items in "dict".
46        """
47        if keys_exist:
48            for key in keys_exist:
49                self.verify_key_in_dict(key, dict, description)
50        if keys_missing:
51            for key in keys_missing:
52                self.verify_key_not_in_dict(key, dict, description)
53
54    def verify_success_fail_count(self, stats, key, num_successes, num_fails):
55        self.verify_key_in_dict(key, stats, 'stats["%s"]' % (key))
56        success_fail_dict = stats[key]
57        self.assertEqual(success_fail_dict['successes'], num_successes,
58                         'make sure success count')
59        self.assertEqual(success_fail_dict['failures'], num_fails,
60                         'make sure success count')
61
62    def get_stats(self, options=None, log_path=None):
63        """
64            Get the output of the "statistics dump" with optional extra options
65            and return the JSON as a python dictionary.
66        """
67        # If log_path is set, open the path and emit the output of the command
68        # for debugging purposes.
69        if log_path is not None:
70            f = open(log_path, 'w')
71        else:
72            f = None
73        return_obj = lldb.SBCommandReturnObject()
74        command = "statistics dump "
75        if options is not None:
76            command += options
77        if f:
78            f.write('(lldb) %s\n' % (command))
79        self.ci.HandleCommand(command, return_obj, False)
80        metrics_json = return_obj.GetOutput()
81        if f:
82            f.write(metrics_json)
83        return json.loads(metrics_json)
84
85    def test_expressions_frame_var_counts(self):
86        lldbutil.run_to_source_breakpoint(self, "// break here",
87                                          lldb.SBFileSpec("main.c"))
88
89        self.expect("expr patatino", substrs=['27'])
90        stats = self.get_stats()
91        self.verify_success_fail_count(stats, 'expressionEvaluation', 1, 0)
92        self.expect("expr doesnt_exist", error=True,
93                    substrs=["undeclared identifier 'doesnt_exist'"])
94        # Doesn't successfully execute.
95        self.expect("expr int *i = nullptr; *i", error=True)
96        # Interpret an integer as an array with 3 elements is a failure for
97        # the "expr" command, but the expression evaluation will succeed and
98        # be counted as a success even though the "expr" options will for the
99        # command to fail. It is more important to track expression evaluation
100        # from all sources instead of just through the command, so this was
101        # changed. If we want to track command success and fails, we can do
102        # so using another metric.
103        self.expect("expr -Z 3 -- 1", error=True,
104                    substrs=["expression cannot be used with --element-count"])
105        # We should have gotten 3 new failures and the previous success.
106        stats = self.get_stats()
107        self.verify_success_fail_count(stats, 'expressionEvaluation', 2, 2)
108
109        self.expect("statistics enable")
110        # 'frame var' with enabled statistics will change stats.
111        self.expect("frame var", substrs=['27'])
112        stats = self.get_stats()
113        self.verify_success_fail_count(stats, 'frameVariable', 1, 0)
114
115    def test_default_no_run(self):
116        """Test "statistics dump" without running the target.
117
118        When we don't run the target, we expect to not see any 'firstStopTime'
119        or 'launchOrAttachTime' top level keys that measure the launch or
120        attach of the target.
121
122        Output expected to be something like:
123
124        (lldb) statistics dump
125        {
126          "targetCreateTime": 0.26566899599999999,
127          "expressionEvaluation": {
128            "failures": 0,
129            "successes": 0
130          },
131          "frameVariable": {
132            "failures": 0,
133            "successes": 0
134          },
135        }
136        """
137        target = self.createTestTarget()
138        stats = self.get_stats()
139        keys_exist = [
140            'expressionEvaluation',
141            'frameVariable',
142            'targetCreateTime',
143        ]
144        keys_missing = [
145            'firstStopTime',
146            'launchOrAttachTime'
147        ]
148        self.verify_keys(stats, '"stats"', keys_exist, keys_missing)
149        self.assertGreater(stats['targetCreateTime'], 0.0)
150
151    def test_default_with_run(self):
152        """Test "statistics dump" when running the target to a breakpoint.
153
154        When we run the target, we expect to see 'launchOrAttachTime' and
155        'firstStopTime' top level keys.
156
157        Output expected to be something like:
158
159        (lldb) statistics dump
160        {
161          "firstStopTime": 0.34164492800000001,
162          "launchOrAttachTime": 0.31969605400000001,
163          "targetCreateTime": 0.0040863039999999998
164          "expressionEvaluation": {
165            "failures": 0,
166            "successes": 0
167          },
168          "frameVariable": {
169            "failures": 0,
170            "successes": 0
171          },
172        }
173
174        """
175        target = self.createTestTarget()
176        lldbutil.run_to_source_breakpoint(self, "// break here",
177                                          lldb.SBFileSpec("main.c"))
178        stats = self.get_stats()
179        keys_exist = [
180            'expressionEvaluation',
181            'firstStopTime',
182            'frameVariable',
183            'launchOrAttachTime',
184            'targetCreateTime',
185        ]
186        self.verify_keys(stats, '"stats"', keys_exist, None)
187        self.assertGreater(stats['firstStopTime'], 0.0)
188        self.assertGreater(stats['launchOrAttachTime'], 0.0)
189        self.assertGreater(stats['targetCreateTime'], 0.0)
190