1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 #include <errno.h> 12 #include <spawn.h> 13 #include <stdlib.h> 14 #include <sys/mman.h> // for mmap 15 #include <sys/stat.h> 16 #include <sys/types.h> 17 #include <time.h> 18 19 // C++ Includes 20 #include <algorithm> 21 #include <map> 22 23 // Other libraries and framework includes 24 25 #include "lldb/Breakpoint/Watchpoint.h" 26 #include "lldb/Interpreter/Args.h" 27 #include "lldb/Core/ArchSpec.h" 28 #include "lldb/Core/Debugger.h" 29 #include "lldb/Core/ConnectionFileDescriptor.h" 30 #include "lldb/Host/FileSpec.h" 31 #include "lldb/Core/InputReader.h" 32 #include "lldb/Core/Module.h" 33 #include "lldb/Core/PluginManager.h" 34 #include "lldb/Core/State.h" 35 #include "lldb/Core/StreamString.h" 36 #include "lldb/Core/Timer.h" 37 #include "lldb/Core/Value.h" 38 #include "lldb/Host/TimeValue.h" 39 #include "lldb/Symbol/ObjectFile.h" 40 #include "lldb/Target/DynamicLoader.h" 41 #include "lldb/Target/Target.h" 42 #include "lldb/Target/TargetList.h" 43 #include "lldb/Target/ThreadPlanCallFunction.h" 44 #include "lldb/Utility/PseudoTerminal.h" 45 46 // Project includes 47 #include "lldb/Host/Host.h" 48 #include "Plugins/Process/Utility/InferiorCallPOSIX.h" 49 #include "Utility/StringExtractorGDBRemote.h" 50 #include "GDBRemoteRegisterContext.h" 51 #include "ProcessGDBRemote.h" 52 #include "ProcessGDBRemoteLog.h" 53 #include "ThreadGDBRemote.h" 54 #include "StopInfoMachException.h" 55 56 57 58 #define DEBUGSERVER_BASENAME "debugserver" 59 using namespace lldb; 60 using namespace lldb_private; 61 62 static bool rand_initialized = false; 63 64 static inline uint16_t 65 get_random_port () 66 { 67 if (!rand_initialized) 68 { 69 time_t seed = time(NULL); 70 71 rand_initialized = true; 72 srand(seed); 73 } 74 return (rand() % (UINT16_MAX - 1000u)) + 1000u; 75 } 76 77 78 const char * 79 ProcessGDBRemote::GetPluginNameStatic() 80 { 81 return "gdb-remote"; 82 } 83 84 const char * 85 ProcessGDBRemote::GetPluginDescriptionStatic() 86 { 87 return "GDB Remote protocol based debugging plug-in."; 88 } 89 90 void 91 ProcessGDBRemote::Terminate() 92 { 93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 94 } 95 96 97 Process* 98 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener) 99 { 100 return new ProcessGDBRemote (target, listener); 101 } 102 103 bool 104 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name) 105 { 106 if (plugin_specified_by_name) 107 return true; 108 109 // For now we are just making sure the file exists for a given module 110 Module *exe_module = target.GetExecutableModulePointer(); 111 if (exe_module) 112 return exe_module->GetFileSpec().Exists(); 113 // However, if there is no executable module, we return true since we might be preparing to attach. 114 return true; 115 } 116 117 //---------------------------------------------------------------------- 118 // ProcessGDBRemote constructor 119 //---------------------------------------------------------------------- 120 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) : 121 Process (target, listener), 122 m_flags (0), 123 m_stdio_mutex (Mutex::eMutexTypeRecursive), 124 m_gdb_comm(false), 125 m_debugserver_pid (LLDB_INVALID_PROCESS_ID), 126 m_debugserver_thread (LLDB_INVALID_HOST_THREAD), 127 m_last_stop_packet (), 128 m_register_info (), 129 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"), 130 m_async_thread (LLDB_INVALID_HOST_THREAD), 131 m_continue_c_tids (), 132 m_continue_C_tids (), 133 m_continue_s_tids (), 134 m_continue_S_tids (), 135 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS), 136 m_max_memory_size (512), 137 m_waiting_for_attach (false), 138 m_thread_observation_bps() 139 { 140 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); 141 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue"); 142 } 143 144 //---------------------------------------------------------------------- 145 // Destructor 146 //---------------------------------------------------------------------- 147 ProcessGDBRemote::~ProcessGDBRemote() 148 { 149 if (IS_VALID_LLDB_HOST_THREAD(m_debugserver_thread)) 150 { 151 Host::ThreadCancel (m_debugserver_thread, NULL); 152 thread_result_t thread_result; 153 Host::ThreadJoin (m_debugserver_thread, &thread_result, NULL); 154 m_debugserver_thread = LLDB_INVALID_HOST_THREAD; 155 } 156 // m_mach_process.UnregisterNotificationCallbacks (this); 157 Clear(); 158 // We need to call finalize on the process before destroying ourselves 159 // to make sure all of the broadcaster cleanup goes as planned. If we 160 // destruct this class, then Process::~Process() might have problems 161 // trying to fully destroy the broadcaster. 162 Finalize(); 163 } 164 165 //---------------------------------------------------------------------- 166 // PluginInterface 167 //---------------------------------------------------------------------- 168 const char * 169 ProcessGDBRemote::GetPluginName() 170 { 171 return "Process debugging plug-in that uses the GDB remote protocol"; 172 } 173 174 const char * 175 ProcessGDBRemote::GetShortPluginName() 176 { 177 return GetPluginNameStatic(); 178 } 179 180 uint32_t 181 ProcessGDBRemote::GetPluginVersion() 182 { 183 return 1; 184 } 185 186 void 187 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force) 188 { 189 if (!force && m_register_info.GetNumRegisters() > 0) 190 return; 191 192 char packet[128]; 193 m_register_info.Clear(); 194 uint32_t reg_offset = 0; 195 uint32_t reg_num = 0; 196 StringExtractorGDBRemote::ResponseType response_type; 197 for (response_type = StringExtractorGDBRemote::eResponse; 198 response_type == StringExtractorGDBRemote::eResponse; 199 ++reg_num) 200 { 201 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num); 202 assert (packet_len < sizeof(packet)); 203 StringExtractorGDBRemote response; 204 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false)) 205 { 206 response_type = response.GetResponseType(); 207 if (response_type == StringExtractorGDBRemote::eResponse) 208 { 209 std::string name; 210 std::string value; 211 ConstString reg_name; 212 ConstString alt_name; 213 ConstString set_name; 214 RegisterInfo reg_info = { NULL, // Name 215 NULL, // Alt name 216 0, // byte size 217 reg_offset, // offset 218 eEncodingUint, // encoding 219 eFormatHex, // formate 220 { 221 LLDB_INVALID_REGNUM, // GCC reg num 222 LLDB_INVALID_REGNUM, // DWARF reg num 223 LLDB_INVALID_REGNUM, // generic reg num 224 reg_num, // GDB reg num 225 reg_num // native register number 226 } 227 }; 228 229 while (response.GetNameColonValue(name, value)) 230 { 231 if (name.compare("name") == 0) 232 { 233 reg_name.SetCString(value.c_str()); 234 } 235 else if (name.compare("alt-name") == 0) 236 { 237 alt_name.SetCString(value.c_str()); 238 } 239 else if (name.compare("bitsize") == 0) 240 { 241 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT; 242 } 243 else if (name.compare("offset") == 0) 244 { 245 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0); 246 if (reg_offset != offset) 247 { 248 reg_offset = offset; 249 } 250 } 251 else if (name.compare("encoding") == 0) 252 { 253 if (value.compare("uint") == 0) 254 reg_info.encoding = eEncodingUint; 255 else if (value.compare("sint") == 0) 256 reg_info.encoding = eEncodingSint; 257 else if (value.compare("ieee754") == 0) 258 reg_info.encoding = eEncodingIEEE754; 259 else if (value.compare("vector") == 0) 260 reg_info.encoding = eEncodingVector; 261 } 262 else if (name.compare("format") == 0) 263 { 264 if (value.compare("binary") == 0) 265 reg_info.format = eFormatBinary; 266 else if (value.compare("decimal") == 0) 267 reg_info.format = eFormatDecimal; 268 else if (value.compare("hex") == 0) 269 reg_info.format = eFormatHex; 270 else if (value.compare("float") == 0) 271 reg_info.format = eFormatFloat; 272 else if (value.compare("vector-sint8") == 0) 273 reg_info.format = eFormatVectorOfSInt8; 274 else if (value.compare("vector-uint8") == 0) 275 reg_info.format = eFormatVectorOfUInt8; 276 else if (value.compare("vector-sint16") == 0) 277 reg_info.format = eFormatVectorOfSInt16; 278 else if (value.compare("vector-uint16") == 0) 279 reg_info.format = eFormatVectorOfUInt16; 280 else if (value.compare("vector-sint32") == 0) 281 reg_info.format = eFormatVectorOfSInt32; 282 else if (value.compare("vector-uint32") == 0) 283 reg_info.format = eFormatVectorOfUInt32; 284 else if (value.compare("vector-float32") == 0) 285 reg_info.format = eFormatVectorOfFloat32; 286 else if (value.compare("vector-uint128") == 0) 287 reg_info.format = eFormatVectorOfUInt128; 288 } 289 else if (name.compare("set") == 0) 290 { 291 set_name.SetCString(value.c_str()); 292 } 293 else if (name.compare("gcc") == 0) 294 { 295 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 296 } 297 else if (name.compare("dwarf") == 0) 298 { 299 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 300 } 301 else if (name.compare("generic") == 0) 302 { 303 if (value.compare("pc") == 0) 304 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; 305 else if (value.compare("sp") == 0) 306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP; 307 else if (value.compare("fp") == 0) 308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP; 309 else if (value.compare("ra") == 0) 310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA; 311 else if (value.compare("flags") == 0) 312 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS; 313 else if (value.find("arg") == 0) 314 { 315 if (value.size() == 4) 316 { 317 switch (value[3]) 318 { 319 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break; 320 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break; 321 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break; 322 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break; 323 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break; 324 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break; 325 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break; 326 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break; 327 } 328 } 329 } 330 } 331 } 332 333 reg_info.byte_offset = reg_offset; 334 assert (reg_info.byte_size != 0); 335 reg_offset += reg_info.byte_size; 336 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 337 } 338 } 339 else 340 { 341 response_type = StringExtractorGDBRemote::eError; 342 break; 343 } 344 } 345 346 if (reg_num == 0) 347 { 348 // We didn't get anything. See if we are debugging ARM and fill with 349 // a hard coded register set until we can get an updated debugserver 350 // down on the devices. 351 352 if (!GetTarget().GetArchitecture().IsValid() 353 && m_gdb_comm.GetHostArchitecture().IsValid() 354 && m_gdb_comm.GetHostArchitecture().GetMachine() == llvm::Triple::arm 355 && m_gdb_comm.GetHostArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) 356 { 357 m_register_info.HardcodeARMRegisters(); 358 } 359 else if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::arm) 360 { 361 m_register_info.HardcodeARMRegisters(); 362 } 363 } 364 m_register_info.Finalize (); 365 } 366 367 Error 368 ProcessGDBRemote::WillLaunch (Module* module) 369 { 370 return WillLaunchOrAttach (); 371 } 372 373 Error 374 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 375 { 376 return WillLaunchOrAttach (); 377 } 378 379 Error 380 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 381 { 382 return WillLaunchOrAttach (); 383 } 384 385 Error 386 ProcessGDBRemote::DoConnectRemote (const char *remote_url) 387 { 388 Error error (WillLaunchOrAttach ()); 389 390 if (error.Fail()) 391 return error; 392 393 error = ConnectToDebugserver (remote_url); 394 395 if (error.Fail()) 396 return error; 397 StartAsyncThread (); 398 399 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 400 if (pid == LLDB_INVALID_PROCESS_ID) 401 { 402 // We don't have a valid process ID, so note that we are connected 403 // and could now request to launch or attach, or get remote process 404 // listings... 405 SetPrivateState (eStateConnected); 406 } 407 else 408 { 409 // We have a valid process 410 SetID (pid); 411 GetThreadList(); 412 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false)) 413 { 414 const StateType state = SetThreadStopInfo (m_last_stop_packet); 415 if (state == eStateStopped) 416 { 417 SetPrivateState (state); 418 } 419 else 420 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state)); 421 } 422 else 423 error.SetErrorStringWithFormat ("Process %i was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url); 424 } 425 return error; 426 } 427 428 Error 429 ProcessGDBRemote::WillLaunchOrAttach () 430 { 431 Error error; 432 m_stdio_communication.Clear (); 433 return error; 434 } 435 436 //---------------------------------------------------------------------- 437 // Process Control 438 //---------------------------------------------------------------------- 439 Error 440 ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info) 441 { 442 Error error; 443 444 uint32_t launch_flags = launch_info.GetFlags().Get(); 445 const char *stdin_path = NULL; 446 const char *stdout_path = NULL; 447 const char *stderr_path = NULL; 448 const char *working_dir = launch_info.GetWorkingDirectory(); 449 450 const ProcessLaunchInfo::FileAction *file_action; 451 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 452 if (file_action) 453 { 454 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 455 stdin_path = file_action->GetPath(); 456 } 457 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 458 if (file_action) 459 { 460 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 461 stdout_path = file_action->GetPath(); 462 } 463 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 464 if (file_action) 465 { 466 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 467 stderr_path = file_action->GetPath(); 468 } 469 470 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 471 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 472 // ::LogSetLogFile ("/dev/stdout"); 473 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 474 475 ObjectFile * object_file = exe_module->GetObjectFile(); 476 if (object_file) 477 { 478 char host_port[128]; 479 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 480 char connect_url[128]; 481 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 482 483 // Make sure we aren't already connected? 484 if (!m_gdb_comm.IsConnected()) 485 { 486 error = StartDebugserverProcess (host_port); 487 if (error.Fail()) 488 { 489 if (log) 490 log->Printf("failed to start debugserver process: %s", error.AsCString()); 491 return error; 492 } 493 494 error = ConnectToDebugserver (connect_url); 495 } 496 497 if (error.Success()) 498 { 499 lldb_utility::PseudoTerminal pty; 500 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 501 502 // If the debugserver is local and we aren't disabling STDIO, lets use 503 // a pseudo terminal to instead of relying on the 'O' packets for stdio 504 // since 'O' packets can really slow down debugging if the inferior 505 // does a lot of output. 506 PlatformSP platform_sp (m_target.GetPlatform()); 507 if (platform_sp && platform_sp->IsHost() && !disable_stdio) 508 { 509 const char *slave_name = NULL; 510 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) 511 { 512 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 513 slave_name = pty.GetSlaveName (NULL, 0); 514 } 515 if (stdin_path == NULL) 516 stdin_path = slave_name; 517 518 if (stdout_path == NULL) 519 stdout_path = slave_name; 520 521 if (stderr_path == NULL) 522 stderr_path = slave_name; 523 } 524 525 // Set STDIN to /dev/null if we want STDIO disabled or if either 526 // STDOUT or STDERR have been set to something and STDIN hasn't 527 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path))) 528 stdin_path = "/dev/null"; 529 530 // Set STDOUT to /dev/null if we want STDIO disabled or if either 531 // STDIN or STDERR have been set to something and STDOUT hasn't 532 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path))) 533 stdout_path = "/dev/null"; 534 535 // Set STDERR to /dev/null if we want STDIO disabled or if either 536 // STDIN or STDOUT have been set to something and STDERR hasn't 537 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path))) 538 stderr_path = "/dev/null"; 539 540 if (stdin_path) 541 m_gdb_comm.SetSTDIN (stdin_path); 542 if (stdout_path) 543 m_gdb_comm.SetSTDOUT (stdout_path); 544 if (stderr_path) 545 m_gdb_comm.SetSTDERR (stderr_path); 546 547 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR); 548 549 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName()); 550 551 if (working_dir && working_dir[0]) 552 { 553 m_gdb_comm.SetWorkingDir (working_dir); 554 } 555 556 // Send the environment and the program + arguments after we connect 557 const Args &environment = launch_info.GetEnvironmentEntries(); 558 if (environment.GetArgumentCount()) 559 { 560 size_t num_environment_entries = environment.GetArgumentCount(); 561 for (size_t i=0; i<num_environment_entries; ++i) 562 { 563 const char *env_entry = environment.GetArgumentAtIndex(i); 564 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0) 565 break; 566 } 567 } 568 569 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10); 570 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector()); 571 if (arg_packet_err == 0) 572 { 573 std::string error_str; 574 if (m_gdb_comm.GetLaunchSuccess (error_str)) 575 { 576 SetID (m_gdb_comm.GetCurrentProcessID ()); 577 } 578 else 579 { 580 error.SetErrorString (error_str.c_str()); 581 } 582 } 583 else 584 { 585 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err); 586 } 587 588 m_gdb_comm.SetPacketTimeout (old_packet_timeout); 589 590 if (GetID() == LLDB_INVALID_PROCESS_ID) 591 { 592 if (log) 593 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 594 KillDebugserverProcess (); 595 return error; 596 } 597 598 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false)) 599 { 600 SetPrivateState (SetThreadStopInfo (m_last_stop_packet)); 601 602 if (!disable_stdio) 603 { 604 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) 605 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor()); 606 } 607 } 608 } 609 else 610 { 611 if (log) 612 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 613 } 614 } 615 else 616 { 617 // Set our user ID to an invalid process ID. 618 SetID(LLDB_INVALID_PROCESS_ID); 619 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s", 620 exe_module->GetFileSpec().GetFilename().AsCString(), 621 exe_module->GetArchitecture().GetArchitectureName()); 622 } 623 return error; 624 625 } 626 627 628 Error 629 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url) 630 { 631 Error error; 632 // Sleep and wait a bit for debugserver to start to listen... 633 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor()); 634 if (conn_ap.get()) 635 { 636 const uint32_t max_retry_count = 50; 637 uint32_t retry_count = 0; 638 while (!m_gdb_comm.IsConnected()) 639 { 640 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) 641 { 642 m_gdb_comm.SetConnection (conn_ap.release()); 643 break; 644 } 645 retry_count++; 646 647 if (retry_count >= max_retry_count) 648 break; 649 650 usleep (100000); 651 } 652 } 653 654 if (!m_gdb_comm.IsConnected()) 655 { 656 if (error.Success()) 657 error.SetErrorString("not connected to remote gdb server"); 658 return error; 659 } 660 661 // We always seem to be able to open a connection to a local port 662 // so we need to make sure we can then send data to it. If we can't 663 // then we aren't actually connected to anything, so try and do the 664 // handshake with the remote GDB server and make sure that goes 665 // alright. 666 if (!m_gdb_comm.HandshakeWithServer (NULL)) 667 { 668 m_gdb_comm.Disconnect(); 669 if (error.Success()) 670 error.SetErrorString("not connected to remote gdb server"); 671 return error; 672 } 673 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 674 m_debugserver_thread = Host::StartMonitoringChildProcess (MonitorDebugserverProcess, 675 this, 676 m_debugserver_pid, 677 false); 678 m_gdb_comm.ResetDiscoverableSettings(); 679 m_gdb_comm.QueryNoAckModeSupported (); 680 m_gdb_comm.GetThreadSuffixSupported (); 681 m_gdb_comm.GetHostInfo (); 682 m_gdb_comm.GetVContSupported ('c'); 683 return error; 684 } 685 686 void 687 ProcessGDBRemote::DidLaunchOrAttach () 688 { 689 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 690 if (log) 691 log->Printf ("ProcessGDBRemote::DidLaunch()"); 692 if (GetID() != LLDB_INVALID_PROCESS_ID) 693 { 694 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; 695 696 BuildDynamicRegisterInfo (false); 697 698 // See if the GDB server supports the qHostInfo information 699 700 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture(); 701 if (gdb_remote_arch.IsValid()) 702 { 703 ArchSpec &target_arch = GetTarget().GetArchitecture(); 704 705 if (target_arch.IsValid()) 706 { 707 // If the remote host is ARM and we have apple as the vendor, then 708 // ARM executables and shared libraries can have mixed ARM architectures. 709 // You can have an armv6 executable, and if the host is armv7, then the 710 // system will load the best possible architecture for all shared libraries 711 // it has, so we really need to take the remote host architecture as our 712 // defacto architecture in this case. 713 714 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm && 715 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 716 { 717 target_arch = gdb_remote_arch; 718 } 719 else 720 { 721 // Fill in what is missing in the triple 722 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple(); 723 llvm::Triple &target_triple = target_arch.GetTriple(); 724 if (target_triple.getVendorName().size() == 0) 725 { 726 target_triple.setVendor (remote_triple.getVendor()); 727 728 if (target_triple.getOSName().size() == 0) 729 { 730 target_triple.setOS (remote_triple.getOS()); 731 732 if (target_triple.getEnvironmentName().size() == 0) 733 target_triple.setEnvironment (remote_triple.getEnvironment()); 734 } 735 } 736 } 737 } 738 else 739 { 740 // The target doesn't have a valid architecture yet, set it from 741 // the architecture we got from the remote GDB server 742 target_arch = gdb_remote_arch; 743 } 744 } 745 } 746 } 747 748 void 749 ProcessGDBRemote::DidLaunch () 750 { 751 DidLaunchOrAttach (); 752 } 753 754 Error 755 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid) 756 { 757 Error error; 758 // Clear out and clean up from any current state 759 Clear(); 760 if (attach_pid != LLDB_INVALID_PROCESS_ID) 761 { 762 // Make sure we aren't already connected? 763 if (!m_gdb_comm.IsConnected()) 764 { 765 char host_port[128]; 766 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 767 char connect_url[128]; 768 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 769 770 error = StartDebugserverProcess (host_port); 771 772 if (error.Fail()) 773 { 774 const char *error_string = error.AsCString(); 775 if (error_string == NULL) 776 error_string = "unable to launch " DEBUGSERVER_BASENAME; 777 778 SetExitStatus (-1, error_string); 779 } 780 else 781 { 782 error = ConnectToDebugserver (connect_url); 783 } 784 } 785 786 if (error.Success()) 787 { 788 char packet[64]; 789 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid); 790 791 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len)); 792 } 793 } 794 return error; 795 } 796 797 size_t 798 ProcessGDBRemote::AttachInputReaderCallback 799 ( 800 void *baton, 801 InputReader *reader, 802 lldb::InputReaderAction notification, 803 const char *bytes, 804 size_t bytes_len 805 ) 806 { 807 if (notification == eInputReaderGotToken) 808 { 809 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton; 810 if (gdb_process->m_waiting_for_attach) 811 gdb_process->m_waiting_for_attach = false; 812 reader->SetIsDone(true); 813 return 1; 814 } 815 return 0; 816 } 817 818 Error 819 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch) 820 { 821 Error error; 822 // Clear out and clean up from any current state 823 Clear(); 824 825 if (process_name && process_name[0]) 826 { 827 // Make sure we aren't already connected? 828 if (!m_gdb_comm.IsConnected()) 829 { 830 char host_port[128]; 831 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 832 char connect_url[128]; 833 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 834 835 error = StartDebugserverProcess (host_port); 836 if (error.Fail()) 837 { 838 const char *error_string = error.AsCString(); 839 if (error_string == NULL) 840 error_string = "unable to launch " DEBUGSERVER_BASENAME; 841 842 SetExitStatus (-1, error_string); 843 } 844 else 845 { 846 error = ConnectToDebugserver (connect_url); 847 } 848 } 849 850 if (error.Success()) 851 { 852 StreamString packet; 853 854 if (wait_for_launch) 855 packet.PutCString("vAttachWait"); 856 else 857 packet.PutCString("vAttachName"); 858 packet.PutChar(';'); 859 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 860 861 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize())); 862 863 } 864 } 865 return error; 866 } 867 868 869 void 870 ProcessGDBRemote::DidAttach () 871 { 872 DidLaunchOrAttach (); 873 } 874 875 Error 876 ProcessGDBRemote::WillResume () 877 { 878 m_continue_c_tids.clear(); 879 m_continue_C_tids.clear(); 880 m_continue_s_tids.clear(); 881 m_continue_S_tids.clear(); 882 return Error(); 883 } 884 885 Error 886 ProcessGDBRemote::DoResume () 887 { 888 Error error; 889 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 890 if (log) 891 log->Printf ("ProcessGDBRemote::Resume()"); 892 893 Listener listener ("gdb-remote.resume-packet-sent"); 894 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 895 { 896 StreamString continue_packet; 897 bool continue_packet_error = false; 898 if (m_gdb_comm.HasAnyVContSupport ()) 899 { 900 continue_packet.PutCString ("vCont"); 901 902 if (!m_continue_c_tids.empty()) 903 { 904 if (m_gdb_comm.GetVContSupported ('c')) 905 { 906 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos) 907 continue_packet.Printf(";c:%4.4x", *t_pos); 908 } 909 else 910 continue_packet_error = true; 911 } 912 913 if (!continue_packet_error && !m_continue_C_tids.empty()) 914 { 915 if (m_gdb_comm.GetVContSupported ('C')) 916 { 917 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos) 918 continue_packet.Printf(";C%2.2x:%4.4x", s_pos->second, s_pos->first); 919 } 920 else 921 continue_packet_error = true; 922 } 923 924 if (!continue_packet_error && !m_continue_s_tids.empty()) 925 { 926 if (m_gdb_comm.GetVContSupported ('s')) 927 { 928 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos) 929 continue_packet.Printf(";s:%4.4x", *t_pos); 930 } 931 else 932 continue_packet_error = true; 933 } 934 935 if (!continue_packet_error && !m_continue_S_tids.empty()) 936 { 937 if (m_gdb_comm.GetVContSupported ('S')) 938 { 939 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos) 940 continue_packet.Printf(";S%2.2x:%4.4x", s_pos->second, s_pos->first); 941 } 942 else 943 continue_packet_error = true; 944 } 945 946 if (continue_packet_error) 947 continue_packet.GetString().clear(); 948 } 949 else 950 continue_packet_error = true; 951 952 if (continue_packet_error) 953 { 954 // Either no vCont support, or we tried to use part of the vCont 955 // packet that wasn't supported by the remote GDB server. 956 // We need to try and make a simple packet that can do our continue 957 const size_t num_threads = GetThreadList().GetSize(); 958 const size_t num_continue_c_tids = m_continue_c_tids.size(); 959 const size_t num_continue_C_tids = m_continue_C_tids.size(); 960 const size_t num_continue_s_tids = m_continue_s_tids.size(); 961 const size_t num_continue_S_tids = m_continue_S_tids.size(); 962 if (num_continue_c_tids > 0) 963 { 964 if (num_continue_c_tids == num_threads) 965 { 966 // All threads are resuming... 967 m_gdb_comm.SetCurrentThreadForRun (-1); 968 continue_packet.PutChar ('c'); 969 continue_packet_error = false; 970 } 971 else if (num_continue_c_tids == 1 && 972 num_continue_C_tids == 0 && 973 num_continue_s_tids == 0 && 974 num_continue_S_tids == 0 ) 975 { 976 // Only one thread is continuing 977 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 978 continue_packet.PutChar ('c'); 979 continue_packet_error = false; 980 } 981 } 982 983 if (continue_packet_error && num_continue_C_tids > 0) 984 { 985 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 986 num_continue_C_tids > 0 && 987 num_continue_s_tids == 0 && 988 num_continue_S_tids == 0 ) 989 { 990 const int continue_signo = m_continue_C_tids.front().second; 991 // Only one thread is continuing 992 if (num_continue_C_tids > 1) 993 { 994 // More that one thread with a signal, yet we don't have 995 // vCont support and we are being asked to resume each 996 // thread with a signal, we need to make sure they are 997 // all the same signal, or we can't issue the continue 998 // accurately with the current support... 999 if (num_continue_C_tids > 1) 1000 { 1001 continue_packet_error = false; 1002 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1003 { 1004 if (m_continue_C_tids[i].second != continue_signo) 1005 continue_packet_error = true; 1006 } 1007 } 1008 if (!continue_packet_error) 1009 m_gdb_comm.SetCurrentThreadForRun (-1); 1010 } 1011 else 1012 { 1013 // Set the continue thread ID 1014 continue_packet_error = false; 1015 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1016 } 1017 if (!continue_packet_error) 1018 { 1019 // Add threads continuing with the same signo... 1020 continue_packet.Printf("C%2.2x", continue_signo); 1021 } 1022 } 1023 } 1024 1025 if (continue_packet_error && num_continue_s_tids > 0) 1026 { 1027 if (num_continue_s_tids == num_threads) 1028 { 1029 // All threads are resuming... 1030 m_gdb_comm.SetCurrentThreadForRun (-1); 1031 continue_packet.PutChar ('s'); 1032 continue_packet_error = false; 1033 } 1034 else if (num_continue_c_tids == 0 && 1035 num_continue_C_tids == 0 && 1036 num_continue_s_tids == 1 && 1037 num_continue_S_tids == 0 ) 1038 { 1039 // Only one thread is stepping 1040 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1041 continue_packet.PutChar ('s'); 1042 continue_packet_error = false; 1043 } 1044 } 1045 1046 if (!continue_packet_error && num_continue_S_tids > 0) 1047 { 1048 if (num_continue_S_tids == num_threads) 1049 { 1050 const int step_signo = m_continue_S_tids.front().second; 1051 // Are all threads trying to step with the same signal? 1052 continue_packet_error = false; 1053 if (num_continue_S_tids > 1) 1054 { 1055 for (size_t i=1; i<num_threads; ++i) 1056 { 1057 if (m_continue_S_tids[i].second != step_signo) 1058 continue_packet_error = true; 1059 } 1060 } 1061 if (!continue_packet_error) 1062 { 1063 // Add threads stepping with the same signo... 1064 m_gdb_comm.SetCurrentThreadForRun (-1); 1065 continue_packet.Printf("S%2.2x", step_signo); 1066 } 1067 } 1068 else if (num_continue_c_tids == 0 && 1069 num_continue_C_tids == 0 && 1070 num_continue_s_tids == 0 && 1071 num_continue_S_tids == 1 ) 1072 { 1073 // Only one thread is stepping with signal 1074 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1075 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1076 continue_packet_error = false; 1077 } 1078 } 1079 } 1080 1081 if (continue_packet_error) 1082 { 1083 error.SetErrorString ("can't make continue packet for this resume"); 1084 } 1085 else 1086 { 1087 EventSP event_sp; 1088 TimeValue timeout; 1089 timeout = TimeValue::Now(); 1090 timeout.OffsetWithSeconds (5); 1091 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1092 1093 if (listener.WaitForEvent (&timeout, event_sp) == false) 1094 error.SetErrorString("Resume timed out."); 1095 } 1096 } 1097 1098 return error; 1099 } 1100 1101 uint32_t 1102 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1103 { 1104 // locker will keep a mutex locked until it goes out of scope 1105 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1106 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1107 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID()); 1108 // Update the thread list's stop id immediately so we don't recurse into this function. 1109 1110 std::vector<lldb::tid_t> thread_ids; 1111 bool sequence_mutex_unavailable = false; 1112 const size_t num_thread_ids = m_gdb_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable); 1113 if (num_thread_ids > 0) 1114 { 1115 for (size_t i=0; i<num_thread_ids; ++i) 1116 { 1117 tid_t tid = thread_ids[i]; 1118 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false)); 1119 if (!thread_sp) 1120 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1121 new_thread_list.AddThread(thread_sp); 1122 } 1123 } 1124 1125 if (sequence_mutex_unavailable == false) 1126 SetThreadStopInfo (m_last_stop_packet); 1127 return new_thread_list.GetSize(false); 1128 } 1129 1130 1131 StateType 1132 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 1133 { 1134 stop_packet.SetFilePos (0); 1135 const char stop_type = stop_packet.GetChar(); 1136 switch (stop_type) 1137 { 1138 case 'T': 1139 case 'S': 1140 { 1141 if (GetStopID() == 0) 1142 { 1143 // Our first stop, make sure we have a process ID, and also make 1144 // sure we know about our registers 1145 if (GetID() == LLDB_INVALID_PROCESS_ID) 1146 { 1147 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 1148 if (pid != LLDB_INVALID_PROCESS_ID) 1149 SetID (pid); 1150 } 1151 BuildDynamicRegisterInfo (true); 1152 } 1153 // Stop with signal and thread info 1154 const uint8_t signo = stop_packet.GetHexU8(); 1155 std::string name; 1156 std::string value; 1157 std::string thread_name; 1158 std::string reason; 1159 std::string description; 1160 uint32_t exc_type = 0; 1161 std::vector<addr_t> exc_data; 1162 uint32_t tid = LLDB_INVALID_THREAD_ID; 1163 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1164 uint32_t exc_data_count = 0; 1165 ThreadSP thread_sp; 1166 1167 while (stop_packet.GetNameColonValue(name, value)) 1168 { 1169 if (name.compare("metype") == 0) 1170 { 1171 // exception type in big endian hex 1172 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 1173 } 1174 else if (name.compare("mecount") == 0) 1175 { 1176 // exception count in big endian hex 1177 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16); 1178 } 1179 else if (name.compare("medata") == 0) 1180 { 1181 // exception data in big endian hex 1182 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1183 } 1184 else if (name.compare("thread") == 0) 1185 { 1186 // thread in big endian hex 1187 tid = Args::StringToUInt32 (value.c_str(), 0, 16); 1188 Mutex::Locker locker (m_thread_list.GetMutex ()); 1189 thread_sp = m_thread_list.FindThreadByID(tid, false); 1190 if (!thread_sp) 1191 { 1192 // Create the thread if we need to 1193 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1194 m_thread_list.AddThread(thread_sp); 1195 } 1196 } 1197 else if (name.compare("hexname") == 0) 1198 { 1199 StringExtractor name_extractor; 1200 // Swap "value" over into "name_extractor" 1201 name_extractor.GetStringRef().swap(value); 1202 // Now convert the HEX bytes into a string value 1203 name_extractor.GetHexByteString (value); 1204 thread_name.swap (value); 1205 } 1206 else if (name.compare("name") == 0) 1207 { 1208 thread_name.swap (value); 1209 } 1210 else if (name.compare("qaddr") == 0) 1211 { 1212 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1213 } 1214 else if (name.compare("reason") == 0) 1215 { 1216 reason.swap(value); 1217 } 1218 else if (name.compare("description") == 0) 1219 { 1220 StringExtractor desc_extractor; 1221 // Swap "value" over into "name_extractor" 1222 desc_extractor.GetStringRef().swap(value); 1223 // Now convert the HEX bytes into a string value 1224 desc_extractor.GetHexByteString (thread_name); 1225 } 1226 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1])) 1227 { 1228 // We have a register number that contains an expedited 1229 // register value. Lets supply this register to our thread 1230 // so it won't have to go and read it. 1231 if (thread_sp) 1232 { 1233 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16); 1234 1235 if (reg != UINT32_MAX) 1236 { 1237 StringExtractor reg_value_extractor; 1238 // Swap "value" over into "reg_value_extractor" 1239 reg_value_extractor.GetStringRef().swap(value); 1240 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor)) 1241 { 1242 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'", 1243 name.c_str(), 1244 reg, 1245 reg, 1246 reg_value_extractor.GetStringRef().c_str(), 1247 stop_packet.GetStringRef().c_str()); 1248 } 1249 } 1250 } 1251 } 1252 } 1253 1254 if (thread_sp) 1255 { 1256 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1257 1258 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1259 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1260 if (exc_type != 0) 1261 { 1262 const size_t exc_data_size = exc_data.size(); 1263 1264 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1265 exc_type, 1266 exc_data_size, 1267 exc_data_size >= 1 ? exc_data[0] : 0, 1268 exc_data_size >= 2 ? exc_data[1] : 0, 1269 exc_data_size >= 3 ? exc_data[2] : 0)); 1270 } 1271 else 1272 { 1273 bool handled = false; 1274 if (!reason.empty()) 1275 { 1276 if (reason.compare("trace") == 0) 1277 { 1278 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1279 handled = true; 1280 } 1281 else if (reason.compare("breakpoint") == 0) 1282 { 1283 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1284 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc); 1285 if (bp_site_sp) 1286 { 1287 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1288 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1289 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1290 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1291 { 1292 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1293 handled = true; 1294 } 1295 } 1296 1297 if (!handled) 1298 { 1299 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1300 } 1301 } 1302 else if (reason.compare("trap") == 0) 1303 { 1304 // Let the trap just use the standard signal stop reason below... 1305 } 1306 else if (reason.compare("watchpoint") == 0) 1307 { 1308 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1309 // TODO: locate the watchpoint somehow... 1310 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1311 handled = true; 1312 } 1313 else if (reason.compare("exception") == 0) 1314 { 1315 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1316 handled = true; 1317 } 1318 } 1319 1320 if (signo) 1321 { 1322 if (signo == SIGTRAP) 1323 { 1324 // Currently we are going to assume SIGTRAP means we are either 1325 // hitting a breakpoint or hardware single stepping. 1326 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1327 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess().GetBreakpointSiteList().FindByAddress(pc); 1328 if (bp_site_sp) 1329 { 1330 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1331 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1332 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1333 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1334 { 1335 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1336 handled = true; 1337 } 1338 } 1339 if (!handled) 1340 { 1341 // TODO: check for breakpoint or trap opcode in case there is a hard 1342 // coded software trap 1343 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1344 handled = true; 1345 } 1346 } 1347 if (!handled) 1348 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1349 } 1350 else 1351 { 1352 StopInfoSP invalid_stop_info_sp; 1353 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1354 } 1355 1356 if (!description.empty()) 1357 { 1358 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ()); 1359 if (stop_info_sp) 1360 { 1361 stop_info_sp->SetDescription (description.c_str()); 1362 } 1363 else 1364 { 1365 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1366 } 1367 } 1368 } 1369 } 1370 return eStateStopped; 1371 } 1372 break; 1373 1374 case 'W': 1375 // process exited 1376 return eStateExited; 1377 1378 default: 1379 break; 1380 } 1381 return eStateInvalid; 1382 } 1383 1384 void 1385 ProcessGDBRemote::RefreshStateAfterStop () 1386 { 1387 // Let all threads recover from stopping and do any clean up based 1388 // on the previous thread state (if any). 1389 m_thread_list.RefreshStateAfterStop(); 1390 SetThreadStopInfo (m_last_stop_packet); 1391 } 1392 1393 Error 1394 ProcessGDBRemote::DoHalt (bool &caused_stop) 1395 { 1396 Error error; 1397 1398 bool timed_out = false; 1399 Mutex::Locker locker; 1400 1401 if (m_public_state.GetValue() == eStateAttaching) 1402 { 1403 // We are being asked to halt during an attach. We need to just close 1404 // our file handle and debugserver will go away, and we can be done... 1405 m_gdb_comm.Disconnect(); 1406 } 1407 else 1408 { 1409 if (!m_gdb_comm.SendInterrupt (locker, 2, caused_stop, timed_out)) 1410 { 1411 if (timed_out) 1412 error.SetErrorString("timed out sending interrupt packet"); 1413 else 1414 error.SetErrorString("unknown error sending interrupt packet"); 1415 } 1416 } 1417 return error; 1418 } 1419 1420 Error 1421 ProcessGDBRemote::InterruptIfRunning 1422 ( 1423 bool discard_thread_plans, 1424 bool catch_stop_event, 1425 EventSP &stop_event_sp 1426 ) 1427 { 1428 Error error; 1429 1430 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1431 1432 bool paused_private_state_thread = false; 1433 const bool is_running = m_gdb_comm.IsRunning(); 1434 if (log) 1435 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i", 1436 discard_thread_plans, 1437 catch_stop_event, 1438 is_running); 1439 1440 if (discard_thread_plans) 1441 { 1442 if (log) 1443 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans"); 1444 m_thread_list.DiscardThreadPlans(); 1445 } 1446 if (is_running) 1447 { 1448 if (catch_stop_event) 1449 { 1450 if (log) 1451 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread"); 1452 PausePrivateStateThread(); 1453 paused_private_state_thread = true; 1454 } 1455 1456 bool timed_out = false; 1457 bool sent_interrupt = false; 1458 Mutex::Locker locker; 1459 1460 if (!m_gdb_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out)) 1461 { 1462 if (timed_out) 1463 error.SetErrorString("timed out sending interrupt packet"); 1464 else 1465 error.SetErrorString("unknown error sending interrupt packet"); 1466 if (paused_private_state_thread) 1467 ResumePrivateStateThread(); 1468 return error; 1469 } 1470 1471 if (catch_stop_event) 1472 { 1473 // LISTEN HERE 1474 TimeValue timeout_time; 1475 timeout_time = TimeValue::Now(); 1476 timeout_time.OffsetWithSeconds(5); 1477 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp); 1478 1479 timed_out = state == eStateInvalid; 1480 if (log) 1481 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out); 1482 1483 if (timed_out) 1484 error.SetErrorString("unable to verify target stopped"); 1485 } 1486 1487 if (paused_private_state_thread) 1488 { 1489 if (log) 1490 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread"); 1491 ResumePrivateStateThread(); 1492 } 1493 } 1494 return error; 1495 } 1496 1497 Error 1498 ProcessGDBRemote::WillDetach () 1499 { 1500 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1501 if (log) 1502 log->Printf ("ProcessGDBRemote::WillDetach()"); 1503 1504 bool discard_thread_plans = true; 1505 bool catch_stop_event = true; 1506 EventSP event_sp; 1507 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp); 1508 } 1509 1510 Error 1511 ProcessGDBRemote::DoDetach() 1512 { 1513 Error error; 1514 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1515 if (log) 1516 log->Printf ("ProcessGDBRemote::DoDetach()"); 1517 1518 DisableAllBreakpointSites (); 1519 1520 m_thread_list.DiscardThreadPlans(); 1521 1522 size_t response_size = m_gdb_comm.SendPacket ("D", 1); 1523 if (log) 1524 { 1525 if (response_size) 1526 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1527 else 1528 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed"); 1529 } 1530 // Sleep for one second to let the process get all detached... 1531 StopAsyncThread (); 1532 1533 SetPrivateState (eStateDetached); 1534 ResumePrivateStateThread(); 1535 1536 //KillDebugserverProcess (); 1537 return error; 1538 } 1539 1540 Error 1541 ProcessGDBRemote::DoDestroy () 1542 { 1543 Error error; 1544 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1545 if (log) 1546 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1547 1548 // Interrupt if our inferior is running... 1549 if (m_gdb_comm.IsConnected()) 1550 { 1551 if (m_public_state.GetValue() != eStateAttaching) 1552 { 1553 1554 StringExtractorGDBRemote response; 1555 bool send_async = true; 1556 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async)) 1557 { 1558 char packet_cmd = response.GetChar(0); 1559 1560 if (packet_cmd == 'W' || packet_cmd == 'X') 1561 { 1562 m_last_stop_packet = response; 1563 SetExitStatus(response.GetHexU8(), NULL); 1564 } 1565 } 1566 else 1567 { 1568 SetExitStatus(SIGABRT, NULL); 1569 //error.SetErrorString("kill packet failed"); 1570 } 1571 } 1572 } 1573 StopAsyncThread (); 1574 KillDebugserverProcess (); 1575 return error; 1576 } 1577 1578 //------------------------------------------------------------------ 1579 // Process Queries 1580 //------------------------------------------------------------------ 1581 1582 bool 1583 ProcessGDBRemote::IsAlive () 1584 { 1585 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 1586 } 1587 1588 addr_t 1589 ProcessGDBRemote::GetImageInfoAddress() 1590 { 1591 if (!m_gdb_comm.IsRunning()) 1592 { 1593 StringExtractorGDBRemote response; 1594 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false)) 1595 { 1596 if (response.IsNormalResponse()) 1597 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1598 } 1599 } 1600 return LLDB_INVALID_ADDRESS; 1601 } 1602 1603 //------------------------------------------------------------------ 1604 // Process Memory 1605 //------------------------------------------------------------------ 1606 size_t 1607 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1608 { 1609 if (size > m_max_memory_size) 1610 { 1611 // Keep memory read sizes down to a sane limit. This function will be 1612 // called multiple times in order to complete the task by 1613 // lldb_private::Process so it is ok to do this. 1614 size = m_max_memory_size; 1615 } 1616 1617 char packet[64]; 1618 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1619 assert (packet_len + 1 < sizeof(packet)); 1620 StringExtractorGDBRemote response; 1621 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true)) 1622 { 1623 if (response.IsNormalResponse()) 1624 { 1625 error.Clear(); 1626 return response.GetHexBytes(buf, size, '\xdd'); 1627 } 1628 else if (response.IsErrorResponse()) 1629 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1630 else if (response.IsUnsupportedResponse()) 1631 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1632 else 1633 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1634 } 1635 else 1636 { 1637 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1638 } 1639 return 0; 1640 } 1641 1642 size_t 1643 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1644 { 1645 if (size > m_max_memory_size) 1646 { 1647 // Keep memory read sizes down to a sane limit. This function will be 1648 // called multiple times in order to complete the task by 1649 // lldb_private::Process so it is ok to do this. 1650 size = m_max_memory_size; 1651 } 1652 1653 StreamString packet; 1654 packet.Printf("M%llx,%zx:", addr, size); 1655 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1656 StringExtractorGDBRemote response; 1657 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true)) 1658 { 1659 if (response.IsOKResponse()) 1660 { 1661 error.Clear(); 1662 return size; 1663 } 1664 else if (response.IsErrorResponse()) 1665 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1666 else if (response.IsUnsupportedResponse()) 1667 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1668 else 1669 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1670 } 1671 else 1672 { 1673 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1674 } 1675 return 0; 1676 } 1677 1678 lldb::addr_t 1679 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1680 { 1681 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 1682 1683 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 1684 switch (supported) 1685 { 1686 case eLazyBoolCalculate: 1687 case eLazyBoolYes: 1688 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 1689 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 1690 return allocated_addr; 1691 1692 case eLazyBoolNo: 1693 // Call mmap() to create memory in the inferior.. 1694 unsigned prot = 0; 1695 if (permissions & lldb::ePermissionsReadable) 1696 prot |= eMmapProtRead; 1697 if (permissions & lldb::ePermissionsWritable) 1698 prot |= eMmapProtWrite; 1699 if (permissions & lldb::ePermissionsExecutable) 1700 prot |= eMmapProtExec; 1701 1702 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 1703 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 1704 m_addr_to_mmap_size[allocated_addr] = size; 1705 else 1706 allocated_addr = LLDB_INVALID_ADDRESS; 1707 break; 1708 } 1709 1710 if (allocated_addr == LLDB_INVALID_ADDRESS) 1711 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 1712 else 1713 error.Clear(); 1714 return allocated_addr; 1715 } 1716 1717 Error 1718 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 1719 { 1720 Error error; 1721 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 1722 1723 switch (supported) 1724 { 1725 case eLazyBoolCalculate: 1726 // We should never be deallocating memory without allocating memory 1727 // first so we should never get eLazyBoolCalculate 1728 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 1729 break; 1730 1731 case eLazyBoolYes: 1732 if (!m_gdb_comm.DeallocateMemory (addr)) 1733 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 1734 break; 1735 1736 case eLazyBoolNo: 1737 // Call munmap() to deallocate memory in the inferior.. 1738 { 1739 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 1740 if (pos != m_addr_to_mmap_size.end() && 1741 InferiorCallMunmap(this, addr, pos->second)) 1742 m_addr_to_mmap_size.erase (pos); 1743 else 1744 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 1745 } 1746 break; 1747 } 1748 1749 return error; 1750 } 1751 1752 1753 //------------------------------------------------------------------ 1754 // Process STDIO 1755 //------------------------------------------------------------------ 1756 1757 size_t 1758 ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error) 1759 { 1760 Mutex::Locker locker(m_stdio_mutex); 1761 size_t bytes_available = m_stdout_data.size(); 1762 if (bytes_available > 0) 1763 { 1764 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1765 if (log) 1766 log->Printf ("ProcessGDBRemote::%s (&%p[%lu]) ...", __FUNCTION__, buf, buf_size); 1767 if (bytes_available > buf_size) 1768 { 1769 memcpy(buf, m_stdout_data.c_str(), buf_size); 1770 m_stdout_data.erase(0, buf_size); 1771 bytes_available = buf_size; 1772 } 1773 else 1774 { 1775 memcpy(buf, m_stdout_data.c_str(), bytes_available); 1776 m_stdout_data.clear(); 1777 1778 //ResetEventBits(eBroadcastBitSTDOUT); 1779 } 1780 } 1781 return bytes_available; 1782 } 1783 1784 size_t 1785 ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error) 1786 { 1787 // Can we get STDERR through the remote protocol? 1788 return 0; 1789 } 1790 1791 size_t 1792 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 1793 { 1794 if (m_stdio_communication.IsConnected()) 1795 { 1796 ConnectionStatus status; 1797 m_stdio_communication.Write(src, src_len, status, NULL); 1798 } 1799 return 0; 1800 } 1801 1802 Error 1803 ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 1804 { 1805 Error error; 1806 assert (bp_site != NULL); 1807 1808 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 1809 user_id_t site_id = bp_site->GetID(); 1810 const addr_t addr = bp_site->GetLoadAddress(); 1811 if (log) 1812 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr); 1813 1814 if (bp_site->IsEnabled()) 1815 { 1816 if (log) 1817 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 1818 return error; 1819 } 1820 else 1821 { 1822 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1823 1824 if (bp_site->HardwarePreferred()) 1825 { 1826 // Try and set hardware breakpoint, and if that fails, fall through 1827 // and set a software breakpoint? 1828 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware)) 1829 { 1830 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 1831 { 1832 bp_site->SetEnabled(true); 1833 bp_site->SetType (BreakpointSite::eHardware); 1834 return error; 1835 } 1836 } 1837 } 1838 1839 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware)) 1840 { 1841 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 1842 { 1843 bp_site->SetEnabled(true); 1844 bp_site->SetType (BreakpointSite::eExternal); 1845 return error; 1846 } 1847 } 1848 1849 return EnableSoftwareBreakpoint (bp_site); 1850 } 1851 1852 if (log) 1853 { 1854 const char *err_string = error.AsCString(); 1855 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 1856 bp_site->GetLoadAddress(), 1857 err_string ? err_string : "NULL"); 1858 } 1859 // We shouldn't reach here on a successful breakpoint enable... 1860 if (error.Success()) 1861 error.SetErrorToGenericError(); 1862 return error; 1863 } 1864 1865 Error 1866 ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 1867 { 1868 Error error; 1869 assert (bp_site != NULL); 1870 addr_t addr = bp_site->GetLoadAddress(); 1871 user_id_t site_id = bp_site->GetID(); 1872 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 1873 if (log) 1874 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr); 1875 1876 if (bp_site->IsEnabled()) 1877 { 1878 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1879 1880 BreakpointSite::Type bp_type = bp_site->GetType(); 1881 switch (bp_type) 1882 { 1883 case BreakpointSite::eSoftware: 1884 error = DisableSoftwareBreakpoint (bp_site); 1885 break; 1886 1887 case BreakpointSite::eHardware: 1888 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 1889 error.SetErrorToGenericError(); 1890 break; 1891 1892 case BreakpointSite::eExternal: 1893 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 1894 error.SetErrorToGenericError(); 1895 break; 1896 } 1897 if (error.Success()) 1898 bp_site->SetEnabled(false); 1899 } 1900 else 1901 { 1902 if (log) 1903 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 1904 return error; 1905 } 1906 1907 if (error.Success()) 1908 error.SetErrorToGenericError(); 1909 return error; 1910 } 1911 1912 // Pre-requisite: wp != NULL. 1913 static GDBStoppointType 1914 GetGDBStoppointType (Watchpoint *wp) 1915 { 1916 assert(wp); 1917 bool watch_read = wp->WatchpointRead(); 1918 bool watch_write = wp->WatchpointWrite(); 1919 1920 // watch_read and watch_write cannot both be false. 1921 assert(watch_read || watch_write); 1922 if (watch_read && watch_write) 1923 return eWatchpointReadWrite; 1924 else if (watch_read) 1925 return eWatchpointRead; 1926 else // Must be watch_write, then. 1927 return eWatchpointWrite; 1928 } 1929 1930 Error 1931 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp) 1932 { 1933 Error error; 1934 if (wp) 1935 { 1936 user_id_t watchID = wp->GetID(); 1937 addr_t addr = wp->GetLoadAddress(); 1938 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 1939 if (log) 1940 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID); 1941 if (wp->IsEnabled()) 1942 { 1943 if (log) 1944 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 1945 return error; 1946 } 1947 1948 GDBStoppointType type = GetGDBStoppointType(wp); 1949 // Pass down an appropriate z/Z packet... 1950 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 1951 { 1952 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 1953 { 1954 wp->SetEnabled(true); 1955 return error; 1956 } 1957 else 1958 error.SetErrorString("sending gdb watchpoint packet failed"); 1959 } 1960 else 1961 error.SetErrorString("watchpoints not supported"); 1962 } 1963 else 1964 { 1965 error.SetErrorString("Watchpoint argument was NULL."); 1966 } 1967 if (error.Success()) 1968 error.SetErrorToGenericError(); 1969 return error; 1970 } 1971 1972 Error 1973 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp) 1974 { 1975 Error error; 1976 if (wp) 1977 { 1978 user_id_t watchID = wp->GetID(); 1979 1980 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 1981 1982 addr_t addr = wp->GetLoadAddress(); 1983 if (log) 1984 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr); 1985 1986 if (!wp->IsEnabled()) 1987 { 1988 if (log) 1989 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 1990 return error; 1991 } 1992 1993 if (wp->IsHardware()) 1994 { 1995 GDBStoppointType type = GetGDBStoppointType(wp); 1996 // Pass down an appropriate z/Z packet... 1997 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 1998 { 1999 wp->SetEnabled(false); 2000 return error; 2001 } 2002 else 2003 error.SetErrorString("sending gdb watchpoint packet failed"); 2004 } 2005 // TODO: clear software watchpoints if we implement them 2006 } 2007 else 2008 { 2009 error.SetErrorString("Watchpoint argument was NULL."); 2010 } 2011 if (error.Success()) 2012 error.SetErrorToGenericError(); 2013 return error; 2014 } 2015 2016 void 2017 ProcessGDBRemote::Clear() 2018 { 2019 m_flags = 0; 2020 m_thread_list.Clear(); 2021 { 2022 Mutex::Locker locker(m_stdio_mutex); 2023 m_stdout_data.clear(); 2024 } 2025 } 2026 2027 Error 2028 ProcessGDBRemote::DoSignal (int signo) 2029 { 2030 Error error; 2031 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2032 if (log) 2033 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2034 2035 if (!m_gdb_comm.SendAsyncSignal (signo)) 2036 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2037 return error; 2038 } 2039 2040 Error 2041 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 2042 { 2043 Error error; 2044 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2045 { 2046 // If we locate debugserver, keep that located version around 2047 static FileSpec g_debugserver_file_spec; 2048 2049 ProcessLaunchInfo launch_info; 2050 char debugserver_path[PATH_MAX]; 2051 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile(); 2052 2053 // Always check to see if we have an environment override for the path 2054 // to the debugserver to use and use it if we do. 2055 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 2056 if (env_debugserver_path) 2057 debugserver_file_spec.SetFile (env_debugserver_path, false); 2058 else 2059 debugserver_file_spec = g_debugserver_file_spec; 2060 bool debugserver_exists = debugserver_file_spec.Exists(); 2061 if (!debugserver_exists) 2062 { 2063 // The debugserver binary is in the LLDB.framework/Resources 2064 // directory. 2065 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 2066 { 2067 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 2068 debugserver_exists = debugserver_file_spec.Exists(); 2069 if (debugserver_exists) 2070 { 2071 g_debugserver_file_spec = debugserver_file_spec; 2072 } 2073 else 2074 { 2075 g_debugserver_file_spec.Clear(); 2076 debugserver_file_spec.Clear(); 2077 } 2078 } 2079 } 2080 2081 if (debugserver_exists) 2082 { 2083 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 2084 2085 m_stdio_communication.Clear(); 2086 2087 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2088 2089 Args &debugserver_args = launch_info.GetArguments(); 2090 char arg_cstr[PATH_MAX]; 2091 2092 // Start args with "debugserver /file/path -r --" 2093 debugserver_args.AppendArgument(debugserver_path); 2094 debugserver_args.AppendArgument(debugserver_url); 2095 // use native registers, not the GDB registers 2096 debugserver_args.AppendArgument("--native-regs"); 2097 // make debugserver run in its own session so signals generated by 2098 // special terminal key sequences (^C) don't affect debugserver 2099 debugserver_args.AppendArgument("--setsid"); 2100 2101 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 2102 if (env_debugserver_log_file) 2103 { 2104 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 2105 debugserver_args.AppendArgument(arg_cstr); 2106 } 2107 2108 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 2109 if (env_debugserver_log_flags) 2110 { 2111 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 2112 debugserver_args.AppendArgument(arg_cstr); 2113 } 2114 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 2115 // debugserver_args.AppendArgument("--log-flags=0x802e0e"); 2116 2117 // We currently send down all arguments, attach pids, or attach 2118 // process names in dedicated GDB server packets, so we don't need 2119 // to pass them as arguments. This is currently because of all the 2120 // things we need to setup prior to launching: the environment, 2121 // current working dir, file actions, etc. 2122 #if 0 2123 // Now append the program arguments 2124 if (inferior_argv) 2125 { 2126 // Terminate the debugserver args so we can now append the inferior args 2127 debugserver_args.AppendArgument("--"); 2128 2129 for (int i = 0; inferior_argv[i] != NULL; ++i) 2130 debugserver_args.AppendArgument (inferior_argv[i]); 2131 } 2132 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 2133 { 2134 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 2135 debugserver_args.AppendArgument (arg_cstr); 2136 } 2137 else if (attach_name && attach_name[0]) 2138 { 2139 if (wait_for_launch) 2140 debugserver_args.AppendArgument ("--waitfor"); 2141 else 2142 debugserver_args.AppendArgument ("--attach"); 2143 debugserver_args.AppendArgument (attach_name); 2144 } 2145 #endif 2146 2147 ProcessLaunchInfo::FileAction file_action; 2148 2149 // Close STDIN, STDOUT and STDERR. We might need to redirect them 2150 // to "/dev/null" if we run into any problems. 2151 file_action.Close (STDIN_FILENO); 2152 launch_info.AppendFileAction (file_action); 2153 file_action.Close (STDOUT_FILENO); 2154 launch_info.AppendFileAction (file_action); 2155 file_action.Close (STDERR_FILENO); 2156 launch_info.AppendFileAction (file_action); 2157 2158 if (log) 2159 { 2160 StreamString strm; 2161 debugserver_args.Dump (&strm); 2162 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 2163 } 2164 2165 error = Host::LaunchProcess(launch_info); 2166 2167 if (error.Success ()) 2168 m_debugserver_pid = launch_info.GetProcessID(); 2169 else 2170 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2171 2172 if (error.Fail() || log) 2173 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%i, path='%s'", m_debugserver_pid, debugserver_path); 2174 } 2175 else 2176 { 2177 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME); 2178 } 2179 2180 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2181 StartAsyncThread (); 2182 } 2183 return error; 2184 } 2185 2186 bool 2187 ProcessGDBRemote::MonitorDebugserverProcess 2188 ( 2189 void *callback_baton, 2190 lldb::pid_t debugserver_pid, 2191 int signo, // Zero for no signal 2192 int exit_status // Exit value of process if signal is zero 2193 ) 2194 { 2195 // We pass in the ProcessGDBRemote inferior process it and name it 2196 // "gdb_remote_pid". The process ID is passed in the "callback_baton" 2197 // pointer value itself, thus we need the double cast... 2198 2199 // "debugserver_pid" argument passed in is the process ID for 2200 // debugserver that we are tracking... 2201 2202 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2203 2204 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2205 if (log) 2206 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2207 2208 if (process) 2209 { 2210 // Sleep for a half a second to make sure our inferior process has 2211 // time to set its exit status before we set it incorrectly when 2212 // both the debugserver and the inferior process shut down. 2213 usleep (500000); 2214 // If our process hasn't yet exited, debugserver might have died. 2215 // If the process did exit, the we are reaping it. 2216 const StateType state = process->GetState(); 2217 2218 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2219 state != eStateInvalid && 2220 state != eStateUnloaded && 2221 state != eStateExited && 2222 state != eStateDetached) 2223 { 2224 char error_str[1024]; 2225 if (signo) 2226 { 2227 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2228 if (signal_cstr) 2229 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2230 else 2231 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2232 } 2233 else 2234 { 2235 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2236 } 2237 2238 process->SetExitStatus (-1, error_str); 2239 } 2240 // Debugserver has exited we need to let our ProcessGDBRemote 2241 // know that it no longer has a debugserver instance 2242 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2243 // We are returning true to this function below, so we can 2244 // forget about the monitor handle. 2245 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD; 2246 } 2247 return true; 2248 } 2249 2250 void 2251 ProcessGDBRemote::KillDebugserverProcess () 2252 { 2253 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2254 { 2255 ::kill (m_debugserver_pid, SIGINT); 2256 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2257 } 2258 } 2259 2260 void 2261 ProcessGDBRemote::Initialize() 2262 { 2263 static bool g_initialized = false; 2264 2265 if (g_initialized == false) 2266 { 2267 g_initialized = true; 2268 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2269 GetPluginDescriptionStatic(), 2270 CreateInstance); 2271 2272 Log::Callbacks log_callbacks = { 2273 ProcessGDBRemoteLog::DisableLog, 2274 ProcessGDBRemoteLog::EnableLog, 2275 ProcessGDBRemoteLog::ListLogCategories 2276 }; 2277 2278 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2279 } 2280 } 2281 2282 bool 2283 ProcessGDBRemote::StartAsyncThread () 2284 { 2285 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2286 2287 if (log) 2288 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2289 2290 // Create a thread that watches our internal state and controls which 2291 // events make it to clients (into the DCProcess event queue). 2292 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2293 return IS_VALID_LLDB_HOST_THREAD(m_async_thread); 2294 } 2295 2296 void 2297 ProcessGDBRemote::StopAsyncThread () 2298 { 2299 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2300 2301 if (log) 2302 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2303 2304 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2305 2306 // This will shut down the async thread. 2307 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2308 2309 // Stop the stdio thread 2310 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2311 { 2312 Host::ThreadJoin (m_async_thread, NULL, NULL); 2313 } 2314 } 2315 2316 2317 void * 2318 ProcessGDBRemote::AsyncThread (void *arg) 2319 { 2320 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2321 2322 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2323 if (log) 2324 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID()); 2325 2326 Listener listener ("ProcessGDBRemote::AsyncThread"); 2327 EventSP event_sp; 2328 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2329 eBroadcastBitAsyncThreadShouldExit; 2330 2331 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2332 { 2333 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2334 2335 bool done = false; 2336 while (!done) 2337 { 2338 if (log) 2339 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2340 if (listener.WaitForEvent (NULL, event_sp)) 2341 { 2342 const uint32_t event_type = event_sp->GetType(); 2343 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2344 { 2345 if (log) 2346 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2347 2348 switch (event_type) 2349 { 2350 case eBroadcastBitAsyncContinue: 2351 { 2352 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2353 2354 if (continue_packet) 2355 { 2356 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2357 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2358 if (log) 2359 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2360 2361 if (::strstr (continue_cstr, "vAttach") == NULL) 2362 process->SetPrivateState(eStateRunning); 2363 StringExtractorGDBRemote response; 2364 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2365 2366 switch (stop_state) 2367 { 2368 case eStateStopped: 2369 case eStateCrashed: 2370 case eStateSuspended: 2371 process->m_last_stop_packet = response; 2372 process->SetPrivateState (stop_state); 2373 break; 2374 2375 case eStateExited: 2376 process->m_last_stop_packet = response; 2377 response.SetFilePos(1); 2378 process->SetExitStatus(response.GetHexU8(), NULL); 2379 done = true; 2380 break; 2381 2382 case eStateInvalid: 2383 process->SetExitStatus(-1, "lost connection"); 2384 break; 2385 2386 default: 2387 process->SetPrivateState (stop_state); 2388 break; 2389 } 2390 } 2391 } 2392 break; 2393 2394 case eBroadcastBitAsyncThreadShouldExit: 2395 if (log) 2396 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2397 done = true; 2398 break; 2399 2400 default: 2401 if (log) 2402 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2403 done = true; 2404 break; 2405 } 2406 } 2407 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 2408 { 2409 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 2410 { 2411 process->SetExitStatus (-1, "lost connection"); 2412 done = true; 2413 } 2414 } 2415 } 2416 else 2417 { 2418 if (log) 2419 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2420 done = true; 2421 } 2422 } 2423 } 2424 2425 if (log) 2426 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID()); 2427 2428 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2429 return NULL; 2430 } 2431 2432 const char * 2433 ProcessGDBRemote::GetDispatchQueueNameForThread 2434 ( 2435 addr_t thread_dispatch_qaddr, 2436 std::string &dispatch_queue_name 2437 ) 2438 { 2439 dispatch_queue_name.clear(); 2440 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2441 { 2442 // Cache the dispatch_queue_offsets_addr value so we don't always have 2443 // to look it up 2444 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2445 { 2446 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); 2447 const Symbol *dispatch_queue_offsets_symbol = NULL; 2448 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false), NULL, NULL)); 2449 if (module_sp) 2450 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2451 2452 if (dispatch_queue_offsets_symbol == NULL) 2453 { 2454 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false), NULL, NULL); 2455 if (module_sp) 2456 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2457 } 2458 if (dispatch_queue_offsets_symbol) 2459 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target); 2460 2461 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2462 return NULL; 2463 } 2464 2465 uint8_t memory_buffer[8]; 2466 DataExtractor data (memory_buffer, 2467 sizeof(memory_buffer), 2468 m_target.GetArchitecture().GetByteOrder(), 2469 m_target.GetArchitecture().GetAddressByteSize()); 2470 2471 // Excerpt from src/queue_private.h 2472 struct dispatch_queue_offsets_s 2473 { 2474 uint16_t dqo_version; 2475 uint16_t dqo_label; 2476 uint16_t dqo_label_size; 2477 } dispatch_queue_offsets; 2478 2479 2480 Error error; 2481 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2482 { 2483 uint32_t data_offset = 0; 2484 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2485 { 2486 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2487 { 2488 data_offset = 0; 2489 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2490 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2491 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2492 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2493 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2494 dispatch_queue_name.erase (bytes_read); 2495 } 2496 } 2497 } 2498 } 2499 if (dispatch_queue_name.empty()) 2500 return NULL; 2501 return dispatch_queue_name.c_str(); 2502 } 2503 2504 //uint32_t 2505 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2506 //{ 2507 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 2508 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 2509 // if (m_local_debugserver) 2510 // { 2511 // return Host::ListProcessesMatchingName (name, matches, pids); 2512 // } 2513 // else 2514 // { 2515 // // FIXME: Implement talking to the remote debugserver. 2516 // return 0; 2517 // } 2518 // 2519 //} 2520 // 2521 bool 2522 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 2523 lldb_private::StoppointCallbackContext *context, 2524 lldb::user_id_t break_id, 2525 lldb::user_id_t break_loc_id) 2526 { 2527 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 2528 // run so I can stop it if that's what I want to do. 2529 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2530 if (log) 2531 log->Printf("Hit New Thread Notification breakpoint."); 2532 return false; 2533 } 2534 2535 2536 bool 2537 ProcessGDBRemote::StartNoticingNewThreads() 2538 { 2539 static const char *bp_names[] = 2540 { 2541 "start_wqthread", 2542 "_pthread_wqthread", 2543 "_pthread_start", 2544 NULL 2545 }; 2546 2547 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2548 size_t num_bps = m_thread_observation_bps.size(); 2549 if (num_bps != 0) 2550 { 2551 for (int i = 0; i < num_bps; i++) 2552 { 2553 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]); 2554 if (break_sp) 2555 { 2556 if (log && log->GetVerbose()) 2557 log->Printf("Enabled noticing new thread breakpoint."); 2558 break_sp->SetEnabled(true); 2559 } 2560 } 2561 } 2562 else 2563 { 2564 for (int i = 0; bp_names[i] != NULL; i++) 2565 { 2566 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, NULL, bp_names[i], eFunctionNameTypeFull, true).get(); 2567 if (breakpoint) 2568 { 2569 if (log && log->GetVerbose()) 2570 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]); 2571 m_thread_observation_bps.push_back(breakpoint->GetID()); 2572 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 2573 } 2574 else 2575 { 2576 if (log) 2577 log->Printf("Failed to create new thread notification breakpoint."); 2578 return false; 2579 } 2580 } 2581 } 2582 2583 return true; 2584 } 2585 2586 bool 2587 ProcessGDBRemote::StopNoticingNewThreads() 2588 { 2589 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2590 if (log && log->GetVerbose()) 2591 log->Printf ("Disabling new thread notification breakpoint."); 2592 size_t num_bps = m_thread_observation_bps.size(); 2593 if (num_bps != 0) 2594 { 2595 for (int i = 0; i < num_bps; i++) 2596 { 2597 2598 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]); 2599 if (break_sp) 2600 { 2601 break_sp->SetEnabled(false); 2602 } 2603 } 2604 } 2605 return true; 2606 } 2607 2608 2609