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    @skipIfReproducer # VFS is a snapshot.
97    def test_modules_search_paths(self):
98        """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'."""
99        if self.platformIsDarwin():
100            dylibName = 'libloadunload_d.dylib'
101        else:
102            dylibName = 'libloadunload_d.so'
103
104        # The directory with the dynamic library we did not link to.
105        new_dir = os.path.join(self.getBuildDir(), "hidden")
106
107        old_dylib = os.path.join(self.getBuildDir(), dylibName)
108        new_dylib = os.path.join(new_dir, dylibName)
109        exe = self.getBuildArtifact("a.out")
110        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
111
112        self.expect("target modules list",
113                    substrs=[old_dylib])
114        # self.expect("target modules list -t 3",
115        #    patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()])
116        # Add an image search path substitution pair.
117        self.runCmd(
118            "target modules search-paths add %s %s" %
119            (self.getBuildDir(), new_dir))
120
121        self.expect("target modules search-paths list",
122                    substrs=[self.getBuildDir(), new_dir])
123
124        self.expect(
125            "target modules search-paths query %s" %
126            self.getBuildDir(),
127            "Image search path successfully transformed",
128            substrs=[new_dir])
129
130        # Obliterate traces of libd from the old location.
131        os.remove(old_dylib)
132        # Inform (DY)LD_LIBRARY_PATH of the new path, too.
133        env_cmd_string = "settings replace target.env-vars " + self.dylibPath + "=" + new_dir
134        if self.TraceOn():
135            print("Set environment to: ", env_cmd_string)
136        self.runCmd(env_cmd_string)
137        self.runCmd("settings show target.env-vars")
138
139        self.runCmd("run")
140
141        self.expect(
142            "target modules list",
143            "LLDB successfully locates the relocated dynamic library",
144            substrs=[new_dylib])
145
146    # libloadunload_d.so does not appear in the image list because executable
147    # dependencies are resolved relative to the debuggers PWD. Bug?
148    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"])
149    @expectedFailureAndroid  # wrong source file shows up for hidden library
150    @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
151    @skipIfDarwinEmbedded
152    def test_dyld_library_path(self):
153        """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else."""
154        self.copy_shlibs_to_remote(hidden_dir=True)
155
156        exe = self.getBuildArtifact("a.out")
157        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
158
159        # Shut off ANSI color usage so we don't get ANSI escape sequences
160        # mixed in with stop locations.
161        self.dbg.SetUseColor(False)
162
163        if self.platformIsDarwin():
164            dylibName = 'libloadunload_d.dylib'
165            dsymName = 'libloadunload_d.dylib.dSYM'
166        else:
167            dylibName = 'libloadunload_d.so'
168
169        # The directory to relocate the dynamic library and its debugging info.
170        special_dir = "hidden"
171        if lldb.remote_platform:
172            wd = lldb.remote_platform.GetWorkingDirectory()
173        else:
174            wd = self.getBuildDir()
175
176        old_dir = wd
177        new_dir = os.path.join(wd, special_dir)
178        old_dylib = os.path.join(old_dir, dylibName)
179
180        # For now we don't track (DY)LD_LIBRARY_PATH, so the old
181        # library will be in the modules list.
182        self.expect("target modules list",
183                    substrs=[os.path.basename(old_dylib)],
184                    matching=True)
185
186        lldbutil.run_break_set_by_file_and_line(
187            self, "d.cpp", self.line_d_function, num_expected_locations=1)
188        # After run, make sure the non-hidden library is picked up.
189        self.expect("run", substrs=["return", "700"])
190
191        self.runCmd("continue")
192
193        # Add the hidden directory first in the search path.
194        env_cmd_string = ("settings set target.env-vars %s=%s%s%s" %
195                          (self.dylibPath, new_dir,
196                              self.platformContext.shlib_path_separator, self.default_path))
197        self.runCmd(env_cmd_string)
198
199        # This time, the hidden library should be picked up.
200        self.expect("run", substrs=["return", "12345"])
201
202    @expectedFailureAll(
203        bugnumber="llvm.org/pr25805",
204        hostoslist=["windows"],
205        triple='.*-android')
206    @expectedFailureAll(oslist=["windows"]) # process load not implemented
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    @skipIfReproducer # FIXME: Unexpected packet during (passive) replay
221    def run_lldb_process_load_and_unload_commands(self):
222        """Test that lldb process load/unload command work correctly."""
223        self.copy_shlibs_to_remote()
224
225        exe = self.getBuildArtifact("a.out")
226        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
227
228        # Break at main.cpp before the call to dlopen().
229        # Use lldb's process load command to load the dylib, instead.
230
231        lldbutil.run_break_set_by_file_and_line(
232            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
233
234        self.runCmd("run", RUN_SUCCEEDED)
235
236        ctx = self.platformContext
237        dylibName = ctx.shlib_prefix + 'loadunload_a.' + ctx.shlib_extension
238        localDylibPath = self.getBuildArtifact(dylibName)
239        if lldb.remote_platform:
240            wd = lldb.remote_platform.GetWorkingDirectory()
241            remoteDylibPath = lldbutil.join_remote_paths(wd, dylibName)
242        else:
243            remoteDylibPath = localDylibPath
244
245        # Make sure that a_function does not exist at this point.
246        self.expect(
247            "image lookup -n a_function",
248            "a_function should not exist yet",
249            error=True,
250            matching=False,
251            patterns=["1 match found"])
252
253        # Use lldb 'process load' to load the dylib.
254        self.expect(
255            "process load %s --install=%s" % (localDylibPath, remoteDylibPath),
256            "%s loaded correctly" % dylibName,
257            patterns=[
258                'Loading "%s".*ok' % re.escape(localDylibPath),
259                'Image [0-9]+ loaded'])
260
261        # Search for and match the "Image ([0-9]+) loaded" pattern.
262        output = self.res.GetOutput()
263        pattern = re.compile("Image ([0-9]+) loaded")
264        for l in output.split(os.linesep):
265            self.trace("l:", l)
266            match = pattern.search(l)
267            if match:
268                break
269        index = match.group(1)
270
271        # Now we should have an entry for a_function.
272        self.expect(
273            "image lookup -n a_function",
274            "a_function should now exist",
275            patterns=[
276                "1 match found .*%s" %
277                dylibName])
278
279        # Use lldb 'process unload' to unload the dylib.
280        self.expect(
281            "process unload %s" %
282            index,
283            "%s unloaded correctly" %
284            dylibName,
285            patterns=[
286                "Unloading .* with index %s.*ok" %
287                index])
288
289        self.runCmd("process continue")
290
291    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
292    def test_load_unload(self):
293        self.setSvr4Support(False)
294        self.run_load_unload()
295
296    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
297    def test_load_unload_with_svr4(self):
298        self.setSvr4Support(True)
299        self.run_load_unload()
300
301    def run_load_unload(self):
302        """Test breakpoint by name works correctly with dlopen'ing."""
303        self.copy_shlibs_to_remote()
304
305        exe = self.getBuildArtifact("a.out")
306        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
307
308        # Break by function name a_function (not yet loaded).
309        lldbutil.run_break_set_by_symbol(
310            self, "a_function", num_expected_locations=0)
311
312        self.runCmd("run", RUN_SUCCEEDED)
313
314        # The stop reason of the thread should be breakpoint and at a_function.
315        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
316                    substrs=['stopped',
317                             'a_function',
318                             'stop reason = breakpoint'])
319
320        # The breakpoint should have a hit count of 1.
321        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
322                    substrs=[' resolved, hit count = 1'])
323
324        # Issue the 'continue' command.  We should stop agaian at a_function.
325        # The stop reason of the thread should be breakpoint and at a_function.
326        self.runCmd("continue")
327
328        # rdar://problem/8508987
329        # The a_function breakpoint should be encountered twice.
330        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
331                    substrs=['stopped',
332                             'a_function',
333                             'stop reason = breakpoint'])
334
335        # The breakpoint should have a hit count of 2.
336        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
337                    substrs=[' resolved, hit count = 2'])
338
339    def test_step_over_load(self):
340        self.setSvr4Support(False)
341        self.run_step_over_load()
342
343    def test_step_over_load_with_svr4(self):
344        self.setSvr4Support(True)
345        self.run_step_over_load()
346
347    def run_step_over_load(self):
348        """Test stepping over code that loads a shared library works correctly."""
349        self.copy_shlibs_to_remote()
350
351        exe = self.getBuildArtifact("a.out")
352        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
353
354        # Break by function name a_function (not yet loaded).
355        lldbutil.run_break_set_by_file_and_line(
356            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
357
358        self.runCmd("run", RUN_SUCCEEDED)
359
360        # The stop reason of the thread should be breakpoint and at a_function.
361        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
362                    substrs=['stopped',
363                             'stop reason = breakpoint'])
364
365        self.runCmd(
366            "thread step-over",
367            "Stepping over function that loads library")
368
369        # The stop reason should be step end.
370        self.expect("thread list", "step over succeeded.",
371                    substrs=['stopped',
372                             'stop reason = step over'])
373
374    # We can't find a breakpoint location for d_init before launching because
375    # executable dependencies are resolved relative to the debuggers PWD. Bug?
376    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], triple=no_match('aarch64-.*-android'))
377    def test_static_init_during_load(self):
378        """Test that we can set breakpoints correctly in static initializers"""
379        self.copy_shlibs_to_remote()
380
381        exe = self.getBuildArtifact("a.out")
382        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
383
384        a_init_bp_num = lldbutil.run_break_set_by_symbol(
385            self, "a_init", num_expected_locations=0)
386        b_init_bp_num = lldbutil.run_break_set_by_symbol(
387            self, "b_init", num_expected_locations=0)
388        d_init_bp_num = lldbutil.run_break_set_by_symbol(
389            self, "d_init", num_expected_locations=1)
390
391        self.runCmd("run", RUN_SUCCEEDED)
392
393        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
394                    substrs=['stopped',
395                             'd_init',
396                             'stop reason = breakpoint %d' % d_init_bp_num])
397
398        self.runCmd("continue")
399        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
400                    substrs=['stopped',
401                             'b_init',
402                             'stop reason = breakpoint %d' % b_init_bp_num])
403        self.expect("thread backtrace",
404                    substrs=['b_init',
405                             'dylib_open',
406                             'main'])
407
408        self.runCmd("continue")
409        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
410                    substrs=['stopped',
411                             'a_init',
412                             'stop reason = breakpoint %d' % a_init_bp_num])
413        self.expect("thread backtrace",
414                    substrs=['a_init',
415                             'dylib_open',
416                             'main'])
417