1""" 2Test SBTarget APIs. 3""" 4 5from __future__ import print_function 6 7 8import unittest2 9import os 10import lldb 11from lldbsuite.test.decorators import * 12from lldbsuite.test.lldbtest import * 13from lldbsuite.test import lldbutil 14 15 16class TargetAPITestCase(TestBase): 17 18 mydir = TestBase.compute_mydir(__file__) 19 20 def setUp(self): 21 # Call super's setUp(). 22 TestBase.setUp(self) 23 # Find the line number to of function 'c'. 24 self.line1 = line_number( 25 'main.c', '// Find the line number for breakpoint 1 here.') 26 self.line2 = line_number( 27 'main.c', '// Find the line number for breakpoint 2 here.') 28 self.line_main = line_number( 29 "main.c", "// Set a break at entry to main.") 30 31 # rdar://problem/9700873 32 # Find global variable value fails for dwarf if inferior not started 33 # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) 34 # 35 # It does not segfaults now. But for dwarf, the variable value is None if 36 # the inferior process does not exist yet. The radar has been updated. 37 #@unittest232.skip("segmentation fault -- skipping") 38 def test_find_global_variables(self): 39 """Exercise SBTarget.FindGlobalVariables() API.""" 40 d = {'EXE': 'b.out'} 41 self.build(dictionary=d) 42 self.setTearDownCleanup(dictionary=d) 43 self.find_global_variables('b.out') 44 45 def test_find_compile_units(self): 46 """Exercise SBTarget.FindCompileUnits() API.""" 47 d = {'EXE': 'b.out'} 48 self.build(dictionary=d) 49 self.setTearDownCleanup(dictionary=d) 50 self.find_compile_units(self.getBuildArtifact('b.out')) 51 52 @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") 53 def test_find_functions(self): 54 """Exercise SBTarget.FindFunctions() API.""" 55 d = {'EXE': 'b.out'} 56 self.build(dictionary=d) 57 self.setTearDownCleanup(dictionary=d) 58 self.find_functions('b.out') 59 60 def test_get_description(self): 61 """Exercise SBTarget.GetDescription() API.""" 62 self.build() 63 self.get_description() 64 65 @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765') 66 def test_resolve_symbol_context_with_address(self): 67 """Exercise SBTarget.ResolveSymbolContextForAddress() API.""" 68 self.build() 69 self.resolve_symbol_context_with_address() 70 71 def test_get_platform(self): 72 d = {'EXE': 'b.out'} 73 self.build(dictionary=d) 74 self.setTearDownCleanup(dictionary=d) 75 target = self.create_simple_target('b.out') 76 platform = target.platform 77 self.assertTrue(platform, VALID_PLATFORM) 78 79 def test_get_data_byte_size(self): 80 d = {'EXE': 'b.out'} 81 self.build(dictionary=d) 82 self.setTearDownCleanup(dictionary=d) 83 target = self.create_simple_target('b.out') 84 self.assertEqual(target.data_byte_size, 1) 85 86 def test_get_code_byte_size(self): 87 d = {'EXE': 'b.out'} 88 self.build(dictionary=d) 89 self.setTearDownCleanup(dictionary=d) 90 target = self.create_simple_target('b.out') 91 self.assertEqual(target.code_byte_size, 1) 92 93 def test_resolve_file_address(self): 94 d = {'EXE': 'b.out'} 95 self.build(dictionary=d) 96 self.setTearDownCleanup(dictionary=d) 97 target = self.create_simple_target('b.out') 98 99 # find the file address in the .data section of the main 100 # module 101 data_section = self.find_data_section(target) 102 data_section_addr = data_section.file_addr 103 104 # resolve the above address, and compare the address produced 105 # by the resolution against the original address/section 106 res_file_addr = target.ResolveFileAddress(data_section_addr) 107 self.assertTrue(res_file_addr.IsValid()) 108 109 self.assertEqual(data_section_addr, res_file_addr.file_addr) 110 111 data_section2 = res_file_addr.section 112 self.assertIsNotNone(data_section2) 113 self.assertEqual(data_section.name, data_section2.name) 114 115 def test_get_ABIName(self): 116 d = {'EXE': 'b.out'} 117 self.build(dictionary=d) 118 self.setTearDownCleanup(dictionary=d) 119 target = self.create_simple_target('b.out') 120 121 abi_pre_launch = target.GetABIName() 122 self.assertTrue(len(abi_pre_launch) != 0, "Got an ABI string") 123 124 breakpoint = target.BreakpointCreateByLocation( 125 "main.c", self.line_main) 126 self.assertTrue(breakpoint, VALID_BREAKPOINT) 127 128 # Put debugger into synchronous mode so when we target.LaunchSimple returns 129 # it will guaranteed to be at the breakpoint 130 self.dbg.SetAsync(False) 131 132 # Launch the process, and do not stop at the entry point. 133 process = target.LaunchSimple( 134 None, None, self.get_process_working_directory()) 135 abi_after_launch = target.GetABIName() 136 self.assertEqual(abi_pre_launch, abi_after_launch, "ABI's match before and during run") 137 138 def test_read_memory(self): 139 d = {'EXE': 'b.out'} 140 self.build(dictionary=d) 141 self.setTearDownCleanup(dictionary=d) 142 target = self.create_simple_target('b.out') 143 144 breakpoint = target.BreakpointCreateByLocation( 145 "main.c", self.line_main) 146 self.assertTrue(breakpoint, VALID_BREAKPOINT) 147 148 # Put debugger into synchronous mode so when we target.LaunchSimple returns 149 # it will guaranteed to be at the breakpoint 150 self.dbg.SetAsync(False) 151 152 # Launch the process, and do not stop at the entry point. 153 process = target.LaunchSimple( 154 None, None, self.get_process_working_directory()) 155 156 # find the file address in the .data section of the main 157 # module 158 data_section = self.find_data_section(target) 159 sb_addr = lldb.SBAddress(data_section, 0) 160 error = lldb.SBError() 161 content = target.ReadMemory(sb_addr, 1, error) 162 self.assertSuccess(error, "Make sure memory read succeeded") 163 self.assertEqual(len(content), 1) 164 165 166 @skipIfWindows # stdio manipulation unsupported on Windows 167 @skipIfRemote # stdio manipulation unsupported on remote iOS devices<rdar://problem/54581135> 168 @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) 169 @no_debug_info_test 170 def test_launch_simple(self): 171 d = {'EXE': 'b.out'} 172 self.build(dictionary=d) 173 self.setTearDownCleanup(dictionary=d) 174 target = self.create_simple_target('b.out') 175 176 # Set the debugger to synchronous mode so we only continue after the 177 # process has exited. 178 self.dbg.SetAsync(False) 179 180 process = target.LaunchSimple( 181 ['foo', 'bar'], ['baz'], self.get_process_working_directory()) 182 process.Continue() 183 self.assertEqual(process.GetState(), lldb.eStateExited) 184 output = process.GetSTDOUT(9999) 185 self.assertIn('arg: foo', output) 186 self.assertIn('arg: bar', output) 187 self.assertIn('env: baz', output) 188 189 self.runCmd("setting set target.run-args foo") 190 self.runCmd("setting set target.env-vars bar=baz") 191 process = target.LaunchSimple(None, None, 192 self.get_process_working_directory()) 193 process.Continue() 194 self.assertEqual(process.GetState(), lldb.eStateExited) 195 output = process.GetSTDOUT(9999) 196 self.assertIn('arg: foo', output) 197 self.assertIn('env: bar=baz', output) 198 199 self.runCmd("settings set target.disable-stdio true") 200 process = target.LaunchSimple( 201 None, None, self.get_process_working_directory()) 202 process.Continue() 203 self.assertEqual(process.GetState(), lldb.eStateExited) 204 output = process.GetSTDOUT(9999) 205 self.assertEqual(output, "") 206 207 def create_simple_target(self, fn): 208 exe = self.getBuildArtifact(fn) 209 target = self.dbg.CreateTarget(exe) 210 self.assertTrue(target, VALID_TARGET) 211 return target 212 213 def find_data_section(self, target): 214 mod = target.GetModuleAtIndex(0) 215 data_section = None 216 for s in mod.sections: 217 sect_type = s.GetSectionType() 218 if sect_type == lldb.eSectionTypeData: 219 data_section = s 220 break 221 elif sect_type == lldb.eSectionTypeContainer: 222 for i in range(s.GetNumSubSections()): 223 ss = s.GetSubSectionAtIndex(i) 224 sect_type = ss.GetSectionType() 225 if sect_type == lldb.eSectionTypeData: 226 data_section = ss 227 break 228 229 self.assertIsNotNone(data_section) 230 return data_section 231 232 def find_global_variables(self, exe_name): 233 """Exercise SBTarget.FindGlobalVariables() API.""" 234 exe = self.getBuildArtifact(exe_name) 235 236 # Create a target by the debugger. 237 target = self.dbg.CreateTarget(exe) 238 self.assertTrue(target, VALID_TARGET) 239 240 # rdar://problem/9700873 241 # Find global variable value fails for dwarf if inferior not started 242 # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) 243 # 244 # Remove the lines to create a breakpoint and to start the inferior 245 # which are workarounds for the dwarf case. 246 247 breakpoint = target.BreakpointCreateByLocation('main.c', self.line1) 248 self.assertTrue(breakpoint, VALID_BREAKPOINT) 249 250 # Now launch the process, and do not stop at entry point. 251 process = target.LaunchSimple( 252 None, None, self.get_process_working_directory()) 253 self.assertTrue(process, PROCESS_IS_VALID) 254 # Make sure we hit our breakpoint: 255 thread_list = lldbutil.get_threads_stopped_at_breakpoint( 256 process, breakpoint) 257 self.assertEqual(len(thread_list), 1) 258 259 value_list = target.FindGlobalVariables( 260 'my_global_var_of_char_type', 3) 261 self.assertEqual(value_list.GetSize(), 1) 262 my_global_var = value_list.GetValueAtIndex(0) 263 self.DebugSBValue(my_global_var) 264 self.assertTrue(my_global_var) 265 self.expect(my_global_var.GetName(), exe=False, 266 startstr="my_global_var_of_char_type") 267 self.expect(my_global_var.GetTypeName(), exe=False, 268 startstr="char") 269 self.expect(my_global_var.GetValue(), exe=False, 270 startstr="'X'") 271 272 # While we are at it, let's also exercise the similar 273 # SBModule.FindGlobalVariables() API. 274 for m in target.module_iter(): 275 if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name: 276 value_list = m.FindGlobalVariables( 277 target, 'my_global_var_of_char_type', 3) 278 self.assertEqual(value_list.GetSize(), 1) 279 self.assertEqual( 280 value_list.GetValueAtIndex(0).GetValue(), "'X'") 281 break 282 283 def find_compile_units(self, exe): 284 """Exercise SBTarget.FindCompileUnits() API.""" 285 source_name = "main.c" 286 287 # Create a target by the debugger. 288 target = self.dbg.CreateTarget(exe) 289 self.assertTrue(target, VALID_TARGET) 290 291 list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False)) 292 # Executable has been built just from one source file 'main.c', 293 # so we may check only the first element of list. 294 self.assertEqual( 295 list[0].GetCompileUnit().GetFileSpec().GetFilename(), source_name) 296 297 def find_functions(self, exe_name): 298 """Exercise SBTarget.FindFunctions() API.""" 299 exe = self.getBuildArtifact(exe_name) 300 301 # Create a target by the debugger. 302 target = self.dbg.CreateTarget(exe) 303 self.assertTrue(target, VALID_TARGET) 304 305 # Try it with a null name: 306 list = target.FindFunctions(None, lldb.eFunctionNameTypeAuto) 307 self.assertEqual(list.GetSize(), 0) 308 309 list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto) 310 self.assertEqual(list.GetSize(), 1) 311 312 for sc in list: 313 self.assertEqual( 314 sc.GetModule().GetFileSpec().GetFilename(), exe_name) 315 self.assertEqual(sc.GetSymbol().GetName(), 'c') 316 317 def get_description(self): 318 """Exercise SBTarget.GetDescription() API.""" 319 exe = self.getBuildArtifact("a.out") 320 321 # Create a target by the debugger. 322 target = self.dbg.CreateTarget(exe) 323 self.assertTrue(target, VALID_TARGET) 324 325 from lldbsuite.test.lldbutil import get_description 326 327 # get_description() allows no option to mean 328 # lldb.eDescriptionLevelBrief. 329 desc = get_description(target) 330 #desc = get_description(target, option=lldb.eDescriptionLevelBrief) 331 if not desc: 332 self.fail("SBTarget.GetDescription() failed") 333 self.expect(desc, exe=False, 334 substrs=['a.out']) 335 self.expect(desc, exe=False, matching=False, 336 substrs=['Target', 'Module', 'Breakpoint']) 337 338 desc = get_description(target, option=lldb.eDescriptionLevelFull) 339 if not desc: 340 self.fail("SBTarget.GetDescription() failed") 341 self.expect(desc, exe=False, 342 substrs=['Target', 'Module', 'a.out', 'Breakpoint']) 343 344 @skipIfRemote 345 @no_debug_info_test 346 def test_launch_new_process_and_redirect_stdout(self): 347 """Exercise SBTarget.Launch() API with redirected stdout.""" 348 self.build() 349 exe = self.getBuildArtifact("a.out") 350 351 # Create a target by the debugger. 352 target = self.dbg.CreateTarget(exe) 353 self.assertTrue(target, VALID_TARGET) 354 355 # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done. 356 # We should still see the entire stdout redirected once the process is 357 # finished. 358 line = line_number('main.c', '// a(3) -> c(3)') 359 breakpoint = target.BreakpointCreateByLocation('main.c', line) 360 361 # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file. 362 # The inferior should run to completion after "process.Continue()" 363 # call. 364 local_path = self.getBuildArtifact("stdout.txt") 365 if os.path.exists(local_path): 366 os.remove(local_path) 367 368 if lldb.remote_platform: 369 stdout_path = lldbutil.append_to_process_working_directory(self, 370 "lldb-stdout-redirect.txt") 371 else: 372 stdout_path = local_path 373 error = lldb.SBError() 374 process = target.Launch( 375 self.dbg.GetListener(), 376 None, 377 None, 378 None, 379 stdout_path, 380 None, 381 None, 382 0, 383 False, 384 error) 385 process.Continue() 386 #self.runCmd("process status") 387 if lldb.remote_platform: 388 # copy output file to host 389 lldb.remote_platform.Get( 390 lldb.SBFileSpec(stdout_path), 391 lldb.SBFileSpec(local_path)) 392 393 # The 'stdout.txt' file should now exist. 394 self.assertTrue( 395 os.path.isfile(local_path), 396 "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.") 397 398 # Read the output file produced by running the program. 399 with open(local_path, 'r') as f: 400 output = f.read() 401 402 self.expect(output, exe=False, 403 substrs=["a(1)", "b(2)", "a(3)"]) 404 405 def resolve_symbol_context_with_address(self): 406 """Exercise SBTarget.ResolveSymbolContextForAddress() API.""" 407 exe = self.getBuildArtifact("a.out") 408 409 # Create a target by the debugger. 410 target = self.dbg.CreateTarget(exe) 411 self.assertTrue(target, VALID_TARGET) 412 413 # Now create the two breakpoints inside function 'a'. 414 breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1) 415 breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2) 416 self.trace("breakpoint1:", breakpoint1) 417 self.trace("breakpoint2:", breakpoint2) 418 self.assertTrue(breakpoint1 and 419 breakpoint1.GetNumLocations() == 1, 420 VALID_BREAKPOINT) 421 self.assertTrue(breakpoint2 and 422 breakpoint2.GetNumLocations() == 1, 423 VALID_BREAKPOINT) 424 425 # Now launch the process, and do not stop at entry point. 426 process = target.LaunchSimple( 427 None, None, self.get_process_working_directory()) 428 self.assertTrue(process, PROCESS_IS_VALID) 429 430 # Frame #0 should be on self.line1. 431 self.assertState(process.GetState(), lldb.eStateStopped) 432 thread = lldbutil.get_stopped_thread( 433 process, lldb.eStopReasonBreakpoint) 434 self.assertTrue( 435 thread.IsValid(), 436 "There should be a thread stopped due to breakpoint condition") 437 #self.runCmd("process status") 438 frame0 = thread.GetFrameAtIndex(0) 439 lineEntry = frame0.GetLineEntry() 440 self.assertEqual(lineEntry.GetLine(), self.line1) 441 442 address1 = lineEntry.GetStartAddress() 443 444 # Continue the inferior, the breakpoint 2 should be hit. 445 process.Continue() 446 self.assertState(process.GetState(), lldb.eStateStopped) 447 thread = lldbutil.get_stopped_thread( 448 process, lldb.eStopReasonBreakpoint) 449 self.assertTrue( 450 thread.IsValid(), 451 "There should be a thread stopped due to breakpoint condition") 452 #self.runCmd("process status") 453 frame0 = thread.GetFrameAtIndex(0) 454 lineEntry = frame0.GetLineEntry() 455 self.assertEqual(lineEntry.GetLine(), self.line2) 456 457 address2 = lineEntry.GetStartAddress() 458 459 self.trace("address1:", address1) 460 self.trace("address2:", address2) 461 462 # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses 463 # from our line entry. 464 context1 = target.ResolveSymbolContextForAddress( 465 address1, lldb.eSymbolContextEverything) 466 context2 = target.ResolveSymbolContextForAddress( 467 address2, lldb.eSymbolContextEverything) 468 469 self.assertTrue(context1 and context2) 470 self.trace("context1:", context1) 471 self.trace("context2:", context2) 472 473 # Verify that the context point to the same function 'a'. 474 symbol1 = context1.GetSymbol() 475 symbol2 = context2.GetSymbol() 476 self.assertTrue(symbol1 and symbol2) 477 self.trace("symbol1:", symbol1) 478 self.trace("symbol2:", symbol2) 479 480 from lldbsuite.test.lldbutil import get_description 481 desc1 = get_description(symbol1) 482 desc2 = get_description(symbol2) 483 self.assertTrue(desc1 and desc2 and desc1 == desc2, 484 "The two addresses should resolve to the same symbol") 485 486 @skipIfRemote 487 def test_default_arch(self): 488 """ Test the other two target create methods using LLDB_ARCH_DEFAULT. """ 489 self.build() 490 exe = self.getBuildArtifact("a.out") 491 target = self.dbg.CreateTargetWithFileAndArch(exe, lldb.LLDB_ARCH_DEFAULT) 492 self.assertTrue(target.IsValid(), "Default arch made a valid target.") 493 # This should also work with the target's triple: 494 target2 = self.dbg.CreateTargetWithFileAndArch(exe, target.GetTriple()) 495 self.assertTrue(target2.IsValid(), "Round trip with triple works") 496 # And this triple should work for the FileAndTriple API: 497 target3 = self.dbg.CreateTargetWithFileAndTargetTriple(exe, target.GetTriple()) 498 self.assertTrue(target3.IsValid()) 499 500 501 @skipIfWindows 502 def test_is_loaded(self): 503 """Exercise SBTarget.IsLoaded(SBModule&) API.""" 504 d = {'EXE': 'b.out'} 505 self.build(dictionary=d) 506 self.setTearDownCleanup(dictionary=d) 507 target = self.create_simple_target('b.out') 508 509 self.assertFalse(target.IsLoaded(lldb.SBModule())) 510 511 num_modules = target.GetNumModules() 512 for i in range(num_modules): 513 module = target.GetModuleAtIndex(i) 514 self.assertFalse(target.IsLoaded(module), "Target that isn't " 515 "running shouldn't have any module loaded.") 516 517 process = target.LaunchSimple(None, None, 518 self.get_process_working_directory()) 519 520 for i in range(num_modules): 521 module = target.GetModuleAtIndex(i) 522 self.assertTrue(target.IsLoaded(module), "Running the target should " 523 "have loaded its modules.") 524