xref: /llvm-project/lldb/test/API/python_api/global_module_cache/TestGlobalModuleCache.py (revision 1bce61e6b01b38e04260be4f422bbae59c34c766)
1"""
2Test the use of the global module cache in lldb
3"""
4
5import lldb
6
7from lldbsuite.test.decorators import *
8from lldbsuite.test.lldbtest import *
9from lldbsuite.test import lldbutil
10import os
11import shutil
12from pathlib import Path
13import time
14
15class GlobalModuleCacheTestCase(TestBase):
16    # NO_DEBUG_INFO_TESTCASE = True
17
18    def check_counter_var(self, thread, value):
19        frame = thread.frames[0]
20        var = frame.FindVariable("counter")
21        self.assertTrue(var.GetError().Success(), "Got counter variable")
22        self.assertEqual(var.GetValueAsUnsigned(), value, "This was one-print")
23
24    def copy_to_main(self, src, dst):
25        # We are relying on the source file being newer than the .o file from
26        # a previous build, so sleep a bit here to ensure that the touch is later.
27        time.sleep(2)
28        try:
29            shutil.copy(src, dst)
30        except:
31            self.fail(f"Could not copy {src} to {dst}")
32        Path(dst).touch()
33
34    # The rerun tests indicate rerunning on Windows doesn't really work, so
35    # this one won't either.
36    @skipIfWindows
37    # On Arm and AArch64 Linux, this test attempts to pop a thread plan when
38    # we only have the base plan remaining. Skip it until we can figure out
39    # the bug this is exposing.
40    @skipIf(oslist=["linux"], archs=["arm", "aarch64"])
41    def test_OneTargetOneDebugger(self):
42        self.do_test(True, True)
43
44    # This behaves as implemented but that behavior is not desirable.
45    # This test tests for the desired behavior as an expected fail.
46    @skipIfWindows
47    @expectedFailureAll
48    def test_TwoTargetsOneDebugger(self):
49        self.do_test(False, True)
50
51    @skipIfWindows
52    @expectedFailureAll
53    def test_OneTargetTwoDebuggers(self):
54        self.do_test(True, False)
55
56    def do_test(self, one_target, one_debugger):
57        # Make sure that if we have one target, and we run, then
58        # change the binary and rerun, the binary (and any .o files
59        # if using dwarf in .o file debugging) get removed from the
60        # shared module cache.  They are no longer reachable.
61        debug_style = self.getDebugInfo()
62
63        # Before we do anything, clear the global module cache so we don't
64        # see objects from other runs:
65        lldb.SBDebugger.MemoryPressureDetected()
66
67        # Set up the paths for our two versions of main.c:
68        main_c_path = os.path.join(self.getBuildDir(), "main.c")
69        one_print_path = os.path.join(self.getSourceDir(), "one-print.c")
70        two_print_path = os.path.join(self.getSourceDir(), "two-print.c")
71        main_filespec = lldb.SBFileSpec(main_c_path)
72
73        # First copy the one-print.c to main.c in the build folder and
74        # build our a.out from there:
75        self.copy_to_main(one_print_path, main_c_path)
76        self.build(dictionary={"C_SOURCES": main_c_path, "EXE": "a.out"})
77
78        (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
79            self, "return counter;", main_filespec
80        )
81
82        # Make sure we ran the version we intended here:
83        self.check_counter_var(thread, 1)
84        process.Kill()
85
86        # Now copy two-print.c over main.c, rebuild, and rerun:
87        # os.unlink(target.GetExecutable().fullpath)
88        self.copy_to_main(two_print_path, main_c_path)
89
90        self.build(dictionary={"C_SOURCES": main_c_path, "EXE": "a.out"})
91        error = lldb.SBError()
92        if one_debugger:
93            if one_target:
94                (_, process, thread, _) = lldbutil.run_to_breakpoint_do_run(
95                    self, target, bkpt
96                )
97            else:
98                (target2, process2, thread, bkpt) = lldbutil.run_to_source_breakpoint(
99                    self, "return counter;", main_filespec
100                )
101        else:
102            if one_target:
103                new_debugger = lldb.SBDebugger().Create()
104                self.old_debugger = self.dbg
105                self.dbg = new_debugger
106                def cleanupDebugger(self):
107                    lldb.SBDebugger.Destroy(self.dbg)
108                    self.dbg = self.old_debugger
109                    self.old_debugger = None
110
111                self.addTearDownHook(cleanupDebugger)
112                (target2, process2, thread, bkpt) = lldbutil.run_to_source_breakpoint(
113                    self, "return counter;", main_filespec
114                )
115
116        # In two-print.c counter will be 2:
117        self.check_counter_var(thread, 2)
118
119        # If we made two targets, destroy the first one, that should free up the
120        # unreachable Modules:
121        if not one_target:
122            target.Clear()
123
124        num_a_dot_out_entries = 1
125        # For dSYM's there will be two lines of output, one for the a.out and one
126        # for the dSYM.
127        if debug_style == "dsym":
128            num_a_dot_out_entries += 1
129
130        error = self.check_image_list_result(num_a_dot_out_entries, 1)
131        # Even if this fails, MemoryPressureDetected should fix this.
132        lldb.SBDebugger.MemoryPressureDetected()
133        error_after_mpd = self.check_image_list_result(num_a_dot_out_entries, 1)
134        fail_msg = ""
135        if error != "":
136            fail_msg = "Error before MPD: " + error
137
138        if error_after_mpd != "":
139            fail_msg = fail_msg + "\nError after MPD: " + error_after_mpd
140        if fail_msg != "":
141            self.fail(fail_msg)
142
143    def check_image_list_result(self, num_a_dot_out, num_main_dot_o):
144        # Check the global module list, there should only be one a.out, and if we are
145        # doing dwarf in .o file, there should only be one .o file.  This returns
146        # an error string on error - rather than asserting, so you can stage this
147        # failing.
148        image_cmd_result = lldb.SBCommandReturnObject()
149        interp = self.dbg.GetCommandInterpreter()
150        interp.HandleCommand("image list -g", image_cmd_result)
151        if self.TraceOn():
152            print(f"Expected: a.out: {num_a_dot_out} main.o: {num_main_dot_o}")
153            print(image_cmd_result)
154
155        image_list_str = image_cmd_result.GetOutput()
156        image_list = image_list_str.splitlines()
157        found_a_dot_out = 0
158        found_main_dot_o = 0
159
160        for line in image_list:
161            # FIXME: force this to be at the end of the string:
162            if "a.out" in line:
163                found_a_dot_out += 1
164            if "main.o" in line:
165                found_main_dot_o += 1
166
167        if num_a_dot_out != found_a_dot_out:
168            return f"Got {found_a_dot_out} number of a.out's, expected {num_a_dot_out}"
169
170        if found_main_dot_o > 0 and num_main_dot_o != found_main_dot_o:
171            return f"Got {found_main_dot_o} number of main.o's, expected {num_main_dot_o}"
172
173        return ""
174