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