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    def test_lldb_process_load_and_unload_commands(self):
207        self.setSvr4Support(False)
208        self.run_lldb_process_load_and_unload_commands()
209
210    @expectedFailureAll(
211        bugnumber="llvm.org/pr25805",
212        hostoslist=["windows"],
213        triple='.*-android')
214    @expectedFailureAll(oslist=["windows"]) # process load not implemented
215    def test_lldb_process_load_and_unload_commands_with_svr4(self):
216        self.setSvr4Support(True)
217        self.run_lldb_process_load_and_unload_commands()
218
219    def run_lldb_process_load_and_unload_commands(self):
220        """Test that lldb process load/unload command work correctly."""
221        self.copy_shlibs_to_remote()
222
223        exe = self.getBuildArtifact("a.out")
224        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
225
226        # Break at main.cpp before the call to dlopen().
227        # Use lldb's process load command to load the dylib, instead.
228
229        lldbutil.run_break_set_by_file_and_line(
230            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
231
232        self.runCmd("run", RUN_SUCCEEDED)
233
234        ctx = self.platformContext
235        dylibName = ctx.shlib_prefix + 'loadunload_a.' + ctx.shlib_extension
236        localDylibPath = self.getBuildArtifact(dylibName)
237        if lldb.remote_platform:
238            wd = lldb.remote_platform.GetWorkingDirectory()
239            remoteDylibPath = lldbutil.join_remote_paths(wd, dylibName)
240        else:
241            remoteDylibPath = localDylibPath
242
243        # First make sure that we get some kind of error if process load fails.
244        # We print some error even if the load fails, which isn't formalized.
245        # The only plugin at present (Posix) that supports this says "unknown reasons".
246        # If another plugin shows up, let's require it uses "unknown error" as well.
247        non_existant_shlib = "/NoSuchDir/NoSuchSubdir/ReallyNo/NotAFile"
248        self.expect("process load %s"%(non_existant_shlib), error=True, matching=False,
249                    patterns=["unknown reasons"])
250
251
252        # Make sure that a_function does not exist at this point.
253        self.expect(
254            "image lookup -n a_function",
255            "a_function should not exist yet",
256            error=True,
257            matching=False,
258            patterns=["1 match found"])
259
260        # Use lldb 'process load' to load the dylib.
261        self.expect(
262            "process load %s --install=%s" % (localDylibPath, remoteDylibPath),
263            "%s loaded correctly" % dylibName,
264            patterns=[
265                'Loading "%s".*ok' % re.escape(localDylibPath),
266                'Image [0-9]+ loaded'])
267
268        # Search for and match the "Image ([0-9]+) loaded" pattern.
269        output = self.res.GetOutput()
270        pattern = re.compile("Image ([0-9]+) loaded")
271        for l in output.split(os.linesep):
272            self.trace("l:", l)
273            match = pattern.search(l)
274            if match:
275                break
276        index = match.group(1)
277
278        # Now we should have an entry for a_function.
279        self.expect(
280            "image lookup -n a_function",
281            "a_function should now exist",
282            patterns=[
283                "1 match found .*%s" %
284                dylibName])
285
286        # Use lldb 'process unload' to unload the dylib.
287        self.expect(
288            "process unload %s" %
289            index,
290            "%s unloaded correctly" %
291            dylibName,
292            patterns=[
293                "Unloading .* with index %s.*ok" %
294                index])
295
296        self.runCmd("process continue")
297
298    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
299    def test_load_unload(self):
300        self.setSvr4Support(False)
301        self.run_load_unload()
302
303    @expectedFailureAll(oslist=["windows"]) # breakpoint not hit
304    def test_load_unload_with_svr4(self):
305        self.setSvr4Support(True)
306        self.run_load_unload()
307
308    def run_load_unload(self):
309        """Test breakpoint by name works correctly with dlopen'ing."""
310        self.copy_shlibs_to_remote()
311
312        exe = self.getBuildArtifact("a.out")
313        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
314
315        # Break by function name a_function (not yet loaded).
316        lldbutil.run_break_set_by_symbol(
317            self, "a_function", num_expected_locations=0)
318
319        self.runCmd("run", RUN_SUCCEEDED)
320
321        # The stop reason of the thread should be breakpoint and at a_function.
322        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
323                    substrs=['stopped',
324                             'a_function',
325                             'stop reason = breakpoint'])
326
327        # The breakpoint should have a hit count of 1.
328        lldbutil.check_breakpoint(self, bpno = 1, expected_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        lldbutil.check_breakpoint(self, bpno = 1, expected_hit_count = 2)
343
344    def test_step_over_load(self):
345        self.setSvr4Support(False)
346        self.run_step_over_load()
347
348    def test_step_over_load_with_svr4(self):
349        self.setSvr4Support(True)
350        self.run_step_over_load()
351
352    def run_step_over_load(self):
353        """Test stepping over code that loads a shared library works correctly."""
354        self.copy_shlibs_to_remote()
355
356        exe = self.getBuildArtifact("a.out")
357        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
358
359        # Break by function name a_function (not yet loaded).
360        lldbutil.run_break_set_by_file_and_line(
361            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
362
363        self.runCmd("run", RUN_SUCCEEDED)
364
365        # The stop reason of the thread should be breakpoint and at a_function.
366        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
367                    substrs=['stopped',
368                             'stop reason = breakpoint'])
369
370        self.runCmd(
371            "thread step-over",
372            "Stepping over function that loads library")
373
374        # The stop reason should be step end.
375        self.expect("thread list", "step over succeeded.",
376                    substrs=['stopped',
377                             'stop reason = step over'])
378
379    # We can't find a breakpoint location for d_init before launching because
380    # executable dependencies are resolved relative to the debuggers PWD. Bug?
381    @expectedFailureAll(oslist=["freebsd", "linux", "netbsd"], triple=no_match('aarch64-.*-android'))
382    def test_static_init_during_load(self):
383        """Test that we can set breakpoints correctly in static initializers"""
384        self.copy_shlibs_to_remote()
385
386        exe = self.getBuildArtifact("a.out")
387        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
388
389        a_init_bp_num = lldbutil.run_break_set_by_symbol(
390            self, "a_init", num_expected_locations=0)
391        b_init_bp_num = lldbutil.run_break_set_by_symbol(
392            self, "b_init", num_expected_locations=0)
393        d_init_bp_num = lldbutil.run_break_set_by_symbol(
394            self, "d_init", num_expected_locations=1)
395
396        self.runCmd("run", RUN_SUCCEEDED)
397
398        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
399                    substrs=['stopped',
400                             'd_init',
401                             'stop reason = breakpoint %d' % d_init_bp_num])
402
403        self.runCmd("continue")
404        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
405                    substrs=['stopped',
406                             'b_init',
407                             'stop reason = breakpoint %d' % b_init_bp_num])
408        self.expect("thread backtrace",
409                    substrs=['b_init',
410                             'dylib_open',
411                             'main'])
412
413        self.runCmd("continue")
414        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
415                    substrs=['stopped',
416                             'a_init',
417                             'stop reason = breakpoint %d' % a_init_bp_num])
418        self.expect("thread backtrace",
419                    substrs=['a_init',
420                             'dylib_open',
421                             'main'])
422