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