1""" 2Test SBTarget APIs. 3""" 4 5import os 6import lldb 7from lldbsuite.test.decorators import * 8from lldbsuite.test.lldbtest import * 9from lldbsuite.test import lldbutil 10 11 12class TargetAPITestCase(TestBase): 13 14 def setUp(self): 15 # Call super's setUp(). 16 TestBase.setUp(self) 17 # Find the line number to of function 'c'. 18 self.line1 = line_number( 19 'main.c', '// Find the line number for breakpoint 1 here.') 20 self.line2 = line_number( 21 'main.c', '// Find the line number for breakpoint 2 here.') 22 self.line_main = line_number( 23 "main.c", "// Set a break at entry to main.") 24 25 # rdar://problem/9700873 26 # Find global variable value fails for dwarf if inferior not started 27 # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) 28 # 29 # It does not segfaults now. But for dwarf, the variable value is None if 30 # the inferior process does not exist yet. The radar has been updated. 31 def test_find_global_variables(self): 32 """Exercise SBTarget.FindGlobalVariables() API.""" 33 d = {'EXE': 'b.out'} 34 self.build(dictionary=d) 35 self.setTearDownCleanup(dictionary=d) 36 self.find_global_variables('b.out') 37 38 def test_find_compile_units(self): 39 """Exercise SBTarget.FindCompileUnits() API.""" 40 d = {'EXE': 'b.out'} 41 self.build(dictionary=d) 42 self.setTearDownCleanup(dictionary=d) 43 self.find_compile_units(self.getBuildArtifact('b.out')) 44 45 def test_find_functions(self): 46 """Exercise SBTarget.FindFunctions() API.""" 47 d = {'EXE': 'b.out'} 48 self.build(dictionary=d) 49 self.setTearDownCleanup(dictionary=d) 50 self.find_functions('b.out') 51 52 def test_get_description(self): 53 """Exercise SBTarget.GetDescription() API.""" 54 self.build() 55 self.get_description() 56 57 def test_resolve_symbol_context_with_address(self): 58 """Exercise SBTarget.ResolveSymbolContextForAddress() API.""" 59 self.build() 60 self.resolve_symbol_context_with_address() 61 62 def test_get_platform(self): 63 d = {'EXE': 'b.out'} 64 self.build(dictionary=d) 65 self.setTearDownCleanup(dictionary=d) 66 target = self.create_simple_target('b.out') 67 platform = target.platform 68 self.assertTrue(platform, VALID_PLATFORM) 69 70 def test_get_data_byte_size(self): 71 d = {'EXE': 'b.out'} 72 self.build(dictionary=d) 73 self.setTearDownCleanup(dictionary=d) 74 target = self.create_simple_target('b.out') 75 self.assertEqual(target.data_byte_size, 1) 76 77 def test_get_code_byte_size(self): 78 d = {'EXE': 'b.out'} 79 self.build(dictionary=d) 80 self.setTearDownCleanup(dictionary=d) 81 target = self.create_simple_target('b.out') 82 self.assertEqual(target.code_byte_size, 1) 83 84 def test_resolve_file_address(self): 85 d = {'EXE': 'b.out'} 86 self.build(dictionary=d) 87 self.setTearDownCleanup(dictionary=d) 88 target = self.create_simple_target('b.out') 89 90 # find the file address in the .data section of the main 91 # module 92 data_section = self.find_data_section(target) 93 data_section_addr = data_section.file_addr 94 95 # resolve the above address, and compare the address produced 96 # by the resolution against the original address/section 97 res_file_addr = target.ResolveFileAddress(data_section_addr) 98 self.assertTrue(res_file_addr.IsValid()) 99 100 self.assertEqual(data_section_addr, res_file_addr.file_addr) 101 102 data_section2 = res_file_addr.section 103 self.assertIsNotNone(data_section2) 104 self.assertEqual(data_section.name, data_section2.name) 105 106 def test_get_ABIName(self): 107 d = {'EXE': 'b.out'} 108 self.build(dictionary=d) 109 self.setTearDownCleanup(dictionary=d) 110 target = self.create_simple_target('b.out') 111 112 abi_pre_launch = target.GetABIName() 113 self.assertTrue(len(abi_pre_launch) != 0, "Got an ABI string") 114 115 breakpoint = target.BreakpointCreateByLocation( 116 "main.c", self.line_main) 117 self.assertTrue(breakpoint, VALID_BREAKPOINT) 118 119 # Put debugger into synchronous mode so when we target.LaunchSimple returns 120 # it will guaranteed to be at the breakpoint 121 self.dbg.SetAsync(False) 122 123 # Launch the process, and do not stop at the entry point. 124 process = target.LaunchSimple( 125 None, None, self.get_process_working_directory()) 126 abi_after_launch = target.GetABIName() 127 self.assertEqual(abi_pre_launch, abi_after_launch, 128 "ABI's match before and during run") 129 130 def test_read_memory(self): 131 d = {'EXE': 'b.out'} 132 self.build(dictionary=d) 133 self.setTearDownCleanup(dictionary=d) 134 target = self.create_simple_target('b.out') 135 136 breakpoint = target.BreakpointCreateByLocation( 137 "main.c", self.line_main) 138 self.assertTrue(breakpoint, VALID_BREAKPOINT) 139 140 # Put debugger into synchronous mode so when we target.LaunchSimple returns 141 # it will guaranteed to be at the breakpoint 142 self.dbg.SetAsync(False) 143 144 # Launch the process, and do not stop at the entry point. 145 process = target.LaunchSimple( 146 None, None, self.get_process_working_directory()) 147 148 # find the file address in the .data section of the main 149 # module 150 data_section = self.find_data_section(target) 151 sb_addr = lldb.SBAddress(data_section, 0) 152 error = lldb.SBError() 153 content = target.ReadMemory(sb_addr, 1, error) 154 self.assertSuccess(error, "Make sure memory read succeeded") 155 self.assertEqual(len(content), 1) 156 157 @skipIfWindows # stdio manipulation unsupported on Windows 158 @skipIfRemote # stdio manipulation unsupported on remote iOS devices<rdar://problem/54581135> 159 @skipIf(oslist=["linux"], archs=["arm", "aarch64"]) 160 @no_debug_info_test 161 def test_launch_simple(self): 162 d = {'EXE': 'b.out'} 163 self.build(dictionary=d) 164 self.setTearDownCleanup(dictionary=d) 165 target = self.create_simple_target('b.out') 166 167 # Set the debugger to synchronous mode so we only continue after the 168 # process has exited. 169 self.dbg.SetAsync(False) 170 171 process = target.LaunchSimple( 172 ['foo', 'bar'], ['baz'], self.get_process_working_directory()) 173 process.Continue() 174 self.assertState(process.GetState(), lldb.eStateExited) 175 output = process.GetSTDOUT(9999) 176 self.assertIn('arg: foo', output) 177 self.assertIn('arg: bar', output) 178 self.assertIn('env: baz', output) 179 180 self.runCmd("setting set target.run-args foo") 181 self.runCmd("setting set target.env-vars bar=baz") 182 process = target.LaunchSimple(None, None, 183 self.get_process_working_directory()) 184 process.Continue() 185 self.assertState(process.GetState(), lldb.eStateExited) 186 output = process.GetSTDOUT(9999) 187 self.assertIn('arg: foo', output) 188 self.assertIn('env: bar=baz', output) 189 190 # Clear all the run args set above. 191 self.runCmd("setting clear target.run-args") 192 process = target.LaunchSimple(None, None, 193 self.get_process_working_directory()) 194 process.Continue() 195 self.assertEqual(process.GetState(), lldb.eStateExited) 196 output = process.GetSTDOUT(9999) 197 self.assertNotIn('arg: foo', 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.assertState(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( 492 exe, lldb.LLDB_ARCH_DEFAULT) 493 self.assertTrue(target.IsValid(), "Default arch made a valid target.") 494 # This should also work with the target's triple: 495 target2 = self.dbg.CreateTargetWithFileAndArch(exe, target.GetTriple()) 496 self.assertTrue(target2.IsValid(), "Round trip with triple works") 497 # And this triple should work for the FileAndTriple API: 498 target3 = self.dbg.CreateTargetWithFileAndTargetTriple( 499 exe, target.GetTriple()) 500 self.assertTrue(target3.IsValid()) 501 502 @skipIfWindows 503 def test_is_loaded(self): 504 """Exercise SBTarget.IsLoaded(SBModule&) API.""" 505 d = {'EXE': 'b.out'} 506 self.build(dictionary=d) 507 self.setTearDownCleanup(dictionary=d) 508 target = self.create_simple_target('b.out') 509 510 self.assertFalse(target.IsLoaded(lldb.SBModule())) 511 512 num_modules = target.GetNumModules() 513 for i in range(num_modules): 514 module = target.GetModuleAtIndex(i) 515 self.assertFalse(target.IsLoaded(module), "Target that isn't " 516 "running shouldn't have any module loaded.") 517 518 process = target.LaunchSimple(None, None, 519 self.get_process_working_directory()) 520 521 for i in range(num_modules): 522 module = target.GetModuleAtIndex(i) 523 self.assertTrue(target.IsLoaded(module), "Running the target should " 524 "have loaded its modules.") 525