xref: /llvm-project/lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py (revision 999e75476ec22ca50cc4c309d34424fa265e244a)
1"""
2Test python scripted process in lldb
3"""
4
5import os, json, tempfile
6
7import lldb
8from lldbsuite.test.decorators import *
9from lldbsuite.test.lldbtest import *
10from lldbsuite.test import lldbutil
11from lldbsuite.test import lldbtest
12
13class StackCoreScriptedProcesTestCase(TestBase):
14
15    NO_DEBUG_INFO_TESTCASE = True
16
17    mydir = TestBase.compute_mydir(__file__)
18
19    def setUp(self):
20        TestBase.setUp(self)
21
22    def tearDown(self):
23        TestBase.tearDown(self)
24
25    def create_stack_skinny_corefile(self, file):
26        self.build()
27        target, process, thread, _ = lldbutil.run_to_source_breakpoint(self, "// break here",
28                                                                       lldb.SBFileSpec("baz.c"))
29        self.assertTrue(process.IsValid(), "Process is invalid.")
30        # FIXME: Use SBAPI to save the process corefile.
31        self.runCmd("process save-core -s stack  " + file)
32        self.assertTrue(os.path.exists(file), "No stack-only corefile found.")
33        self.assertTrue(self.dbg.DeleteTarget(target), "Couldn't delete target")
34
35    def get_module_with_name(self, target, name):
36        for module in target.modules:
37            if name in module.GetFileSpec().GetFilename():
38                return module
39        return None
40
41    @skipUnlessDarwin
42    @skipIfOutOfTreeDebugserver
43    def test_launch_scripted_process_stack_frames(self):
44        """Test that we can launch an lldb scripted process from the command
45        line, check its process ID and read string from memory."""
46        self.build()
47        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
48        self.assertTrue(target, VALID_TARGET)
49
50        main_module = self.get_module_with_name(target, 'a.out')
51        self.assertTrue(main_module, "Invalid main module.")
52        error = target.SetModuleLoadAddress(main_module, 0)
53        self.assertSuccess(error, "Reloading main module at offset 0 failed.")
54
55        scripted_dylib = self.get_module_with_name(target, 'libbaz.dylib')
56        self.assertTrue(scripted_dylib, "Dynamic library libbaz.dylib not found.")
57        self.assertEqual(scripted_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target), 0xffffffffffffffff)
58
59        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'
60        def cleanup():
61          del os.environ["SKIP_SCRIPTED_PROCESS_LAUNCH"]
62        self.addTearDownHook(cleanup)
63
64        scripted_process_example_relpath = 'stack_core_scripted_process.py'
65        self.runCmd("command script import " + os.path.join(self.getSourceDir(),
66                                                            scripted_process_example_relpath))
67
68        corefile_process = None
69        with tempfile.NamedTemporaryFile() as file:
70            self.create_stack_skinny_corefile(file.name)
71            corefile_target = self.dbg.CreateTarget(None)
72            corefile_process = corefile_target.LoadCore(self.getBuildArtifact(file.name))
73        self.assertTrue(corefile_process, PROCESS_IS_VALID)
74
75        structured_data = lldb.SBStructuredData()
76        structured_data.SetFromJSON(json.dumps({
77            "backing_target_idx" : self.dbg.GetIndexOfTarget(corefile_process.GetTarget()),
78            "libbaz_path" : self.getBuildArtifact("libbaz.dylib")
79        }))
80        launch_info = lldb.SBLaunchInfo(None)
81        launch_info.SetProcessPluginName("ScriptedProcess")
82        launch_info.SetScriptedProcessClassName("stack_core_scripted_process.StackCoreScriptedProcess")
83        launch_info.SetScriptedProcessDictionary(structured_data)
84
85        error = lldb.SBError()
86        process = target.Launch(launch_info, error)
87        self.assertSuccess(error)
88        self.assertTrue(process, PROCESS_IS_VALID)
89        self.assertEqual(process.GetProcessID(), 42)
90
91        self.assertEqual(process.GetNumThreads(), 2)
92        thread = process.GetSelectedThread()
93        self.assertTrue(thread, "Invalid thread.")
94        self.assertEqual(thread.GetName(), "StackCoreScriptedThread.thread-1")
95
96        self.assertTrue(target.triple, "Invalid target triple")
97        arch = target.triple.split('-')[0]
98        supported_arch = ['x86_64', 'arm64', 'arm64e']
99        self.assertIn(arch, supported_arch)
100        # When creating a corefile of a arm process, lldb saves the exception
101        # that triggers the breakpoint in the LC_NOTES of the corefile, so they
102        # can be reloaded with the corefile on the next debug session.
103        if arch in 'arm64e':
104            self.assertTrue(thread.GetStopReason(), lldb.eStopReasonException)
105        # However, it's architecture specific, and corefiles made from intel
106        # process don't save any metadata to retrieve to stop reason.
107        # To mitigate this, the StackCoreScriptedProcess will report a
108        # eStopReasonSignal with a SIGTRAP, mimicking what debugserver does.
109        else:
110            self.assertTrue(thread.GetStopReason(), lldb.eStopReasonSignal)
111
112        self.assertEqual(thread.GetNumFrames(), 5)
113        frame = thread.GetSelectedFrame()
114        self.assertTrue(frame, "Invalid frame.")
115        func = frame.GetFunction()
116        self.assertTrue(func, "Invalid function.")
117
118        self.assertIn("baz", frame.GetFunctionName())
119        self.assertEqual(frame.vars.GetSize(), 2)
120        self.assertEqual(int(frame.vars.GetFirstValueByName('j').GetValue()), 42 * 42)
121        self.assertEqual(int(frame.vars.GetFirstValueByName('k').GetValue()), 42)
122
123        corefile_dylib = self.get_module_with_name(corefile_target, 'libbaz.dylib')
124        self.assertTrue(corefile_dylib, "Dynamic library libbaz.dylib not found.")
125        scripted_dylib = self.get_module_with_name(target, 'libbaz.dylib')
126        self.assertTrue(scripted_dylib, "Dynamic library libbaz.dylib not found.")
127        self.assertEqual(scripted_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target),
128                         corefile_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target))
129