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