1"""
2Test basics of Minidump debugging.
3"""
4
5from six import iteritems
6
7import shutil
8
9import lldb
10from lldbsuite.test.decorators import *
11from lldbsuite.test.lldbtest import *
12from lldbsuite.test import lldbutil
13
14
15class MiniDumpNewTestCase(TestBase):
16
17    mydir = TestBase.compute_mydir(__file__)
18
19    NO_DEBUG_INFO_TESTCASE = True
20
21    _linux_x86_64_pid = 29917
22    _linux_x86_64_not_crashed_pid = 29939
23    _linux_x86_64_not_crashed_pid_offset = 0xD967
24
25    def process_from_yaml(self, yaml_file):
26        minidump_path = self.getBuildArtifact(os.path.basename(yaml_file) + ".dmp")
27        self.yaml2obj(yaml_file, minidump_path)
28        self.target = self.dbg.CreateTarget(None)
29        self.process = self.target.LoadCore(minidump_path)
30        return self.process
31
32    def check_state(self):
33        with open(os.devnull) as devnul:
34            # sanitize test output
35            self.dbg.SetOutputFileHandle(devnul, False)
36            self.dbg.SetErrorFileHandle(devnul, False)
37
38            self.assertTrue(self.process.is_stopped)
39
40            # Process.Continue
41            error = self.process.Continue()
42            self.assertFalse(error.Success())
43            self.assertTrue(self.process.is_stopped)
44
45            # Thread.StepOut
46            thread = self.process.GetSelectedThread()
47            thread.StepOut()
48            self.assertTrue(self.process.is_stopped)
49
50            # command line
51            self.dbg.HandleCommand('s')
52            self.assertTrue(self.process.is_stopped)
53            self.dbg.HandleCommand('c')
54            self.assertTrue(self.process.is_stopped)
55
56            # restore file handles
57            self.dbg.SetOutputFileHandle(None, False)
58            self.dbg.SetErrorFileHandle(None, False)
59
60    def test_loadcore_error_status(self):
61        """Test the SBTarget.LoadCore(core, error) overload."""
62        minidump_path = self.getBuildArtifact("linux-x86_64.dmp")
63        self.yaml2obj("linux-x86_64.yaml", minidump_path)
64        self.target = self.dbg.CreateTarget(None)
65        error = lldb.SBError()
66        self.process = self.target.LoadCore(minidump_path, error)
67        self.assertTrue(self.process, PROCESS_IS_VALID)
68        self.assertTrue(error.Success())
69
70    def test_loadcore_error_status_failure(self):
71        """Test the SBTarget.LoadCore(core, error) overload."""
72        self.target = self.dbg.CreateTarget(None)
73        error = lldb.SBError()
74        self.process = self.target.LoadCore("non-existent.dmp", error)
75        self.assertFalse(self.process, PROCESS_IS_VALID)
76        self.assertTrue(error.Fail())
77
78    def test_process_info_in_minidump(self):
79        """Test that lldb can read the process information from the Minidump."""
80        self.process_from_yaml("linux-x86_64.yaml")
81        self.assertTrue(self.process, PROCESS_IS_VALID)
82        self.assertEqual(self.process.GetNumThreads(), 1)
83        self.assertEqual(self.process.GetProcessID(), self._linux_x86_64_pid)
84        self.check_state()
85
86    def test_memory_region_name(self):
87        self.process_from_yaml("regions-linux-map.yaml")
88        result = lldb.SBCommandReturnObject()
89        addr_region_name_pairs = [
90            ("0x400d9000", "/system/bin/app_process"),
91            ("0x400db000", "/system/bin/app_process"),
92            ("0x400dd000", "/system/bin/linker"),
93            ("0x400ed000", "/system/bin/linker"),
94            ("0x400ee000", "/system/bin/linker"),
95            ("0x400fb000", "/system/lib/liblog.so"),
96            ("0x400fc000", "/system/lib/liblog.so"),
97            ("0x400fd000", "/system/lib/liblog.so"),
98            ("0x400ff000", "/system/lib/liblog.so"),
99            ("0x40100000", "/system/lib/liblog.so"),
100            ("0x40101000", "/system/lib/libc.so"),
101            ("0x40122000", "/system/lib/libc.so"),
102            ("0x40123000", "/system/lib/libc.so"),
103            ("0x40167000", "/system/lib/libc.so"),
104            ("0x40169000", "/system/lib/libc.so"),
105        ]
106        ci = self.dbg.GetCommandInterpreter()
107        for (addr, region_name) in addr_region_name_pairs:
108            command = 'memory region ' + addr
109            ci.HandleCommand(command, result, False)
110            message = 'Ensure memory "%s" shows up in output for "%s"' % (
111                region_name, command)
112            self.assertTrue(region_name in result.GetOutput(), message)
113
114    def test_thread_info_in_minidump(self):
115        """Test that lldb can read the thread information from the Minidump."""
116        self.process_from_yaml("linux-x86_64.yaml")
117        self.check_state()
118        # This process crashed due to a segmentation fault in its
119        # one and only thread.
120        self.assertEqual(self.process.GetNumThreads(), 1)
121        thread = self.process.GetThreadAtIndex(0)
122        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal)
123        stop_description = thread.GetStopDescription(256)
124        self.assertTrue("SIGSEGV" in stop_description)
125
126    def test_stack_info_in_minidump(self):
127        """Test that we can see a trivial stack in a breakpad-generated Minidump."""
128        # target create linux-x86_64 -c linux-x86_64.dmp
129        self.dbg.CreateTarget("linux-x86_64")
130        self.target = self.dbg.GetSelectedTarget()
131        self.process = self.target.LoadCore("linux-x86_64.dmp")
132        self.check_state()
133        self.assertEqual(self.process.GetNumThreads(), 1)
134        self.assertEqual(self.process.GetProcessID(), self._linux_x86_64_pid)
135        thread = self.process.GetThreadAtIndex(0)
136        # frame #0: linux-x86_64`crash()
137        # frame #1: linux-x86_64`_start
138        self.assertEqual(thread.GetNumFrames(), 2)
139        frame = thread.GetFrameAtIndex(0)
140        self.assertTrue(frame.IsValid())
141        self.assertTrue(frame.GetModule().IsValid())
142        pc = frame.GetPC()
143        eip = frame.FindRegister("pc")
144        self.assertTrue(eip.IsValid())
145        self.assertEqual(pc, eip.GetValueAsUnsigned())
146
147    def test_snapshot_minidump_dump_requested(self):
148        """Test that if we load a snapshot minidump file (meaning the process
149        did not crash) with exception code "DUMP_REQUESTED" there is no stop reason."""
150        # target create -c linux-x86_64_not_crashed.dmp
151        self.dbg.CreateTarget(None)
152        self.target = self.dbg.GetSelectedTarget()
153        self.process = self.target.LoadCore("linux-x86_64_not_crashed.dmp")
154        self.check_state()
155        self.assertEqual(self.process.GetNumThreads(), 1)
156        thread = self.process.GetThreadAtIndex(0)
157        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone)
158        stop_description = thread.GetStopDescription(256)
159        self.assertEqual(stop_description, "")
160
161    def test_snapshot_minidump_null_exn_code(self):
162        """Test that if we load a snapshot minidump file (meaning the process
163        did not crash) with exception code zero there is no stop reason."""
164        self.process_from_yaml("linux-x86_64_null_signal.yaml")
165        self.check_state()
166        self.assertEqual(self.process.GetNumThreads(), 1)
167        thread = self.process.GetThreadAtIndex(0)
168        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone)
169        stop_description = thread.GetStopDescription(256)
170        self.assertEqual(stop_description, "")
171
172    def check_register_unsigned(self, set, name, expected):
173        reg_value = set.GetChildMemberWithName(name)
174        self.assertTrue(reg_value.IsValid(),
175                        'Verify we have a register named "%s"' % (name))
176        self.assertEqual(reg_value.GetValueAsUnsigned(), expected,
177                         'Verify "%s" == %i' % (name, expected))
178
179    def check_register_string_value(self, set, name, expected, format):
180        reg_value = set.GetChildMemberWithName(name)
181        self.assertTrue(reg_value.IsValid(),
182                        'Verify we have a register named "%s"' % (name))
183        if format is not None:
184            reg_value.SetFormat(format)
185        self.assertEqual(reg_value.GetValue(), expected,
186                         'Verify "%s" has string value "%s"' % (name,
187                                                                expected))
188
189    def test_arm64_registers(self):
190        """Test ARM64 registers from a breakpad created minidump."""
191        self.process_from_yaml("arm64-macos.yaml")
192        self.check_state()
193        self.assertEqual(self.process.GetNumThreads(), 1)
194        thread = self.process.GetThreadAtIndex(0)
195        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone)
196        stop_description = thread.GetStopDescription(256)
197        self.assertEqual(stop_description, "")
198        registers = thread.GetFrameAtIndex(0).GetRegisters()
199        # Verify the GPR registers are all correct
200        # Verify x0 - x31 register values
201        gpr = registers.GetValueAtIndex(0)
202        for i in range(32):
203            v = i+1 | i+2 << 32 | i+3 << 48
204            w = i+1
205            self.check_register_unsigned(gpr, 'x%i' % (i), v)
206            self.check_register_unsigned(gpr, 'w%i' % (i), w)
207        # Verify arg1 - arg8 register values
208        for i in range(1, 9):
209            v = i | i+1 << 32 | i+2 << 48
210            self.check_register_unsigned(gpr, 'arg%i' % (i), v)
211        i = 29
212        v = i+1 | i+2 << 32 | i+3 << 48
213        self.check_register_unsigned(gpr, 'fp', v)
214        i = 30
215        v = i+1 | i+2 << 32 | i+3 << 48
216        self.check_register_unsigned(gpr, 'lr', v)
217        i = 31
218        v = i+1 | i+2 << 32 | i+3 << 48
219        self.check_register_unsigned(gpr, 'sp', v)
220        self.check_register_unsigned(gpr, 'pc', 0x1000)
221        self.check_register_unsigned(gpr, 'cpsr', 0x11223344)
222        self.check_register_unsigned(gpr, 'psr', 0x11223344)
223
224        # Verify the FPR registers are all correct
225        fpr = registers.GetValueAtIndex(1)
226        for i in range(32):
227            v = "0x"
228            d = "0x"
229            s = "0x"
230            h = "0x"
231            for j in range(i+15, i-1, -1):
232                v += "%2.2x" % (j)
233            for j in range(i+7, i-1, -1):
234                d += "%2.2x" % (j)
235            for j in range(i+3, i-1, -1):
236                s += "%2.2x" % (j)
237            for j in range(i+1, i-1, -1):
238                h += "%2.2x" % (j)
239            self.check_register_string_value(fpr, "v%i" % (i), v,
240                                             lldb.eFormatHex)
241            self.check_register_string_value(fpr, "d%i" % (i), d,
242                                             lldb.eFormatHex)
243            self.check_register_string_value(fpr, "s%i" % (i), s,
244                                             lldb.eFormatHex)
245            self.check_register_string_value(fpr, "h%i" % (i), h,
246                                             lldb.eFormatHex)
247        self.check_register_unsigned(gpr, 'fpsr', 0x55667788)
248        self.check_register_unsigned(gpr, 'fpcr', 0x99aabbcc)
249
250    def verify_arm_registers(self, apple=False):
251        """
252            Verify values of all ARM registers from a breakpad created
253            minidump.
254        """
255        if apple:
256            self.process_from_yaml("arm-macos.yaml")
257        else:
258            self.process_from_yaml("arm-linux.yaml")
259        self.check_state()
260        self.assertEqual(self.process.GetNumThreads(), 1)
261        thread = self.process.GetThreadAtIndex(0)
262        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone)
263        stop_description = thread.GetStopDescription(256)
264        self.assertEqual(stop_description, "")
265        registers = thread.GetFrameAtIndex(0).GetRegisters()
266        # Verify the GPR registers are all correct
267        # Verify x0 - x31 register values
268        gpr = registers.GetValueAtIndex(0)
269        for i in range(1, 16):
270            self.check_register_unsigned(gpr, 'r%i' % (i), i+1)
271        # Verify arg1 - arg4 register values
272        for i in range(1, 5):
273            self.check_register_unsigned(gpr, 'arg%i' % (i), i)
274        if apple:
275            self.check_register_unsigned(gpr, 'fp', 0x08)
276        else:
277            self.check_register_unsigned(gpr, 'fp', 0x0c)
278        self.check_register_unsigned(gpr, 'lr', 0x0f)
279        self.check_register_unsigned(gpr, 'sp', 0x0e)
280        self.check_register_unsigned(gpr, 'pc', 0x10)
281        self.check_register_unsigned(gpr, 'cpsr', 0x11223344)
282
283        # Verify the FPR registers are all correct
284        fpr = registers.GetValueAtIndex(1)
285        # Check d0 - d31
286        self.check_register_unsigned(gpr, 'fpscr', 0x55667788aabbccdd)
287        for i in range(32):
288            value = (i+1) | (i+1) << 8 | (i+1) << 32 | (i+1) << 48
289            self.check_register_unsigned(fpr, "d%i" % (i), value)
290        # Check s0 - s31
291        for i in range(32):
292            i_val = (i >> 1) + 1
293            if i & 1:
294                value = "%#8.8x" % (i_val | i_val << 16)
295            else:
296                value = "%#8.8x" % (i_val | i_val << 8)
297            self.check_register_string_value(fpr, "s%i" % (i), value,
298                                             lldb.eFormatHex)
299        # Check q0 - q15
300        for i in range(15):
301            a = i * 2 + 1
302            b = a + 1
303            value = ("0x00%2.2x00%2.2x0000%2.2x%2.2x"
304                     "00%2.2x00%2.2x0000%2.2x%2.2x") % (b, b, b, b, a, a, a, a)
305            self.check_register_string_value(fpr, "q%i" % (i), value,
306                                             lldb.eFormatHex)
307
308    def test_linux_arm_registers(self):
309        """Test Linux ARM registers from a breakpad created minidump.
310
311           The frame pointer is R11 for linux.
312        """
313        self.verify_arm_registers(apple=False)
314
315    def test_apple_arm_registers(self):
316        """Test Apple ARM registers from a breakpad created minidump.
317
318           The frame pointer is R7 for linux.
319        """
320        self.verify_arm_registers(apple=True)
321
322    def do_test_deeper_stack(self, binary, core, pid):
323        target = self.dbg.CreateTarget(binary)
324        process = target.LoadCore(core)
325        thread = process.GetThreadAtIndex(0)
326
327        self.assertEqual(process.GetProcessID(), pid)
328
329        expected_stack = {1: 'bar', 2: 'foo', 3: '_start'}
330        self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack))
331        for index, name in iteritems(expected_stack):
332            frame = thread.GetFrameAtIndex(index)
333            self.assertTrue(frame.IsValid())
334            function_name = frame.GetFunctionName()
335            self.assertTrue(name in function_name)
336
337    @skipIfLLVMTargetMissing("X86")
338    def test_deeper_stack_in_minidump(self):
339        """Test that we can examine a more interesting stack in a Minidump."""
340        # Launch with the Minidump, and inspect the stack.
341        # target create linux-x86_64_not_crashed -c linux-x86_64_not_crashed.dmp
342        self.do_test_deeper_stack("linux-x86_64_not_crashed",
343                                  "linux-x86_64_not_crashed.dmp",
344                                  self._linux_x86_64_not_crashed_pid)
345
346    def do_change_pid_in_minidump(self, core, newcore, offset, oldpid, newpid):
347        """ This assumes that the minidump is breakpad generated on Linux -
348        meaning that the PID in the file will be an ascii string part of
349        /proc/PID/status which is written in the file
350        """
351        shutil.copyfile(core, newcore)
352        with open(newcore, "rb+") as f:
353            f.seek(offset)
354            currentpid = f.read(5).decode('utf-8')
355            self.assertEqual(currentpid, oldpid)
356
357            f.seek(offset)
358            if len(newpid) < len(oldpid):
359                newpid += " " * (len(oldpid) - len(newpid))
360            newpid += "\n"
361            f.write(newpid.encode('utf-8'))
362
363    def test_deeper_stack_in_minidump_with_same_pid_running(self):
364        """Test that we read the information from the core correctly even if we
365        have a running process with the same PID"""
366        new_core = self.getBuildArtifact("linux-x86_64_not_crashed-pid.dmp")
367        self.do_change_pid_in_minidump("linux-x86_64_not_crashed.dmp",
368                                       new_core,
369                                       self._linux_x86_64_not_crashed_pid_offset,
370                                       str(self._linux_x86_64_not_crashed_pid),
371                                       str(os.getpid()))
372        self.do_test_deeper_stack("linux-x86_64_not_crashed", new_core, os.getpid())
373
374    def test_two_cores_same_pid(self):
375        """Test that we handle the situation if we have two core files with the same PID """
376        new_core = self.getBuildArtifact("linux-x86_64_not_crashed-pid.dmp")
377        self.do_change_pid_in_minidump("linux-x86_64_not_crashed.dmp",
378                                       new_core,
379                                       self._linux_x86_64_not_crashed_pid_offset,
380                                       str(self._linux_x86_64_not_crashed_pid),
381                                       str(self._linux_x86_64_pid))
382        self.do_test_deeper_stack("linux-x86_64_not_crashed",
383                                  new_core, self._linux_x86_64_pid)
384        self.test_stack_info_in_minidump()
385
386    def test_local_variables_in_minidump(self):
387        """Test that we can examine local variables in a Minidump."""
388        # Launch with the Minidump, and inspect a local variable.
389        # target create linux-x86_64_not_crashed -c linux-x86_64_not_crashed.dmp
390        self.target = self.dbg.CreateTarget("linux-x86_64_not_crashed")
391        self.process = self.target.LoadCore("linux-x86_64_not_crashed.dmp")
392        self.check_state()
393        thread = self.process.GetThreadAtIndex(0)
394        frame = thread.GetFrameAtIndex(1)
395        value = frame.EvaluateExpression('x')
396        self.assertEqual(value.GetValueAsSigned(), 3)
397
398    def test_memory_regions_in_minidump(self):
399        """Test memory regions from a Minidump"""
400        self.process_from_yaml("regions-linux-map.yaml")
401        self.check_state()
402
403        regions_count = 19
404        region_info_list = self.process.GetMemoryRegions()
405        self.assertEqual(region_info_list.GetSize(), regions_count)
406
407        def check_region(index, start, end, read, write, execute, mapped, name):
408            region_info = lldb.SBMemoryRegionInfo()
409            self.assertTrue(
410                self.process.GetMemoryRegionInfo(start, region_info).Success())
411            self.assertEqual(start, region_info.GetRegionBase())
412            self.assertEqual(end, region_info.GetRegionEnd())
413            self.assertEqual(read, region_info.IsReadable())
414            self.assertEqual(write, region_info.IsWritable())
415            self.assertEqual(execute, region_info.IsExecutable())
416            self.assertEqual(mapped, region_info.IsMapped())
417            self.assertEqual(name, region_info.GetName())
418
419            # Ensure we have the same regions as SBMemoryRegionInfoList contains.
420            if index >= 0 and index < regions_count:
421                region_info_from_list = lldb.SBMemoryRegionInfo()
422                self.assertTrue(region_info_list.GetMemoryRegionAtIndex(
423                    index, region_info_from_list))
424                self.assertEqual(region_info_from_list, region_info)
425
426        a = "/system/bin/app_process"
427        b = "/system/bin/linker"
428        c = "/system/lib/liblog.so"
429        d = "/system/lib/libc.so"
430        n = None
431        max_int = 0xffffffffffffffff
432
433        # Test address before the first entry comes back with nothing mapped up
434        # to first valid region info
435        check_region(-1, 0x00000000, 0x400d9000, False, False, False, False, n)
436        check_region( 0, 0x400d9000, 0x400db000, True,  False, True,  True,  a)
437        check_region( 1, 0x400db000, 0x400dc000, True,  False, False, True,  a)
438        check_region( 2, 0x400dc000, 0x400dd000, True,  True,  False, True,  n)
439        check_region( 3, 0x400dd000, 0x400ec000, True,  False, True,  True,  b)
440        check_region( 4, 0x400ec000, 0x400ed000, True,  False, False, True,  n)
441        check_region( 5, 0x400ed000, 0x400ee000, True,  False, False, True,  b)
442        check_region( 6, 0x400ee000, 0x400ef000, True,  True,  False, True,  b)
443        check_region( 7, 0x400ef000, 0x400fb000, True,  True,  False, True,  n)
444        check_region( 8, 0x400fb000, 0x400fc000, True,  False, True,  True,  c)
445        check_region( 9, 0x400fc000, 0x400fd000, True,  True,  True,  True,  c)
446        check_region(10, 0x400fd000, 0x400ff000, True,  False, True,  True,  c)
447        check_region(11, 0x400ff000, 0x40100000, True,  False, False, True,  c)
448        check_region(12, 0x40100000, 0x40101000, True,  True,  False, True,  c)
449        check_region(13, 0x40101000, 0x40122000, True,  False, True,  True,  d)
450        check_region(14, 0x40122000, 0x40123000, True,  True,  True,  True,  d)
451        check_region(15, 0x40123000, 0x40167000, True,  False, True,  True,  d)
452        check_region(16, 0x40167000, 0x40169000, True,  False, False, True,  d)
453        check_region(17, 0x40169000, 0x4016b000, True,  True,  False, True,  d)
454        check_region(18, 0x4016b000, 0x40176000, True,  True,  False, True,  n)
455        check_region(-1, 0x40176000, max_int,    False, False, False, False, n)
456