1"""
2Test that breakpoint by symbol name works correctly with dynamic libs.
3"""
4
5from __future__ import print_function
6
7
8import os
9import re
10import lldb
11from lldbsuite.test.decorators import *
12from lldbsuite.test.lldbtest import *
13from lldbsuite.test import lldbutil
14
15
16class LoadUnloadTestCase(TestBase):
17
18    mydir = TestBase.compute_mydir(__file__)
19
20    NO_DEBUG_INFO_TESTCASE = True
21
22    def setUp(self):
23        # Call super's setUp().
24        TestBase.setUp(self)
25        self.setup_test()
26        # Invoke the default build rule.
27        self.build()
28        # Find the line number to break for main.cpp.
29        self.line = line_number(
30            'main.cpp',
31            '// Set break point at this line for test_lldb_process_load_and_unload_commands().')
32        self.line_d_function = line_number(
33            'd.cpp', '// Find this line number within d_dunction().')
34
35    def setup_test(self):
36        lldbutil.mkdir_p(self.getBuildArtifact("hidden"))
37        if lldb.remote_platform:
38            path = lldb.remote_platform.GetWorkingDirectory()
39        else:
40            path = self.getBuildDir()
41            if self.dylibPath in os.environ:
42                sep = self.platformContext.shlib_path_separator
43                path = os.environ[self.dylibPath] + sep + path
44        self.runCmd("settings append target.env-vars '{}={}'".format(self.dylibPath, path))
45        self.default_path = path
46
47    def copy_shlibs_to_remote(self, hidden_dir=False):
48        """ Copies the shared libs required by this test suite to remote.
49        Does nothing in case of non-remote platforms.
50        """
51        if lldb.remote_platform:
52            ext = 'so'
53            if self.platformIsDarwin():
54                ext = 'dylib'
55
56            shlibs = ['libloadunload_a.' + ext, 'libloadunload_b.' + ext,
57                      'libloadunload_c.' + ext, 'libloadunload_d.' + ext]
58            wd = lldb.remote_platform.GetWorkingDirectory()
59            cwd = os.getcwd()
60            for f in shlibs:
61                err = lldb.remote_platform.Put(
62                    lldb.SBFileSpec(self.getBuildArtifact(f)),
63                    lldb.SBFileSpec(os.path.join(wd, f)))
64                if err.Fail():
65                    raise RuntimeError(
66                        "Unable copy '%s' to '%s'.\n>>> %s" %
67                        (f, wd, err.GetCString()))
68            if hidden_dir:
69                shlib = 'libloadunload_d.' + ext
70                hidden_dir = os.path.join(wd, 'hidden')
71                hidden_file = os.path.join(hidden_dir, shlib)
72                err = lldb.remote_platform.MakeDirectory(hidden_dir)
73                if err.Fail():
74                    raise RuntimeError(
75                        "Unable to create a directory '%s'." % hidden_dir)
76                err = lldb.remote_platform.Put(
77                    lldb.SBFileSpec(os.path.join('hidden', shlib)),
78                    lldb.SBFileSpec(hidden_file))
79                if err.Fail():
80                    raise RuntimeError(
81                        "Unable copy 'libloadunload_d.so' to '%s'.\n>>> %s" %
82                        (wd, err.GetCString()))
83
84    def setSvr4Support(self, enabled):
85        self.runCmd(
86            "settings set plugin.process.gdb-remote.use-libraries-svr4 {enabled}".format(
87                enabled="true" if enabled else "false"
88            )
89        )
90
91    # libloadunload_d.so does not appear in the image list because executable
92    # dependencies are resolved relative to the debuggers PWD. Bug?
93    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"])
94    @skipIfRemote
95    @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
96    def test_modules_search_paths(self):
97        """Test target modules list after loading a different copy of the library libd.dylib, and verifies that it works with 'target modules search-paths add'."""
98        if self.platformIsDarwin():
99            dylibName = 'libloadunload_d.dylib'
100        else:
101            dylibName = 'libloadunload_d.so'
102
103        # The directory with the dynamic library we did not link to.
104        new_dir = os.path.join(self.getBuildDir(), "hidden")
105
106        old_dylib = os.path.join(self.getBuildDir(), dylibName)
107        new_dylib = os.path.join(new_dir, dylibName)
108        exe = self.getBuildArtifact("a.out")
109        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
110
111        self.expect("target modules list",
112                    substrs=[old_dylib])
113        # self.expect("target modules list -t 3",
114        #    patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()])
115        # Add an image search path substitution pair.
116        self.runCmd(
117            "target modules search-paths add %s %s" %
118            (self.getBuildDir(), new_dir))
119
120        self.expect("target modules search-paths list",
121                    substrs=[self.getBuildDir(), new_dir])
122
123        self.expect(
124            "target modules search-paths query %s" %
125            self.getBuildDir(),
126            "Image search path successfully transformed",
127            substrs=[new_dir])
128
129        # Obliterate traces of libd from the old location.
130        os.remove(old_dylib)
131        # Inform (DY)LD_LIBRARY_PATH of the new path, too.
132        env_cmd_string = "settings replace target.env-vars " + self.dylibPath + "=" + new_dir
133        if self.TraceOn():
134            print("Set environment to: ", env_cmd_string)
135        self.runCmd(env_cmd_string)
136        self.runCmd("settings show target.env-vars")
137
138        self.runCmd("run")
139
140        self.expect(
141            "target modules list",
142            "LLDB successfully locates the relocated dynamic library",
143            substrs=[new_dylib])
144
145    # libloadunload_d.so does not appear in the image list because executable
146    # dependencies are resolved relative to the debuggers PWD. Bug?
147    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"])
148    @expectedFailureAndroid  # wrong source file shows up for hidden library
149    @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
150    @skipIfDarwinEmbedded
151    def test_dyld_library_path(self):
152        """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else."""
153        self.copy_shlibs_to_remote(hidden_dir=True)
154
155        exe = self.getBuildArtifact("a.out")
156        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
157
158        # Shut off ANSI color usage so we don't get ANSI escape sequences
159        # mixed in with stop locations.
160        self.dbg.SetUseColor(False)
161
162        if self.platformIsDarwin():
163            dylibName = 'libloadunload_d.dylib'
164            dsymName = 'libloadunload_d.dylib.dSYM'
165        else:
166            dylibName = 'libloadunload_d.so'
167
168        # The directory to relocate the dynamic library and its debugging info.
169        special_dir = "hidden"
170        if lldb.remote_platform:
171            wd = lldb.remote_platform.GetWorkingDirectory()
172        else:
173            wd = self.getBuildDir()
174
175        old_dir = wd
176        new_dir = os.path.join(wd, special_dir)
177        old_dylib = os.path.join(old_dir, dylibName)
178
179        # For now we don't track (DY)LD_LIBRARY_PATH, so the old
180        # library will be in the modules list.
181        self.expect("target modules list",
182                    substrs=[os.path.basename(old_dylib)],
183                    matching=True)
184
185        lldbutil.run_break_set_by_file_and_line(
186            self, "d.cpp", self.line_d_function, num_expected_locations=1)
187        # After run, make sure the non-hidden library is picked up.
188        self.expect("run", substrs=["return", "700"])
189
190        self.runCmd("continue")
191
192        # Add the hidden directory first in the search path.
193        env_cmd_string = ("settings set target.env-vars %s=%s%s%s" %
194                          (self.dylibPath, new_dir,
195                              self.platformContext.shlib_path_separator, self.default_path))
196        self.runCmd(env_cmd_string)
197
198        # This time, the hidden library should be picked up.
199        self.expect("run", substrs=["return", "12345"])
200
201    @expectedFailureAll(
202        bugnumber="llvm.org/pr25805",
203        hostoslist=["windows"],
204        triple='.*-android')
205    @expectedFailureAll(oslist=["windows"]) # process load not implemented
206    @expectedFailureAll(oslist=["linux"], archs=["arm"]) # Fails on ubuntu jammy
207    def test_lldb_process_load_and_unload_commands(self):
208        self.setSvr4Support(False)
209        self.run_lldb_process_load_and_unload_commands()
210
211    @expectedFailureAll(
212        bugnumber="llvm.org/pr25805",
213        hostoslist=["windows"],
214        triple='.*-android')
215    @expectedFailureAll(oslist=["windows"]) # process load not implemented
216    def test_lldb_process_load_and_unload_commands_with_svr4(self):
217        self.setSvr4Support(True)
218        self.run_lldb_process_load_and_unload_commands()
219
220    def run_lldb_process_load_and_unload_commands(self):
221        """Test that lldb process load/unload command work correctly."""
222        self.copy_shlibs_to_remote()
223
224        exe = self.getBuildArtifact("a.out")
225        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
226
227        # Break at main.cpp before the call to dlopen().
228        # Use lldb's process load command to load the dylib, instead.
229
230        lldbutil.run_break_set_by_file_and_line(
231            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
232
233        self.runCmd("run", RUN_SUCCEEDED)
234
235        ctx = self.platformContext
236        dylibName = ctx.shlib_prefix + 'loadunload_a.' + ctx.shlib_extension
237        localDylibPath = self.getBuildArtifact(dylibName)
238        if lldb.remote_platform:
239            wd = lldb.remote_platform.GetWorkingDirectory()
240            remoteDylibPath = lldbutil.join_remote_paths(wd, dylibName)
241        else:
242            remoteDylibPath = localDylibPath
243
244        # First make sure that we get some kind of error if process load fails.
245        # We print some error even if the load fails, which isn't formalized.
246        # The only plugin at present (Posix) that supports this says "unknown reasons".
247        # If another plugin shows up, let's require it uses "unknown error" as well.
248        non_existant_shlib = "/NoSuchDir/NoSuchSubdir/ReallyNo/NotAFile"
249        self.expect("process load %s"%(non_existant_shlib), error=True, matching=False,
250                    patterns=["unknown reasons"])
251
252
253        # Make sure that a_function does not exist at this point.
254        self.expect(
255            "image lookup -n a_function",
256            "a_function should not exist yet",
257            error=True,
258            matching=False,
259            patterns=["1 match found"])
260
261        # Use lldb 'process load' to load the dylib.
262        self.expect(
263            "process load %s --install=%s" % (localDylibPath, remoteDylibPath),
264            "%s loaded correctly" % dylibName,
265            patterns=[
266                'Loading "%s".*ok' % re.escape(localDylibPath),
267                'Image [0-9]+ loaded'])
268
269        # Search for and match the "Image ([0-9]+) loaded" pattern.
270        output = self.res.GetOutput()
271        pattern = re.compile("Image ([0-9]+) loaded")
272        for l in output.split(os.linesep):
273            self.trace("l:", l)
274            match = pattern.search(l)
275            if match:
276                break
277        index = match.group(1)
278
279        # Now we should have an entry for a_function.
280        self.expect(
281            "image lookup -n a_function",
282            "a_function should now exist",
283            patterns=[
284                "1 match found .*%s" %
285                dylibName])
286
287        # Use lldb 'process unload' to unload the dylib.
288        self.expect(
289            "process unload %s" %
290            index,
291            "%s unloaded correctly" %
292            dylibName,
293            patterns=[
294                "Unloading .* with index %s.*ok" %
295                index])
296
297        self.runCmd("process continue")
298
299    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
300    @expectedFailureAll(oslist=["linux"], archs=["arm"]) # Fails on ubuntu jammy
301    def test_load_unload(self):
302        self.setSvr4Support(False)
303        self.run_load_unload()
304
305    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
306    def test_load_unload_with_svr4(self):
307        self.setSvr4Support(True)
308        self.run_load_unload()
309
310    def run_load_unload(self):
311        """Test breakpoint by name works correctly with dlopen'ing."""
312        self.copy_shlibs_to_remote()
313
314        exe = self.getBuildArtifact("a.out")
315        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
316
317        # Break by function name a_function (not yet loaded).
318        lldbutil.run_break_set_by_symbol(
319            self, "a_function", num_expected_locations=0)
320
321        self.runCmd("run", RUN_SUCCEEDED)
322
323        # The stop reason of the thread should be breakpoint and at a_function.
324        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
325                    substrs=['stopped',
326                             'a_function',
327                             'stop reason = breakpoint'])
328
329        # The breakpoint should have a hit count of 1.
330        lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 1)
331
332        # Issue the 'continue' command.  We should stop agaian at a_function.
333        # The stop reason of the thread should be breakpoint and at a_function.
334        self.runCmd("continue")
335
336        # rdar://problem/8508987
337        # The a_function breakpoint should be encountered twice.
338        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
339                    substrs=['stopped',
340                             'a_function',
341                             'stop reason = breakpoint'])
342
343        # The breakpoint should have a hit count of 2.
344        lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 2)
345
346    def test_step_over_load(self):
347        self.setSvr4Support(False)
348        self.run_step_over_load()
349
350    def test_step_over_load_with_svr4(self):
351        self.setSvr4Support(True)
352        self.run_step_over_load()
353
354    def run_step_over_load(self):
355        """Test stepping over code that loads a shared library works correctly."""
356        self.copy_shlibs_to_remote()
357
358        exe = self.getBuildArtifact("a.out")
359        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
360
361        # Break by function name a_function (not yet loaded).
362        lldbutil.run_break_set_by_file_and_line(
363            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
364
365        self.runCmd("run", RUN_SUCCEEDED)
366
367        # The stop reason of the thread should be breakpoint and at a_function.
368        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
369                    substrs=['stopped',
370                             'stop reason = breakpoint'])
371
372        self.runCmd(
373            "thread step-over",
374            "Stepping over function that loads library")
375
376        # The stop reason should be step end.
377        self.expect("thread list", "step over succeeded.",
378                    substrs=['stopped',
379                             'stop reason = step over'])
380
381    # We can't find a breakpoint location for d_init before launching because
382    # executable dependencies are resolved relative to the debuggers PWD. Bug?
383    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], triple=no_match('aarch64-.*-android'))
384    def test_static_init_during_load(self):
385        """Test that we can set breakpoints correctly in static initializers"""
386        self.copy_shlibs_to_remote()
387
388        exe = self.getBuildArtifact("a.out")
389        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
390
391        a_init_bp_num = lldbutil.run_break_set_by_symbol(
392            self, "a_init", num_expected_locations=0)
393        b_init_bp_num = lldbutil.run_break_set_by_symbol(
394            self, "b_init", num_expected_locations=0)
395        d_init_bp_num = lldbutil.run_break_set_by_symbol(
396            self, "d_init", num_expected_locations=1)
397
398        self.runCmd("run", RUN_SUCCEEDED)
399
400        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
401                    substrs=['stopped',
402                             'd_init',
403                             'stop reason = breakpoint %d' % d_init_bp_num])
404
405        self.runCmd("continue")
406        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
407                    substrs=['stopped',
408                             'b_init',
409                             'stop reason = breakpoint %d' % b_init_bp_num])
410        self.expect("thread backtrace",
411                    substrs=['b_init',
412                             'dylib_open',
413                             'main'])
414
415        self.runCmd("continue")
416        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
417                    substrs=['stopped',
418                             'a_init',
419                             'stop reason = breakpoint %d' % a_init_bp_num])
420        self.expect("thread backtrace",
421                    substrs=['a_init',
422                             'dylib_open',
423                             'main'])
424