]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / packages / Python / lldbsuite / test / functionalities / load_unload / TestLoadUnload.py
1 """
2 Test that breakpoint by symbol name works correctly with dynamic libs.
3 """
4
5 from __future__ import print_function
6
7
8 import os
9 import time
10 import re
11 import lldb
12 from lldbsuite.test.decorators import *
13 from lldbsuite.test.lldbtest import *
14 from lldbsuite.test import lldbutil
15
16
17 @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
18 class LoadUnloadTestCase(TestBase):
19
20     def getCategories(self):
21         return ['basic_process']
22
23     mydir = TestBase.compute_mydir(__file__)
24
25     def setUp(self):
26         # Call super's setUp().
27         TestBase.setUp(self)
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         if not self.platformIsDarwin():
35             if not lldb.remote_platform and "LD_LIBRARY_PATH" in os.environ:
36                 self.runCmd(
37                     "settings set target.env-vars " +
38                     self.dylibPath +
39                     "=" +
40                     os.environ["LD_LIBRARY_PATH"] +
41                     ":" +
42                     os.getcwd())
43             else:
44                 if lldb.remote_platform:
45                     wd = lldb.remote_platform.GetWorkingDirectory()
46                 else:
47                     wd = os.getcwd()
48                 self.runCmd(
49                     "settings set target.env-vars " +
50                     self.dylibPath +
51                     "=" +
52                     wd)
53
54     def copy_shlibs_to_remote(self, hidden_dir=False):
55         """ Copies the shared libs required by this test suite to remote.
56         Does nothing in case of non-remote platforms.
57         """
58         if lldb.remote_platform:
59             cwd = os.getcwd()
60             shlibs = ['libloadunload_a.so', 'libloadunload_b.so',
61                       'libloadunload_c.so', 'libloadunload_d.so']
62             wd = lldb.remote_platform.GetWorkingDirectory()
63             for f in shlibs:
64                 err = lldb.remote_platform.Put(
65                     lldb.SBFileSpec(os.path.join(cwd, f)),
66                     lldb.SBFileSpec(os.path.join(wd, f)))
67                 if err.Fail():
68                     raise RuntimeError(
69                         "Unable copy '%s' to '%s'.\n>>> %s" %
70                         (f, wd, err.GetCString()))
71             if hidden_dir:
72                 shlib = 'libloadunload_d.so'
73                 hidden_dir = os.path.join(wd, 'hidden')
74                 hidden_file = os.path.join(hidden_dir, shlib)
75                 err = lldb.remote_platform.MakeDirectory(hidden_dir)
76                 if err.Fail():
77                     raise RuntimeError(
78                         "Unable to create a directory '%s'." % hidden_dir)
79                 err = lldb.remote_platform.Put(
80                     lldb.SBFileSpec(os.path.join(cwd, 'hidden', shlib)),
81                     lldb.SBFileSpec(hidden_file))
82                 if err.Fail():
83                     raise RuntimeError(
84                         "Unable copy 'libloadunload_d.so' to '%s'.\n>>> %s" %
85                         (wd, err.GetCString()))
86
87     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
88     @not_remote_testsuite_ready
89     @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
90     def test_modules_search_paths(self):
91         """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'."""
92
93         # Invoke the default build rule.
94         self.build()
95
96         if self.platformIsDarwin():
97             dylibName = 'libloadunload_d.dylib'
98         else:
99             dylibName = 'libloadunload_d.so'
100
101         # The directory with the dynamic library we did not link to.
102         new_dir = os.path.join(os.getcwd(), "hidden")
103
104         old_dylib = os.path.join(os.getcwd(), dylibName)
105         new_dylib = os.path.join(new_dir, dylibName)
106
107         exe = os.path.join(os.getcwd(), "a.out")
108         self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
109
110         self.expect("target modules list",
111                     substrs=[old_dylib])
112         # self.expect("target modules list -t 3",
113         #    patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()])
114         # Add an image search path substitution pair.
115         self.runCmd(
116             "target modules search-paths add %s %s" %
117             (os.getcwd(), new_dir))
118
119         self.expect("target modules search-paths list",
120                     substrs=[os.getcwd(), new_dir])
121
122         self.expect(
123             "target modules search-paths query %s" %
124             os.getcwd(),
125             "Image search path successfully transformed",
126             substrs=[new_dir])
127
128         # Obliterate traces of libd from the old location.
129         os.remove(old_dylib)
130         # Inform (DY)LD_LIBRARY_PATH of the new path, too.
131         env_cmd_string = "settings set target.env-vars " + self.dylibPath + "=" + new_dir
132         if self.TraceOn():
133             print("Set environment to: ", env_cmd_string)
134         self.runCmd(env_cmd_string)
135         self.runCmd("settings show target.env-vars")
136
137         remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath
138         self.addTearDownHook(
139             lambda: self.dbg.HandleCommand(remove_dyld_path_cmd))
140
141         self.runCmd("run")
142
143         self.expect(
144             "target modules list",
145             "LLDB successfully locates the relocated dynamic library",
146             substrs=[new_dylib])
147
148     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
149     @expectedFailureAndroid  # wrong source file shows up for hidden library
150     @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
151     def test_dyld_library_path(self):
152         """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else."""
153
154         # Invoke the default build rule.
155         self.build()
156         self.copy_shlibs_to_remote(hidden_dir=True)
157
158         exe = os.path.join(os.getcwd(), "a.out")
159         self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
160
161         # Shut off ANSI color usage so we don't get ANSI escape sequences
162         # mixed in with stop locations.
163         self.dbg.SetUseColor(False)
164
165         if self.platformIsDarwin():
166             dylibName = 'libloadunload_d.dylib'
167             dsymName = 'libloadunload_d.dylib.dSYM'
168         else:
169             dylibName = 'libloadunload_d.so'
170
171         # The directory to relocate the dynamic library and its debugging info.
172         special_dir = "hidden"
173         if lldb.remote_platform:
174             wd = lldb.remote_platform.GetWorkingDirectory()
175         else:
176             wd = os.getcwd()
177
178         old_dir = wd
179         new_dir = os.path.join(wd, special_dir)
180         old_dylib = os.path.join(old_dir, dylibName)
181
182         remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath
183         self.addTearDownHook(
184             lambda: self.dbg.HandleCommand(remove_dyld_path_cmd))
185
186         # For now we don't track (DY)LD_LIBRARY_PATH, so the old library will be in
187         # the modules list.
188         self.expect("target modules list",
189                     substrs=[os.path.basename(old_dylib)],
190                     matching=True)
191
192         lldbutil.run_break_set_by_file_and_line(
193             self, "d.cpp", self.line_d_function, num_expected_locations=1)
194         # After run, make sure the non-hidden library is picked up.
195         self.expect("run", substrs=["return", "700"])
196
197         self.runCmd("continue")
198
199         # Add the hidden directory first in the search path.
200         env_cmd_string = ("settings set target.env-vars %s=%s" %
201                           (self.dylibPath, new_dir))
202         if not self.platformIsDarwin():
203             env_cmd_string += ":" + wd
204         self.runCmd(env_cmd_string)
205
206         # This time, the hidden library should be picked up.
207         self.expect("run", substrs=["return", "12345"])
208
209     @expectedFailureAll(
210         bugnumber="llvm.org/pr25805",
211         hostoslist=["windows"],
212         compiler="gcc",
213         archs=["i386"],
214         triple='.*-android')
215     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
216     @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
217     def test_lldb_process_load_and_unload_commands(self):
218         """Test that lldb process load/unload command work correctly."""
219
220         # Invoke the default build rule.
221         self.build()
222         self.copy_shlibs_to_remote()
223
224         exe = os.path.join(os.getcwd(), "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         if lldb.remote_platform:
236             shlib_dir = lldb.remote_platform.GetWorkingDirectory()
237         else:
238             shlib_dir = self.mydir
239
240         if self.platformIsDarwin():
241             dylibName = 'libloadunload_a.dylib'
242         else:
243             dylibName = 'libloadunload_a.so'
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" %
256             dylibName,
257             "%s loaded correctly" %
258             dylibName,
259             patterns=[
260                 'Loading "%s".*ok' %
261                 dylibName,
262                 'Image [0-9]+ loaded'])
263
264         # Search for and match the "Image ([0-9]+) loaded" pattern.
265         output = self.res.GetOutput()
266         pattern = re.compile("Image ([0-9]+) loaded")
267         for l in output.split(os.linesep):
268             #print("l:", l)
269             match = pattern.search(l)
270             if match:
271                 break
272         index = match.group(1)
273
274         # Now we should have an entry for a_function.
275         self.expect(
276             "image lookup -n a_function",
277             "a_function should now exist",
278             patterns=[
279                 "1 match found .*%s" %
280                 dylibName])
281
282         # Use lldb 'process unload' to unload the dylib.
283         self.expect(
284             "process unload %s" %
285             index,
286             "%s unloaded correctly" %
287             dylibName,
288             patterns=[
289                 "Unloading .* with index %s.*ok" %
290                 index])
291
292         self.runCmd("process continue")
293
294     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
295     def test_load_unload(self):
296         """Test breakpoint by name works correctly with dlopen'ing."""
297
298         # Invoke the default build rule.
299         self.build()
300         self.copy_shlibs_to_remote()
301
302         exe = os.path.join(os.getcwd(), "a.out")
303         self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
304
305         # Break by function name a_function (not yet loaded).
306         lldbutil.run_break_set_by_symbol(
307             self, "a_function", num_expected_locations=0)
308
309         self.runCmd("run", RUN_SUCCEEDED)
310
311         # The stop reason of the thread should be breakpoint and at a_function.
312         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
313                     substrs=['stopped',
314                              'a_function',
315                              'stop reason = breakpoint'])
316
317         # The breakpoint should have a hit count of 1.
318         self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
319                     substrs=[' resolved, hit count = 1'])
320
321         # Issue the 'contnue' command.  We should stop agaian at a_function.
322         # The stop reason of the thread should be breakpoint and at a_function.
323         self.runCmd("continue")
324
325         # rdar://problem/8508987
326         # The a_function breakpoint should be encountered twice.
327         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
328                     substrs=['stopped',
329                              'a_function',
330                              'stop reason = breakpoint'])
331
332         # The breakpoint should have a hit count of 2.
333         self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
334                     substrs=[' resolved, hit count = 2'])
335
336     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
337     @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
338     def test_step_over_load(self):
339         """Test stepping over code that loads a shared library works correctly."""
340
341         # Invoke the default build rule.
342         self.build()
343         self.copy_shlibs_to_remote()
344
345         exe = os.path.join(os.getcwd(), "a.out")
346         self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
347
348         # Break by function name a_function (not yet loaded).
349         lldbutil.run_break_set_by_file_and_line(
350             self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
351
352         self.runCmd("run", RUN_SUCCEEDED)
353
354         # The stop reason of the thread should be breakpoint and at a_function.
355         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
356                     substrs=['stopped',
357                              'stop reason = breakpoint'])
358
359         self.runCmd(
360             "thread step-over",
361             "Stepping over function that loads library")
362
363         # The stop reason should be step end.
364         self.expect("thread list", "step over succeeded.",
365                     substrs=['stopped',
366                              'stop reason = step over'])
367
368     @skipIfFreeBSD  # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
369     @skipIfWindows  # Windows doesn't have dlopen and friends, dynamic libraries work differently
370     @unittest2.expectedFailure("llvm.org/pr25806")
371     def test_static_init_during_load(self):
372         """Test that we can set breakpoints correctly in static initializers"""
373
374         self.build()
375         self.copy_shlibs_to_remote()
376
377         exe = os.path.join(os.getcwd(), "a.out")
378         self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
379
380         a_init_bp_num = lldbutil.run_break_set_by_symbol(
381             self, "a_init", num_expected_locations=0)
382         b_init_bp_num = lldbutil.run_break_set_by_symbol(
383             self, "b_init", num_expected_locations=0)
384         d_init_bp_num = lldbutil.run_break_set_by_symbol(
385             self, "d_init", num_expected_locations=1)
386
387         self.runCmd("run", RUN_SUCCEEDED)
388
389         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
390                     substrs=['stopped',
391                              'd_init',
392                              'stop reason = breakpoint %d' % d_init_bp_num])
393
394         self.runCmd("continue")
395         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
396                     substrs=['stopped',
397                              'a_init',
398                              'stop reason = breakpoint %d' % a_init_bp_num])
399         self.expect("thread backtrace",
400                     substrs=['a_init',
401                              'dlopen',
402                              'main'])
403
404         self.runCmd("continue")
405         self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
406                     substrs=['stopped',
407                              'b_init',
408                              'stop reason = breakpoint %d' % b_init_bp_num])
409         self.expect("thread backtrace",
410                     substrs=['b_init',
411                              'dlopen',
412                              'main'])