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