xref: /llvm-project/lldb/test/API/python_api/global_module_cache/TestGlobalModuleCache.py (revision 2684281d208612a746b05c891f346bd7b95318d5)
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    def test_OneTargetOneDebugger(self):
38        self.do_test(True, True)
39
40    # This behaves as implemented but that behavior is not desirable.
41    # This test tests for the desired behavior as an expected fail.
42    @skipIfWindows
43    @expectedFailureAll
44    def test_TwoTargetsOneDebugger(self):
45        self.do_test(False, True)
46
47    @skipIfWindows
48    @expectedFailureAll
49    def test_OneTargetTwoDebuggers(self):
50        self.do_test(True, False)
51
52    def do_test(self, one_target, one_debugger):
53        # Make sure that if we have one target, and we run, then
54        # change the binary and rerun, the binary (and any .o files
55        # if using dwarf in .o file debugging) get removed from the
56        # shared module cache.  They are no longer reachable.
57        debug_style = self.getDebugInfo()
58
59        # Before we do anything, clear the global module cache so we don't
60        # see objects from other runs:
61        lldb.SBDebugger.MemoryPressureDetected()
62
63        # Set up the paths for our two versions of main.c:
64        main_c_path = os.path.join(self.getBuildDir(), "main.c")
65        one_print_path = os.path.join(self.getSourceDir(), "one-print.c")
66        two_print_path = os.path.join(self.getSourceDir(), "two-print.c")
67        main_filespec = lldb.SBFileSpec(main_c_path)
68
69        # First copy the one-print.c to main.c in the build folder and
70        # build our a.out from there:
71        self.copy_to_main(one_print_path, main_c_path)
72        self.build(dictionary={"C_SOURCES": main_c_path, "EXE": "a.out"})
73
74        (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
75            self, "return counter;", main_filespec
76        )
77
78        # Make sure we ran the version we intended here:
79        self.check_counter_var(thread, 1)
80        process.Kill()
81
82        # Now copy two-print.c over main.c, rebuild, and rerun:
83        # os.unlink(target.GetExecutable().fullpath)
84        self.copy_to_main(two_print_path, main_c_path)
85
86        self.build(dictionary={"C_SOURCES": main_c_path, "EXE": "a.out"})
87        error = lldb.SBError()
88        if one_debugger:
89            if one_target:
90                (_, process, thread, _) = lldbutil.run_to_breakpoint_do_run(
91                    self, target, bkpt
92                )
93            else:
94                (target2, process2, thread, bkpt) = lldbutil.run_to_source_breakpoint(
95                    self, "return counter;", main_filespec
96                )
97        else:
98            if one_target:
99                new_debugger = lldb.SBDebugger().Create()
100                self.old_debugger = self.dbg
101                self.dbg = new_debugger
102                def cleanupDebugger(self):
103                    lldb.SBDebugger.Destroy(self.dbg)
104                    self.dbg = self.old_debugger
105                    self.old_debugger = None
106
107                self.addTearDownHook(cleanupDebugger)
108                (target2, process2, thread, bkpt) = lldbutil.run_to_source_breakpoint(
109                    self, "return counter;", main_filespec
110                )
111
112        # In two-print.c counter will be 2:
113        self.check_counter_var(thread, 2)
114
115        # If we made two targets, destroy the first one, that should free up the
116        # unreachable Modules:
117        if not one_target:
118            target.Clear()
119
120        num_a_dot_out_entries = 1
121        # For dSYM's there will be two lines of output, one for the a.out and one
122        # for the dSYM.
123        if debug_style == "dsym":
124            num_a_dot_out_entries += 1
125
126        error = self.check_image_list_result(num_a_dot_out_entries, 1)
127        # Even if this fails, MemoryPressureDetected should fix this.
128        lldb.SBDebugger.MemoryPressureDetected()
129        error_after_mpd = self.check_image_list_result(num_a_dot_out_entries, 1)
130        fail_msg = ""
131        if error != "":
132            fail_msg = "Error before MPD: " + error
133
134        if error_after_mpd != "":
135            fail_msg = fail_msg + "\nError after MPD: " + error_after_mpd
136        if fail_msg != "":
137            self.fail(fail_msg)
138
139    def check_image_list_result(self, num_a_dot_out, num_main_dot_o):
140        # Check the global module list, there should only be one a.out, and if we are
141        # doing dwarf in .o file, there should only be one .o file.  This returns
142        # an error string on error - rather than asserting, so you can stage this
143        # failing.
144        image_cmd_result = lldb.SBCommandReturnObject()
145        interp = self.dbg.GetCommandInterpreter()
146        interp.HandleCommand("image list -g", image_cmd_result)
147        if self.TraceOn():
148            print(f"Expected: a.out: {num_a_dot_out} main.o: {num_main_dot_o}")
149            print(image_cmd_result)
150
151        image_list_str = image_cmd_result.GetOutput()
152        image_list = image_list_str.splitlines()
153        found_a_dot_out = 0
154        found_main_dot_o = 0
155
156        for line in image_list:
157            # FIXME: force this to be at the end of the string:
158            if "a.out" in line:
159                found_a_dot_out += 1
160            if "main.o" in line:
161                found_main_dot_o += 1
162
163        if num_a_dot_out != found_a_dot_out:
164            return f"Got {found_a_dot_out} number of a.out's, expected {num_a_dot_out}"
165
166        if found_main_dot_o > 0 and num_main_dot_o != found_main_dot_o:
167            return f"Got {found_main_dot_o} number of main.o's, expected {num_main_dot_o}"
168
169        return ""
170