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