ProcessGDBRemote.cpp revision 84cdc15005983e5244d665fa779e33c2b6fac95f
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 <mach/mach.h> 13#include <mach-o/dyld.h> 14#include <spawn.h> 15#include <sys/fcntl.h> 16#include <sys/types.h> 17#include <sys/ptrace.h> 18#include <sys/stat.h> 19#include <sys/sysctl.h> 20#include <unistd.h> 21 22// C++ Includes 23#include <algorithm> 24#include <map> 25 26// Other libraries and framework includes 27 28#include "lldb/Breakpoint/WatchpointLocation.h" 29#include "lldb/Interpreter/Args.h" 30#include "lldb/Core/ArchSpec.h" 31#include "lldb/Core/Debugger.h" 32#include "lldb/Core/ConnectionFileDescriptor.h" 33#include "lldb/Core/FileSpec.h" 34#include "lldb/Core/InputReader.h" 35#include "lldb/Core/Module.h" 36#include "lldb/Core/PluginManager.h" 37#include "lldb/Core/State.h" 38#include "lldb/Core/StreamString.h" 39#include "lldb/Core/Timer.h" 40#include "lldb/Host/TimeValue.h" 41#include "lldb/Symbol/ObjectFile.h" 42#include "lldb/Target/DynamicLoader.h" 43#include "lldb/Target/Target.h" 44#include "lldb/Target/TargetList.h" 45#include "lldb/Utility/PseudoTerminal.h" 46 47// Project includes 48#include "lldb/Host/Host.h" 49#include "StringExtractorGDBRemote.h" 50#include "GDBRemoteRegisterContext.h" 51#include "ProcessGDBRemote.h" 52#include "ProcessGDBRemoteLog.h" 53#include "ThreadGDBRemote.h" 54#include "libunwind.h" 55#include "MacOSXLibunwindCallbacks.h" 56 57#if defined (__i386__) || defined (__x86_64__) 58#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_I386_BPT 59#define MACH_EXC_DATA0_TRACE EXC_I386_SGL 60#elif defined (__powerpc__) || defined (__ppc__) || defined (__ppc64__) 61#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_PPC_BREAKPOINT 62#elif defined (__arm__) 63#define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_ARM_BREAKPOINT 64#endif 65 66 67#define DEBUGSERVER_BASENAME "debugserver" 68using namespace lldb; 69using namespace lldb_private; 70 71static inline uint16_t 72get_random_port () 73{ 74 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u; 75} 76 77 78const char * 79ProcessGDBRemote::GetPluginNameStatic() 80{ 81 return "process.gdb-remote"; 82} 83 84const char * 85ProcessGDBRemote::GetPluginDescriptionStatic() 86{ 87 return "GDB Remote protocol based debugging plug-in."; 88} 89 90void 91ProcessGDBRemote::Terminate() 92{ 93 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 94} 95 96 97Process* 98ProcessGDBRemote::CreateInstance (Target &target, Listener &listener) 99{ 100 return new ProcessGDBRemote (target, listener); 101} 102 103bool 104ProcessGDBRemote::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 return false; 111} 112 113//---------------------------------------------------------------------- 114// ProcessGDBRemote constructor 115//---------------------------------------------------------------------- 116ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) : 117 Process (target, listener), 118 m_dynamic_loader_ap (), 119 m_byte_order (eByteOrderHost), 120 m_flags (0), 121 m_stdio_communication ("gdb-remote.stdio"), 122 m_stdio_mutex (Mutex::eMutexTypeRecursive), 123 m_stdout_data (), 124 m_arch_spec (), 125 m_gdb_comm(), 126 m_debugserver_pid (LLDB_INVALID_PROCESS_ID), 127 m_debugserver_monitor (0), 128 m_register_info (), 129 m_curr_tid (LLDB_INVALID_THREAD_ID), 130 m_curr_tid_run (LLDB_INVALID_THREAD_ID), 131 m_async_broadcaster ("lldb.process.gdb-remote.async-broadcaster"), 132 m_async_thread (LLDB_INVALID_HOST_THREAD), 133 m_z0_supported (1), 134 m_continue_packet(), 135 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS), 136 m_libunwind_target_type (UNW_TARGET_UNSPECIFIED), 137 m_libunwind_addr_space (NULL), 138 m_waiting_for_attach (false), 139 m_packet_timeout (1), 140 m_max_memory_size (512) 141{ 142} 143 144//---------------------------------------------------------------------- 145// Destructor 146//---------------------------------------------------------------------- 147ProcessGDBRemote::~ProcessGDBRemote() 148{ 149 // m_mach_process.UnregisterNotificationCallbacks (this); 150 Clear(); 151} 152 153//---------------------------------------------------------------------- 154// PluginInterface 155//---------------------------------------------------------------------- 156const char * 157ProcessGDBRemote::GetPluginName() 158{ 159 return "Process debugging plug-in that uses the GDB remote protocol"; 160} 161 162const char * 163ProcessGDBRemote::GetShortPluginName() 164{ 165 return GetPluginNameStatic(); 166} 167 168uint32_t 169ProcessGDBRemote::GetPluginVersion() 170{ 171 return 1; 172} 173 174void 175ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm) 176{ 177 strm->Printf("TODO: fill this in\n"); 178} 179 180Error 181ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm) 182{ 183 Error error; 184 error.SetErrorString("No plug-in commands are currently supported."); 185 return error; 186} 187 188Log * 189ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command) 190{ 191 return NULL; 192} 193 194void 195ProcessGDBRemote::BuildDynamicRegisterInfo () 196{ 197 char register_info_command[64]; 198 m_register_info.Clear(); 199 StringExtractorGDBRemote::Type packet_type = StringExtractorGDBRemote::eResponse; 200 uint32_t reg_offset = 0; 201 uint32_t reg_num = 0; 202 for (; packet_type == StringExtractorGDBRemote::eResponse; ++reg_num) 203 { 204 ::snprintf (register_info_command, sizeof(register_info_command), "qRegisterInfo%x", reg_num); 205 StringExtractorGDBRemote response; 206 if (m_gdb_comm.SendPacketAndWaitForResponse(register_info_command, response, 2, false)) 207 { 208 packet_type = response.GetType(); 209 if (packet_type == StringExtractorGDBRemote::eResponse) 210 { 211 std::string name; 212 std::string value; 213 ConstString reg_name; 214 ConstString alt_name; 215 ConstString set_name; 216 RegisterInfo reg_info = { NULL, // Name 217 NULL, // Alt name 218 0, // byte size 219 reg_offset, // offset 220 eEncodingUint, // encoding 221 eFormatHex, // formate 222 reg_num, // native register number 223 { 224 LLDB_INVALID_REGNUM, // GCC reg num 225 LLDB_INVALID_REGNUM, // DWARF reg num 226 LLDB_INVALID_REGNUM, // generic reg num 227 reg_num // GDB reg num 228 } 229 }; 230 231 while (response.GetNameColonValue(name, value)) 232 { 233 if (name.compare("name") == 0) 234 { 235 reg_name.SetCString(value.c_str()); 236 } 237 else if (name.compare("alt-name") == 0) 238 { 239 alt_name.SetCString(value.c_str()); 240 } 241 else if (name.compare("bitsize") == 0) 242 { 243 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT; 244 } 245 else if (name.compare("offset") == 0) 246 { 247 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0); 248 if (reg_offset != offset) 249 { 250 reg_offset = offset; 251 } 252 } 253 else if (name.compare("encoding") == 0) 254 { 255 if (value.compare("uint") == 0) 256 reg_info.encoding = eEncodingUint; 257 else if (value.compare("sint") == 0) 258 reg_info.encoding = eEncodingSint; 259 else if (value.compare("ieee754") == 0) 260 reg_info.encoding = eEncodingIEEE754; 261 else if (value.compare("vector") == 0) 262 reg_info.encoding = eEncodingVector; 263 } 264 else if (name.compare("format") == 0) 265 { 266 if (value.compare("binary") == 0) 267 reg_info.format = eFormatBinary; 268 else if (value.compare("decimal") == 0) 269 reg_info.format = eFormatDecimal; 270 else if (value.compare("hex") == 0) 271 reg_info.format = eFormatHex; 272 else if (value.compare("float") == 0) 273 reg_info.format = eFormatFloat; 274 else if (value.compare("vector-sint8") == 0) 275 reg_info.format = eFormatVectorOfSInt8; 276 else if (value.compare("vector-uint8") == 0) 277 reg_info.format = eFormatVectorOfUInt8; 278 else if (value.compare("vector-sint16") == 0) 279 reg_info.format = eFormatVectorOfSInt16; 280 else if (value.compare("vector-uint16") == 0) 281 reg_info.format = eFormatVectorOfUInt16; 282 else if (value.compare("vector-sint32") == 0) 283 reg_info.format = eFormatVectorOfSInt32; 284 else if (value.compare("vector-uint32") == 0) 285 reg_info.format = eFormatVectorOfUInt32; 286 else if (value.compare("vector-float32") == 0) 287 reg_info.format = eFormatVectorOfFloat32; 288 else if (value.compare("vector-uint128") == 0) 289 reg_info.format = eFormatVectorOfUInt128; 290 } 291 else if (name.compare("set") == 0) 292 { 293 set_name.SetCString(value.c_str()); 294 } 295 else if (name.compare("gcc") == 0) 296 { 297 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 298 } 299 else if (name.compare("dwarf") == 0) 300 { 301 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 302 } 303 else if (name.compare("generic") == 0) 304 { 305 if (value.compare("pc") == 0) 306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; 307 else if (value.compare("sp") == 0) 308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP; 309 else if (value.compare("fp") == 0) 310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP; 311 else if (value.compare("ra") == 0) 312 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA; 313 else if (value.compare("flags") == 0) 314 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS; 315 } 316 } 317 318 reg_info.byte_offset = reg_offset; 319 assert (reg_info.byte_size != 0); 320 reg_offset += reg_info.byte_size; 321 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 322 } 323 } 324 else 325 { 326 packet_type = StringExtractorGDBRemote::eError; 327 } 328 } 329 330 if (reg_num == 0) 331 { 332 // We didn't get anything. See if we are debugging ARM and fill with 333 // a hard coded register set until we can get an updated debugserver 334 // down on the devices. 335 ArchSpec arm_arch ("arm"); 336 if (GetTarget().GetArchitecture() == arm_arch) 337 m_register_info.HardcodeARMRegisters(); 338 } 339 m_register_info.Finalize (); 340} 341 342Error 343ProcessGDBRemote::WillLaunch (Module* module) 344{ 345 return WillLaunchOrAttach (); 346} 347 348Error 349ProcessGDBRemote::WillAttach (lldb::pid_t pid) 350{ 351 return WillLaunchOrAttach (); 352} 353 354Error 355ProcessGDBRemote::WillAttach (const char *process_name, bool wait_for_launch) 356{ 357 return WillLaunchOrAttach (); 358} 359 360Error 361ProcessGDBRemote::WillLaunchOrAttach () 362{ 363 Error error; 364 // TODO: this is hardcoded for macosx right now. We need this to be more dynamic 365 m_dynamic_loader_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.macosx-dyld")); 366 367 if (m_dynamic_loader_ap.get() == NULL) 368 error.SetErrorString("unable to find the dynamic loader named 'dynamic-loader.macosx-dyld'"); 369 m_stdio_communication.Clear (); 370 371 return error; 372} 373 374//---------------------------------------------------------------------- 375// Process Control 376//---------------------------------------------------------------------- 377Error 378ProcessGDBRemote::DoLaunch 379( 380 Module* module, 381 char const *argv[], 382 char const *envp[], 383 const char *stdin_path, 384 const char *stdout_path, 385 const char *stderr_path 386) 387{ 388 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 389 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 390 // ::LogSetLogFile ("/dev/stdout"); 391 Error error; 392 393 ObjectFile * object_file = module->GetObjectFile(); 394 if (object_file) 395 { 396 ArchSpec inferior_arch(module->GetArchitecture()); 397 char host_port[128]; 398 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 399 400 bool start_debugserver_with_inferior_args = false; 401 if (start_debugserver_with_inferior_args) 402 { 403 // We want to launch debugserver with the inferior program and its 404 // arguments on the command line. We should only do this if we 405 // the GDB server we are talking to doesn't support the 'A' packet. 406 error = StartDebugserverProcess (host_port, 407 argv, 408 envp, 409 NULL, //stdin_path, 410 LLDB_INVALID_PROCESS_ID, 411 NULL, false, 412 inferior_arch); 413 if (error.Fail()) 414 return error; 415 416 error = ConnectToDebugserver (host_port); 417 if (error.Success()) 418 { 419 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout)); 420 } 421 } 422 else 423 { 424 error = StartDebugserverProcess (host_port, 425 NULL, 426 NULL, 427 NULL, //stdin_path, 428 LLDB_INVALID_PROCESS_ID, 429 NULL, false, 430 inferior_arch); 431 if (error.Fail()) 432 return error; 433 434 error = ConnectToDebugserver (host_port); 435 if (error.Success()) 436 { 437 // Send the environment and the program + arguments after we connect 438 if (envp) 439 { 440 const char *env_entry; 441 for (int i=0; (env_entry = envp[i]); ++i) 442 { 443 if (m_gdb_comm.SendEnvironmentPacket(env_entry, m_packet_timeout) != 0) 444 break; 445 } 446 } 447 448 const uint32_t arg_timeout_seconds = 10; 449 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (argv, arg_timeout_seconds); 450 if (arg_packet_err == 0) 451 { 452 std::string error_str; 453 if (m_gdb_comm.GetLaunchSuccess (m_packet_timeout, error_str)) 454 { 455 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout)); 456 } 457 else 458 { 459 error.SetErrorString (error_str.c_str()); 460 } 461 } 462 else 463 { 464 error.SetErrorStringWithFormat("'A' packet returned an error: %i.\n", arg_packet_err); 465 } 466 467 SetID (m_gdb_comm.GetCurrentProcessID (m_packet_timeout)); 468 } 469 } 470 471 if (GetID() == LLDB_INVALID_PROCESS_ID) 472 { 473 KillDebugserverProcess (); 474 return error; 475 } 476 477 StringExtractorGDBRemote response; 478 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, response, m_packet_timeout, false)) 479 SetPrivateState (SetThreadStopInfo (response)); 480 481 } 482 else 483 { 484 // Set our user ID to an invalid process ID. 485 SetID(LLDB_INVALID_PROCESS_ID); 486 error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString()); 487 } 488 489 // Return the process ID we have 490 return error; 491} 492 493 494Error 495ProcessGDBRemote::ConnectToDebugserver (const char *host_port) 496{ 497 Error error; 498 // Sleep and wait a bit for debugserver to start to listen... 499 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor()); 500 if (conn_ap.get()) 501 { 502 std::string connect_url("connect://"); 503 connect_url.append (host_port); 504 const uint32_t max_retry_count = 50; 505 uint32_t retry_count = 0; 506 while (!m_gdb_comm.IsConnected()) 507 { 508 if (conn_ap->Connect(connect_url.c_str(), &error) == eConnectionStatusSuccess) 509 { 510 m_gdb_comm.SetConnection (conn_ap.release()); 511 break; 512 } 513 retry_count++; 514 515 if (retry_count >= max_retry_count) 516 break; 517 518 usleep (100000); 519 } 520 } 521 522 if (!m_gdb_comm.IsConnected()) 523 { 524 if (error.Success()) 525 error.SetErrorString("not connected to remote gdb server"); 526 return error; 527 } 528 529 m_gdb_comm.SetAckMode (true); 530 if (m_gdb_comm.StartReadThread(&error)) 531 { 532 // Send an initial ack 533 m_gdb_comm.SendAck('+'); 534 535 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 536 m_debugserver_monitor = Host::StartMonitoringChildProcess (MonitorDebugserverProcess, 537 (void*)(intptr_t)GetID(), // Pass the inferior pid in the thread argument (which is a void *) 538 m_debugserver_pid, 539 false); 540 541 StringExtractorGDBRemote response; 542 if (m_gdb_comm.SendPacketAndWaitForResponse("QStartNoAckMode", response, 1, false)) 543 { 544 if (response.IsOKPacket()) 545 m_gdb_comm.SetAckMode (false); 546 } 547 548 BuildDynamicRegisterInfo (); 549 } 550 return error; 551} 552 553void 554ProcessGDBRemote::DidLaunchOrAttach () 555{ 556 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::DidLaunch()"); 557 if (GetID() == LLDB_INVALID_PROCESS_ID) 558 { 559 m_dynamic_loader_ap.reset(); 560 } 561 else 562 { 563 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; 564 565 Module * exe_module = GetTarget().GetExecutableModule ().get(); 566 assert(exe_module); 567 568 m_arch_spec = exe_module->GetArchitecture(); 569 570 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 571 assert(exe_objfile); 572 573 m_byte_order = exe_objfile->GetByteOrder(); 574 assert (m_byte_order != eByteOrderInvalid); 575 576 StreamString strm; 577 578 ArchSpec inferior_arch; 579 // See if the GDB server supports the qHostInfo information 580 const char *vendor = m_gdb_comm.GetVendorString().AsCString(); 581 const char *os_type = m_gdb_comm.GetOSString().AsCString(); 582 583 if (m_arch_spec.IsValid() && m_arch_spec == ArchSpec ("arm")) 584 { 585 // For ARM we can't trust the arch of the process as it could 586 // have an armv6 object file, but be running on armv7 kernel. 587 inferior_arch = m_gdb_comm.GetHostArchitecture(); 588 } 589 590 if (!inferior_arch.IsValid()) 591 inferior_arch = m_arch_spec; 592 593 if (vendor == NULL) 594 vendor = Host::GetVendorString().AsCString("apple"); 595 596 if (os_type == NULL) 597 os_type = Host::GetOSString().AsCString("darwin"); 598 599 strm.Printf ("%s-%s-%s", inferior_arch.AsCString(), vendor, os_type); 600 601 std::transform (strm.GetString().begin(), 602 strm.GetString().end(), 603 strm.GetString().begin(), 604 ::tolower); 605 606 m_target_triple.SetCString(strm.GetString().c_str()); 607 } 608} 609 610void 611ProcessGDBRemote::DidLaunch () 612{ 613 DidLaunchOrAttach (); 614 if (m_dynamic_loader_ap.get()) 615 m_dynamic_loader_ap->DidLaunch(); 616} 617 618Error 619ProcessGDBRemote::DoAttach (pid_t attach_pid) 620{ 621 Error error; 622 // Clear out and clean up from any current state 623 Clear(); 624 // HACK: require arch be set correctly at the target level until we can 625 // figure out a good way to determine the arch of what we are attaching to 626 m_arch_spec = m_target.GetArchitecture(); 627 628 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 629 if (attach_pid != LLDB_INVALID_PROCESS_ID) 630 { 631 SetPrivateState (eStateAttaching); 632 char host_port[128]; 633 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 634 error = StartDebugserverProcess (host_port, 635 NULL, 636 NULL, 637 NULL, 638 LLDB_INVALID_PROCESS_ID, 639 NULL, false, 640 m_arch_spec); 641 642 if (error.Fail()) 643 { 644 const char *error_string = error.AsCString(); 645 if (error_string == NULL) 646 error_string = "unable to launch " DEBUGSERVER_BASENAME; 647 648 SetExitStatus (-1, error_string); 649 } 650 else 651 { 652 error = ConnectToDebugserver (host_port); 653 if (error.Success()) 654 { 655 char packet[64]; 656 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%x", attach_pid); 657 StringExtractorGDBRemote response; 658 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this, 659 packet, 660 packet_len, 661 response); 662 switch (stop_state) 663 { 664 case eStateStopped: 665 case eStateCrashed: 666 case eStateSuspended: 667 SetID (attach_pid); 668 m_last_stop_packet = response; 669 m_last_stop_packet.SetFilePos (0); 670 SetPrivateState (stop_state); 671 break; 672 673 case eStateExited: 674 m_last_stop_packet = response; 675 m_last_stop_packet.SetFilePos (0); 676 response.SetFilePos(1); 677 SetExitStatus(response.GetHexU8(), NULL); 678 break; 679 680 default: 681 SetExitStatus(-1, "unable to attach to process"); 682 break; 683 } 684 685 } 686 } 687 } 688 689 lldb::pid_t pid = GetID(); 690 if (pid == LLDB_INVALID_PROCESS_ID) 691 { 692 KillDebugserverProcess(); 693 } 694 return error; 695} 696 697size_t 698ProcessGDBRemote::AttachInputReaderCallback 699( 700 void *baton, 701 InputReader *reader, 702 lldb::InputReaderAction notification, 703 const char *bytes, 704 size_t bytes_len 705) 706{ 707 if (notification == eInputReaderGotToken) 708 { 709 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton; 710 if (gdb_process->m_waiting_for_attach) 711 gdb_process->m_waiting_for_attach = false; 712 reader->SetIsDone(true); 713 return 1; 714 } 715 return 0; 716} 717 718Error 719ProcessGDBRemote::DoAttach (const char *process_name, bool wait_for_launch) 720{ 721 Error error; 722 // Clear out and clean up from any current state 723 Clear(); 724 // HACK: require arch be set correctly at the target level until we can 725 // figure out a good way to determine the arch of what we are attaching to 726 m_arch_spec = m_target.GetArchitecture(); 727 728 //Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 729 if (process_name && process_name[0]) 730 { 731 732 SetPrivateState (eStateAttaching); 733 char host_port[128]; 734 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 735 error = StartDebugserverProcess (host_port, 736 NULL, 737 NULL, 738 NULL, 739 LLDB_INVALID_PROCESS_ID, 740 NULL, false, 741 m_arch_spec); 742 if (error.Fail()) 743 { 744 const char *error_string = error.AsCString(); 745 if (error_string == NULL) 746 error_string = "unable to launch " DEBUGSERVER_BASENAME; 747 748 SetExitStatus (-1, error_string); 749 } 750 else 751 { 752 error = ConnectToDebugserver (host_port); 753 if (error.Success()) 754 { 755 StreamString packet; 756 757 packet.PutCString("vAttach"); 758 if (wait_for_launch) 759 packet.PutCString("Wait"); 760 packet.PutChar(';'); 761 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost); 762 StringExtractorGDBRemote response; 763 StateType stop_state = m_gdb_comm.SendContinuePacketAndWaitForResponse (this, 764 packet.GetData(), 765 packet.GetSize(), 766 response); 767 switch (stop_state) 768 { 769 case eStateStopped: 770 case eStateCrashed: 771 case eStateSuspended: 772 SetID (m_gdb_comm.GetCurrentProcessID(m_packet_timeout)); 773 m_last_stop_packet = response; 774 m_last_stop_packet.SetFilePos (0); 775 SetPrivateState (stop_state); 776 break; 777 778 case eStateExited: 779 m_last_stop_packet = response; 780 m_last_stop_packet.SetFilePos (0); 781 response.SetFilePos(1); 782 SetExitStatus(response.GetHexU8(), NULL); 783 break; 784 785 default: 786 SetExitStatus(-1, "unable to attach to process"); 787 break; 788 } 789 } 790 } 791 } 792 793 lldb::pid_t pid = GetID(); 794 if (pid == LLDB_INVALID_PROCESS_ID) 795 { 796 KillDebugserverProcess(); 797 } 798 return error; 799} 800 801// 802// if (wait_for_launch) 803// { 804// InputReaderSP reader_sp (new InputReader()); 805// StreamString instructions; 806// instructions.Printf("Hit any key to cancel waiting for '%s' to launch...", process_name); 807// error = reader_sp->Initialize (AttachInputReaderCallback, // callback 808// this, // baton 809// eInputReaderGranularityByte, 810// NULL, // End token 811// false); 812// 813// StringExtractorGDBRemote response; 814// m_waiting_for_attach = true; 815// FILE *reader_out_fh = reader_sp->GetOutputFileHandle(); 816// while (m_waiting_for_attach) 817// { 818// // Wait for one second for the stop reply packet 819// if (m_gdb_comm.WaitForPacket(response, 1)) 820// { 821// // Got some sort of packet, see if it is the stop reply packet? 822// char ch = response.GetChar(0); 823// if (ch == 'T') 824// { 825// m_waiting_for_attach = false; 826// } 827// } 828// else 829// { 830// // Put a period character every second 831// fputc('.', reader_out_fh); 832// } 833// } 834// } 835// } 836// return GetID(); 837//} 838 839void 840ProcessGDBRemote::DidAttach () 841{ 842 DidLaunchOrAttach (); 843 if (m_dynamic_loader_ap.get()) 844 m_dynamic_loader_ap->DidAttach(); 845} 846 847Error 848ProcessGDBRemote::WillResume () 849{ 850 m_continue_packet.Clear(); 851 // Start the continue packet we will use to run the target. Each thread 852 // will append what it is supposed to be doing to this packet when the 853 // ThreadList::WillResume() is called. If a thread it supposed 854 // to stay stopped, then don't append anything to this string. 855 m_continue_packet.Printf("vCont"); 856 return Error(); 857} 858 859Error 860ProcessGDBRemote::DoResume () 861{ 862 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::Resume()"); 863 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (m_continue_packet.GetData(), m_continue_packet.GetSize())); 864 return Error(); 865} 866 867size_t 868ProcessGDBRemote::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) 869{ 870 const uint8_t *trap_opcode = NULL; 871 uint32_t trap_opcode_size = 0; 872 873 static const uint8_t g_arm_breakpoint_opcode[] = { 0xFE, 0xDE, 0xFF, 0xE7 }; 874 //static const uint8_t g_thumb_breakpooint_opcode[] = { 0xFE, 0xDE }; 875 static const uint8_t g_ppc_breakpoint_opcode[] = { 0x7F, 0xC0, 0x00, 0x08 }; 876 static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC }; 877 878 ArchSpec::CPU arch_cpu = m_arch_spec.GetGenericCPUType(); 879 switch (arch_cpu) 880 { 881 case ArchSpec::eCPU_i386: 882 case ArchSpec::eCPU_x86_64: 883 trap_opcode = g_i386_breakpoint_opcode; 884 trap_opcode_size = sizeof(g_i386_breakpoint_opcode); 885 break; 886 887 case ArchSpec::eCPU_arm: 888 // TODO: fill this in for ARM. We need to dig up the symbol for 889 // the address in the breakpoint locaiton and figure out if it is 890 // an ARM or Thumb breakpoint. 891 trap_opcode = g_arm_breakpoint_opcode; 892 trap_opcode_size = sizeof(g_arm_breakpoint_opcode); 893 break; 894 895 case ArchSpec::eCPU_ppc: 896 case ArchSpec::eCPU_ppc64: 897 trap_opcode = g_ppc_breakpoint_opcode; 898 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode); 899 break; 900 901 default: 902 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()"); 903 break; 904 } 905 906 if (trap_opcode && trap_opcode_size) 907 { 908 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size)) 909 return trap_opcode_size; 910 } 911 return 0; 912} 913 914uint32_t 915ProcessGDBRemote::UpdateThreadListIfNeeded () 916{ 917 // locker will keep a mutex locked until it goes out of scope 918 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD); 919 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE)) 920 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID()); 921 922 const uint32_t stop_id = GetStopID(); 923 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 924 { 925 // Update the thread list's stop id immediately so we don't recurse into this function. 926 ThreadList curr_thread_list (this); 927 curr_thread_list.SetStopID(stop_id); 928 929 Error err; 930 StringExtractorGDBRemote response; 931 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false); 932 response.IsNormalPacket(); 933 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false)) 934 { 935 char ch = response.GetChar(); 936 if (ch == 'l') 937 break; 938 if (ch == 'm') 939 { 940 do 941 { 942 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 943 944 if (tid != LLDB_INVALID_THREAD_ID) 945 { 946 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false)); 947 if (thread_sp) 948 thread_sp->GetRegisterContext()->Invalidate(); 949 else 950 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 951 curr_thread_list.AddThread(thread_sp); 952 } 953 954 ch = response.GetChar(); 955 } while (ch == ','); 956 } 957 } 958 959 m_thread_list = curr_thread_list; 960 961 SetThreadStopInfo (m_last_stop_packet); 962 } 963 return GetThreadList().GetSize(false); 964} 965 966 967StateType 968ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 969{ 970 const char stop_type = stop_packet.GetChar(); 971 switch (stop_type) 972 { 973 case 'T': 974 case 'S': 975 { 976 // Stop with signal and thread info 977 const uint8_t signo = stop_packet.GetHexU8(); 978 std::string name; 979 std::string value; 980 std::string thread_name; 981 uint32_t exc_type = 0; 982 std::vector<uint64_t> exc_data; 983 uint32_t tid = LLDB_INVALID_THREAD_ID; 984 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 985 uint32_t exc_data_count = 0; 986 while (stop_packet.GetNameColonValue(name, value)) 987 { 988 if (name.compare("metype") == 0) 989 { 990 // exception type in big endian hex 991 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 992 } 993 else if (name.compare("mecount") == 0) 994 { 995 // exception count in big endian hex 996 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16); 997 } 998 else if (name.compare("medata") == 0) 999 { 1000 // exception data in big endian hex 1001 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1002 } 1003 else if (name.compare("thread") == 0) 1004 { 1005 // thread in big endian hex 1006 tid = Args::StringToUInt32 (value.c_str(), 0, 16); 1007 } 1008 else if (name.compare("name") == 0) 1009 { 1010 thread_name.swap (value); 1011 } 1012 else if (name.compare("dispatchqaddr") == 0) 1013 { 1014 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1015 } 1016 } 1017 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false)); 1018 1019 if (thread_sp) 1020 { 1021 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1022 1023 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1024 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL); 1025 Thread::StopInfo& stop_info = gdb_thread->GetStopInfoRef(); 1026 gdb_thread->SetStopInfoStopID (GetStopID()); 1027 if (exc_type != 0) 1028 { 1029 if (exc_type == EXC_SOFTWARE && exc_data.size() == 2 && exc_data[0] == EXC_SOFT_SIGNAL) 1030 { 1031 stop_info.SetStopReasonWithSignal(exc_data[1]); 1032 } 1033#if defined (MACH_EXC_DATA0_SOFTWARE_BREAKPOINT) 1034 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_SOFTWARE_BREAKPOINT) 1035 { 1036 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1037 user_id_t break_id = GetBreakpointSiteList().FindIDByAddress(pc); 1038 if (break_id == LLDB_INVALID_BREAK_ID) 1039 { 1040 //log->Printf("got EXC_BREAKPOINT at 0x%llx but didn't find a breakpoint site.\n", pc); 1041 stop_info.SetStopReasonWithException(exc_type, exc_data.size()); 1042 for (uint32_t i=0; i<exc_data.size(); ++i) 1043 stop_info.SetExceptionDataAtIndex(i, exc_data[i]); 1044 } 1045 else 1046 { 1047 stop_info.Clear (); 1048 stop_info.SetStopReasonWithBreakpointSiteID (break_id); 1049 } 1050 } 1051#endif 1052#if defined (MACH_EXC_DATA0_TRACE) 1053 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_TRACE) 1054 { 1055 stop_info.SetStopReasonToTrace (); 1056 } 1057#endif 1058 else 1059 { 1060 stop_info.SetStopReasonWithException(exc_type, exc_data.size()); 1061 for (uint32_t i=0; i<exc_data.size(); ++i) 1062 stop_info.SetExceptionDataAtIndex(i, exc_data[i]); 1063 } 1064 } 1065 else if (signo) 1066 { 1067 stop_info.SetStopReasonWithSignal(signo); 1068 } 1069 else 1070 { 1071 stop_info.SetStopReasonToNone(); 1072 } 1073 } 1074 return eStateStopped; 1075 } 1076 break; 1077 1078 case 'W': 1079 // process exited 1080 return eStateExited; 1081 1082 default: 1083 break; 1084 } 1085 return eStateInvalid; 1086} 1087 1088void 1089ProcessGDBRemote::RefreshStateAfterStop () 1090{ 1091 // We must be attaching if we don't already have a valid architecture 1092 if (!m_arch_spec.IsValid()) 1093 { 1094 Module *exe_module = GetTarget().GetExecutableModule().get(); 1095 if (exe_module) 1096 m_arch_spec = exe_module->GetArchitecture(); 1097 } 1098 // Let all threads recover from stopping and do any clean up based 1099 // on the previous thread state (if any). 1100 m_thread_list.RefreshStateAfterStop(); 1101 1102 // Discover new threads: 1103 UpdateThreadListIfNeeded (); 1104} 1105 1106Error 1107ProcessGDBRemote::DoHalt () 1108{ 1109 Error error; 1110 if (m_gdb_comm.IsRunning()) 1111 { 1112 bool timed_out = false; 1113 if (!m_gdb_comm.SendInterrupt (2, &timed_out)) 1114 { 1115 if (timed_out) 1116 error.SetErrorString("timed out sending interrupt packet"); 1117 else 1118 error.SetErrorString("unknown error sending interrupt packet"); 1119 } 1120 } 1121 return error; 1122} 1123 1124Error 1125ProcessGDBRemote::WillDetach () 1126{ 1127 Error error; 1128 const StateType state = m_private_state.GetValue(); 1129 1130 if (IsRunning(state)) 1131 error.SetErrorString("Process must be stopped in order to detach."); 1132 1133 return error; 1134} 1135 1136 1137Error 1138ProcessGDBRemote::DoDestroy () 1139{ 1140 Error error; 1141 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1142 if (log) 1143 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1144 1145 // Interrupt if our inferior is running... 1146 m_gdb_comm.SendInterrupt (1); 1147 DisableAllBreakpointSites (); 1148 SetExitStatus(-1, "process killed"); 1149 1150 StringExtractorGDBRemote response; 1151 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false)) 1152 { 1153 if (log) 1154 { 1155 if (response.IsOKPacket()) 1156 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful"); 1157 else 1158 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str()); 1159 } 1160 } 1161 1162 StopAsyncThread (); 1163 m_gdb_comm.StopReadThread(); 1164 KillDebugserverProcess (); 1165 return error; 1166} 1167 1168ByteOrder 1169ProcessGDBRemote::GetByteOrder () const 1170{ 1171 return m_byte_order; 1172} 1173 1174//------------------------------------------------------------------ 1175// Process Queries 1176//------------------------------------------------------------------ 1177 1178bool 1179ProcessGDBRemote::IsAlive () 1180{ 1181 return m_gdb_comm.IsConnected(); 1182} 1183 1184addr_t 1185ProcessGDBRemote::GetImageInfoAddress() 1186{ 1187 if (!m_gdb_comm.IsRunning()) 1188 { 1189 StringExtractorGDBRemote response; 1190 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false)) 1191 { 1192 if (response.IsNormalPacket()) 1193 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1194 } 1195 } 1196 return LLDB_INVALID_ADDRESS; 1197} 1198 1199DynamicLoader * 1200ProcessGDBRemote::GetDynamicLoader() 1201{ 1202 return m_dynamic_loader_ap.get(); 1203} 1204 1205//------------------------------------------------------------------ 1206// Process Memory 1207//------------------------------------------------------------------ 1208size_t 1209ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1210{ 1211 if (size > m_max_memory_size) 1212 { 1213 // Keep memory read sizes down to a sane limit. This function will be 1214 // called multiple times in order to complete the task by 1215 // lldb_private::Process so it is ok to do this. 1216 size = m_max_memory_size; 1217 } 1218 1219 char packet[64]; 1220 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1221 assert (packet_len + 1 < sizeof(packet)); 1222 StringExtractorGDBRemote response; 1223 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1224 { 1225 if (response.IsNormalPacket()) 1226 { 1227 error.Clear(); 1228 return response.GetHexBytes(buf, size, '\xdd'); 1229 } 1230 else if (response.IsErrorPacket()) 1231 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1232 else if (response.IsUnsupportedPacket()) 1233 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1234 else 1235 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1236 } 1237 else 1238 { 1239 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1240 } 1241 return 0; 1242} 1243 1244size_t 1245ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1246{ 1247 StreamString packet; 1248 packet.Printf("M%llx,%zx:", addr, size); 1249 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost); 1250 StringExtractorGDBRemote response; 1251 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true)) 1252 { 1253 if (response.IsOKPacket()) 1254 { 1255 error.Clear(); 1256 return size; 1257 } 1258 else if (response.IsErrorPacket()) 1259 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1260 else if (response.IsUnsupportedPacket()) 1261 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1262 else 1263 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1264 } 1265 else 1266 { 1267 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1268 } 1269 return 0; 1270} 1271 1272lldb::addr_t 1273ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1274{ 1275 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout); 1276 if (allocated_addr == LLDB_INVALID_ADDRESS) 1277 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions); 1278 else 1279 error.Clear(); 1280 return allocated_addr; 1281} 1282 1283Error 1284ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 1285{ 1286 Error error; 1287 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout)) 1288 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 1289 return error; 1290} 1291 1292 1293//------------------------------------------------------------------ 1294// Process STDIO 1295//------------------------------------------------------------------ 1296 1297size_t 1298ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error) 1299{ 1300 Mutex::Locker locker(m_stdio_mutex); 1301 size_t bytes_available = m_stdout_data.size(); 1302 if (bytes_available > 0) 1303 { 1304 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size); 1305 if (bytes_available > buf_size) 1306 { 1307 memcpy(buf, m_stdout_data.data(), buf_size); 1308 m_stdout_data.erase(0, buf_size); 1309 bytes_available = buf_size; 1310 } 1311 else 1312 { 1313 memcpy(buf, m_stdout_data.data(), bytes_available); 1314 m_stdout_data.clear(); 1315 1316 //ResetEventBits(eBroadcastBitSTDOUT); 1317 } 1318 } 1319 return bytes_available; 1320} 1321 1322size_t 1323ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error) 1324{ 1325 // Can we get STDERR through the remote protocol? 1326 return 0; 1327} 1328 1329size_t 1330ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 1331{ 1332 if (m_stdio_communication.IsConnected()) 1333 { 1334 ConnectionStatus status; 1335 m_stdio_communication.Write(src, src_len, status, NULL); 1336 } 1337 return 0; 1338} 1339 1340Error 1341ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 1342{ 1343 Error error; 1344 assert (bp_site != NULL); 1345 1346 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS); 1347 user_id_t site_id = bp_site->GetID(); 1348 const addr_t addr = bp_site->GetLoadAddress(); 1349 if (log) 1350 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr); 1351 1352 if (bp_site->IsEnabled()) 1353 { 1354 if (log) 1355 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 1356 return error; 1357 } 1358 else 1359 { 1360 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1361 1362 if (bp_site->HardwarePreferred()) 1363 { 1364 // Try and set hardware breakpoint, and if that fails, fall through 1365 // and set a software breakpoint? 1366 } 1367 1368 if (m_z0_supported) 1369 { 1370 char packet[64]; 1371 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size); 1372 assert (packet_len + 1 < sizeof(packet)); 1373 StringExtractorGDBRemote response; 1374 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1375 { 1376 if (response.IsUnsupportedPacket()) 1377 { 1378 // Disable z packet support and try again 1379 m_z0_supported = 0; 1380 return EnableBreakpoint (bp_site); 1381 } 1382 else if (response.IsOKPacket()) 1383 { 1384 bp_site->SetEnabled(true); 1385 bp_site->SetType (BreakpointSite::eExternal); 1386 return error; 1387 } 1388 else 1389 { 1390 uint8_t error_byte = response.GetError(); 1391 if (error_byte) 1392 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1393 } 1394 } 1395 } 1396 else 1397 { 1398 return EnableSoftwareBreakpoint (bp_site); 1399 } 1400 } 1401 1402 if (log) 1403 { 1404 const char *err_string = error.AsCString(); 1405 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 1406 bp_site->GetLoadAddress(), 1407 err_string ? err_string : "NULL"); 1408 } 1409 // We shouldn't reach here on a successful breakpoint enable... 1410 if (error.Success()) 1411 error.SetErrorToGenericError(); 1412 return error; 1413} 1414 1415Error 1416ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 1417{ 1418 Error error; 1419 assert (bp_site != NULL); 1420 addr_t addr = bp_site->GetLoadAddress(); 1421 user_id_t site_id = bp_site->GetID(); 1422 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS); 1423 if (log) 1424 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr); 1425 1426 if (bp_site->IsEnabled()) 1427 { 1428 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1429 1430 if (bp_site->IsHardware()) 1431 { 1432 // TODO: disable hardware breakpoint... 1433 } 1434 else 1435 { 1436 if (m_z0_supported) 1437 { 1438 char packet[64]; 1439 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size); 1440 assert (packet_len + 1 < sizeof(packet)); 1441 StringExtractorGDBRemote response; 1442 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1443 { 1444 if (response.IsUnsupportedPacket()) 1445 { 1446 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported."); 1447 } 1448 else if (response.IsOKPacket()) 1449 { 1450 if (log) 1451 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr); 1452 bp_site->SetEnabled(false); 1453 return error; 1454 } 1455 else 1456 { 1457 uint8_t error_byte = response.GetError(); 1458 if (error_byte) 1459 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1460 } 1461 } 1462 } 1463 else 1464 { 1465 return DisableSoftwareBreakpoint (bp_site); 1466 } 1467 } 1468 } 1469 else 1470 { 1471 if (log) 1472 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 1473 return error; 1474 } 1475 1476 if (error.Success()) 1477 error.SetErrorToGenericError(); 1478 return error; 1479} 1480 1481Error 1482ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp) 1483{ 1484 Error error; 1485 if (wp) 1486 { 1487 user_id_t watchID = wp->GetID(); 1488 addr_t addr = wp->GetLoadAddress(); 1489 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS); 1490 if (log) 1491 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID); 1492 if (wp->IsEnabled()) 1493 { 1494 if (log) 1495 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 1496 return error; 1497 } 1498 else 1499 { 1500 // Pass down an appropriate z/Z packet... 1501 error.SetErrorString("watchpoints not supported"); 1502 } 1503 } 1504 else 1505 { 1506 error.SetErrorString("Watchpoint location argument was NULL."); 1507 } 1508 if (error.Success()) 1509 error.SetErrorToGenericError(); 1510 return error; 1511} 1512 1513Error 1514ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp) 1515{ 1516 Error error; 1517 if (wp) 1518 { 1519 user_id_t watchID = wp->GetID(); 1520 1521 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS); 1522 1523 addr_t addr = wp->GetLoadAddress(); 1524 if (log) 1525 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr); 1526 1527 if (wp->IsHardware()) 1528 { 1529 // Pass down an appropriate z/Z packet... 1530 error.SetErrorString("watchpoints not supported"); 1531 } 1532 // TODO: clear software watchpoints if we implement them 1533 } 1534 else 1535 { 1536 error.SetErrorString("Watchpoint location argument was NULL."); 1537 } 1538 if (error.Success()) 1539 error.SetErrorToGenericError(); 1540 return error; 1541} 1542 1543void 1544ProcessGDBRemote::Clear() 1545{ 1546 m_flags = 0; 1547 m_thread_list.Clear(); 1548 { 1549 Mutex::Locker locker(m_stdio_mutex); 1550 m_stdout_data.clear(); 1551 } 1552 DestoryLibUnwindAddressSpace(); 1553} 1554 1555Error 1556ProcessGDBRemote::DoSignal (int signo) 1557{ 1558 Error error; 1559 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1560 if (log) 1561 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 1562 1563 if (!m_gdb_comm.SendAsyncSignal (signo)) 1564 error.SetErrorStringWithFormat("failed to send signal %i", signo); 1565 return error; 1566} 1567 1568 1569Error 1570ProcessGDBRemote::DoDetach() 1571{ 1572 Error error; 1573 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1574 if (log) 1575 log->Printf ("ProcessGDBRemote::DoDetach()"); 1576 1577 // if (DoSIGSTOP (true)) 1578 // { 1579 // CloseChildFileDescriptors (); 1580 // 1581 // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP 1582 // // exception). 1583 // { 1584 // Mutex::Locker locker(m_exception_messages_mutex); 1585 // ReplyToAllExceptions(); 1586 // } 1587 // 1588 // // Shut down the exception thread and cleanup our exception remappings 1589 // Task().ShutDownExceptionThread(); 1590 // 1591 // pid_t pid = GetID(); 1592 // 1593 // // Detach from our process while we are stopped. 1594 // errno = 0; 1595 // 1596 // // Detach from our process 1597 // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0); 1598 // 1599 // error.SetErrorToErrno(); 1600 // 1601 // if (log || error.Fail()) 1602 // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid); 1603 // 1604 // // Resume our task 1605 // Task().Resume(); 1606 // 1607 // // NULL our task out as we have already retored all exception ports 1608 // Task().Clear(); 1609 // 1610 // // Clear out any notion of the process we once were 1611 // Clear(); 1612 // 1613 // SetPrivateState (eStateDetached); 1614 // return true; 1615 // } 1616 return error; 1617} 1618 1619void 1620ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 1621{ 1622 ProcessGDBRemote *process = (ProcessGDBRemote *)baton; 1623 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 1624} 1625 1626void 1627ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len) 1628{ 1629 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s); 1630 Mutex::Locker locker(m_stdio_mutex); 1631 m_stdout_data.append(s, len); 1632 1633 // FIXME: Make a real data object for this and put it out. 1634 BroadcastEventIfUnique (eBroadcastBitSTDOUT); 1635} 1636 1637 1638Error 1639ProcessGDBRemote::StartDebugserverProcess 1640( 1641 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 1642 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument 1643 char const *inferior_envp[], // Environment to pass along to the inferior program 1644 char const *stdio_path, 1645 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid 1646 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name" 1647 bool wait_for_launch, // Wait for the process named "attach_name" to launch 1648 ArchSpec& inferior_arch // The arch of the inferior that we will launch 1649) 1650{ 1651 Error error; 1652 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 1653 { 1654 // If we locate debugserver, keep that located version around 1655 static FileSpec g_debugserver_file_spec; 1656 1657 FileSpec debugserver_file_spec; 1658 char debugserver_path[PATH_MAX]; 1659 1660 // Always check to see if we have an environment override for the path 1661 // to the debugserver to use and use it if we do. 1662 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 1663 if (env_debugserver_path) 1664 debugserver_file_spec.SetFile (env_debugserver_path); 1665 else 1666 debugserver_file_spec = g_debugserver_file_spec; 1667 bool debugserver_exists = debugserver_file_spec.Exists(); 1668 if (!debugserver_exists) 1669 { 1670 // The debugserver binary is in the LLDB.framework/Resources 1671 // directory. 1672 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize)); 1673 const char *framework_dir = framework_file_spec.GetDirectory().AsCString(); 1674 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework"); 1675 1676 if (lldb_framework) 1677 { 1678 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework"); 1679 ::snprintf (debugserver_path, 1680 sizeof(debugserver_path), 1681 "%.*s/Resources/%s", 1682 len, 1683 framework_dir, 1684 DEBUGSERVER_BASENAME); 1685 debugserver_file_spec.SetFile (debugserver_path); 1686 debugserver_exists = debugserver_file_spec.Exists(); 1687 } 1688 1689 if (debugserver_exists) 1690 { 1691 g_debugserver_file_spec = debugserver_file_spec; 1692 } 1693 else 1694 { 1695 g_debugserver_file_spec.Clear(); 1696 debugserver_file_spec.Clear(); 1697 } 1698 } 1699 1700 if (debugserver_exists) 1701 { 1702 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 1703 1704 m_stdio_communication.Clear(); 1705 posix_spawnattr_t attr; 1706 1707 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 1708 1709 Error local_err; // Errors that don't affect the spawning. 1710 if (log) 1711 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString()); 1712 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX); 1713 if (error.Fail() || log) 1714 error.PutToLog(log, "::posix_spawnattr_init ( &attr )"); 1715 if (error.Fail()) 1716 return error;; 1717 1718#if !defined (__arm__) 1719 1720 // We don't need to do this for ARM, and we really shouldn't now that we 1721 // have multiple CPU subtypes and no posix_spawnattr call that allows us 1722 // to set which CPU subtype to launch... 1723 if (inferior_arch.GetType() == eArchTypeMachO) 1724 { 1725 cpu_type_t cpu = inferior_arch.GetCPUType(); 1726 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE) 1727 { 1728 size_t ocount = 0; 1729 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX); 1730 if (error.Fail() || log) 1731 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount); 1732 1733 if (error.Fail() != 0 || ocount != 1) 1734 return error; 1735 } 1736 } 1737 1738#endif 1739 1740 Args debugserver_args; 1741 char arg_cstr[PATH_MAX]; 1742 bool launch_process = true; 1743 1744 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID) 1745 launch_process = false; 1746 else if (attach_name) 1747 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0] 1748 1749 bool pass_stdio_path_to_debugserver = true; 1750 lldb_utility::PseudoTerminal pty; 1751 if (stdio_path == NULL) 1752 { 1753 pass_stdio_path_to_debugserver = false; 1754 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 1755 { 1756 struct termios stdin_termios; 1757 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0) 1758 { 1759 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing 1760 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time 1761 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios); 1762 } 1763 stdio_path = pty.GetSlaveName (NULL, 0); 1764 } 1765 } 1766 1767 // Start args with "debugserver /file/path -r --" 1768 debugserver_args.AppendArgument(debugserver_path); 1769 debugserver_args.AppendArgument(debugserver_url); 1770 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers 1771 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so 1772 // signals generated by special terminal key 1773 // sequences (^C) don't affect debugserver 1774 1775 // Only set the inferior 1776 if (launch_process) 1777 { 1778 if (stdio_path && pass_stdio_path_to_debugserver) 1779 { 1780 debugserver_args.AppendArgument("-s"); // short for --stdio-path 1781 StreamString strm; 1782 strm.Printf("'%s'", stdio_path); 1783 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO 1784 } 1785 } 1786 1787 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 1788 if (env_debugserver_log_file) 1789 { 1790 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 1791 debugserver_args.AppendArgument(arg_cstr); 1792 } 1793 1794 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 1795 if (env_debugserver_log_flags) 1796 { 1797 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 1798 debugserver_args.AppendArgument(arg_cstr); 1799 } 1800// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 1801// debugserver_args.AppendArgument("--log-flags=0x800e0e"); 1802 1803 // Now append the program arguments 1804 if (launch_process) 1805 { 1806 if (inferior_argv) 1807 { 1808 // Terminate the debugserver args so we can now append the inferior args 1809 debugserver_args.AppendArgument("--"); 1810 1811 for (int i = 0; inferior_argv[i] != NULL; ++i) 1812 debugserver_args.AppendArgument (inferior_argv[i]); 1813 } 1814 else 1815 { 1816 // Will send environment entries with the 'QEnvironment:' packet 1817 // Will send arguments with the 'A' packet 1818 } 1819 } 1820 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 1821 { 1822 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 1823 debugserver_args.AppendArgument (arg_cstr); 1824 } 1825 else if (attach_name && attach_name[0]) 1826 { 1827 if (wait_for_launch) 1828 debugserver_args.AppendArgument ("--waitfor"); 1829 else 1830 debugserver_args.AppendArgument ("--attach"); 1831 debugserver_args.AppendArgument (attach_name); 1832 } 1833 1834 Error file_actions_err; 1835 posix_spawn_file_actions_t file_actions; 1836#if DONT_CLOSE_DEBUGSERVER_STDIO 1837 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below."); 1838#else 1839 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX); 1840 if (file_actions_err.Success()) 1841 { 1842 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO); 1843 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO); 1844 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO); 1845 } 1846#endif 1847 1848 if (log) 1849 { 1850 StreamString strm; 1851 debugserver_args.Dump (&strm); 1852 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 1853 } 1854 1855 error.SetError(::posix_spawnp (&m_debugserver_pid, 1856 debugserver_path, 1857 file_actions_err.Success() ? &file_actions : NULL, 1858 &attr, 1859 debugserver_args.GetArgumentVector(), 1860 (char * const*)inferior_envp), 1861 eErrorTypePOSIX); 1862 1863 if (file_actions_err.Success()) 1864 ::posix_spawn_file_actions_destroy (&file_actions); 1865 1866 // We have seen some cases where posix_spawnp was returning a valid 1867 // looking pid even when an error was returned, so clear it out 1868 if (error.Fail()) 1869 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1870 1871 if (error.Fail() || log) 1872 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", m_debugserver_pid, debugserver_path, NULL, &attr, inferior_argv, inferior_envp); 1873 1874// if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1875// { 1876// std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true)); 1877// if (conn_ap.get()) 1878// { 1879// m_stdio_communication.SetConnection(conn_ap.release()); 1880// if (m_stdio_communication.IsConnected()) 1881// { 1882// m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 1883// m_stdio_communication.StartReadThread(); 1884// } 1885// } 1886// } 1887 } 1888 else 1889 { 1890 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n"); 1891 } 1892 1893 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1894 StartAsyncThread (); 1895 } 1896 return error; 1897} 1898 1899bool 1900ProcessGDBRemote::MonitorDebugserverProcess 1901( 1902 void *callback_baton, 1903 lldb::pid_t debugserver_pid, 1904 int signo, // Zero for no signal 1905 int exit_status // Exit value of process if signal is zero 1906) 1907{ 1908 // We pass in the ProcessGDBRemote inferior process it and name it 1909 // "gdb_remote_pid". The process ID is passed in the "callback_baton" 1910 // pointer value itself, thus we need the double cast... 1911 1912 // "debugserver_pid" argument passed in is the process ID for 1913 // debugserver that we are tracking... 1914 1915 lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton; 1916 TargetSP target_sp(Debugger::GetSharedInstance().GetTargetList().FindTargetWithProcessID (gdb_remote_pid)); 1917 if (target_sp) 1918 { 1919 ProcessSP process_sp (target_sp->GetProcessSP()); 1920 if (process_sp) 1921 { 1922 // Sleep for a half a second to make sure our inferior process has 1923 // time to set its exit status before we set it incorrectly when 1924 // both the debugserver and the inferior process shut down. 1925 usleep (500000); 1926 // If our process hasn't yet exited, debugserver might have died. 1927 // If the process did exit, the we are reaping it. 1928 if (process_sp->GetState() != eStateExited) 1929 { 1930 char error_str[1024]; 1931 if (signo) 1932 { 1933 const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1934 if (signal_cstr) 1935 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 1936 else 1937 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 1938 } 1939 else 1940 { 1941 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 1942 } 1943 1944 process_sp->SetExitStatus (-1, error_str); 1945 } 1946 else 1947 { 1948 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get(); 1949 // Debugserver has exited we need to let our ProcessGDBRemote 1950 // know that it no longer has a debugserver instance 1951 gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1952 // We are returning true to this function below, so we can 1953 // forget about the monitor handle. 1954 gdb_process->m_debugserver_monitor = 0; 1955 } 1956 } 1957 } 1958 return true; 1959} 1960 1961void 1962ProcessGDBRemote::KillDebugserverProcess () 1963{ 1964 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1965 { 1966 ::kill (m_debugserver_pid, SIGINT); 1967 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1968 } 1969} 1970 1971void 1972ProcessGDBRemote::Initialize() 1973{ 1974 static bool g_initialized = false; 1975 1976 if (g_initialized == false) 1977 { 1978 g_initialized = true; 1979 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1980 GetPluginDescriptionStatic(), 1981 CreateInstance); 1982 1983 Log::Callbacks log_callbacks = { 1984 ProcessGDBRemoteLog::DisableLog, 1985 ProcessGDBRemoteLog::EnableLog, 1986 ProcessGDBRemoteLog::ListLogCategories 1987 }; 1988 1989 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 1990 } 1991} 1992 1993bool 1994ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid) 1995{ 1996 if (m_curr_tid == tid) 1997 return true; 1998 1999 char packet[32]; 2000 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 2001 assert (packet_len + 1 < sizeof(packet)); 2002 StringExtractorGDBRemote response; 2003 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2004 { 2005 if (response.IsOKPacket()) 2006 { 2007 m_curr_tid = tid; 2008 return true; 2009 } 2010 } 2011 return false; 2012} 2013 2014bool 2015ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid) 2016{ 2017 if (m_curr_tid_run == tid) 2018 return true; 2019 2020 char packet[32]; 2021 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 2022 assert (packet_len + 1 < sizeof(packet)); 2023 StringExtractorGDBRemote response; 2024 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2025 { 2026 if (response.IsOKPacket()) 2027 { 2028 m_curr_tid_run = tid; 2029 return true; 2030 } 2031 } 2032 return false; 2033} 2034 2035void 2036ProcessGDBRemote::ResetGDBRemoteState () 2037{ 2038 // Reset and GDB remote state 2039 m_curr_tid = LLDB_INVALID_THREAD_ID; 2040 m_curr_tid_run = LLDB_INVALID_THREAD_ID; 2041 m_z0_supported = 1; 2042} 2043 2044 2045bool 2046ProcessGDBRemote::StartAsyncThread () 2047{ 2048 ResetGDBRemoteState (); 2049 2050 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 2051 2052 if (log) 2053 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2054 2055 // Create a thread that watches our internal state and controls which 2056 // events make it to clients (into the DCProcess event queue). 2057 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2058 return m_async_thread != LLDB_INVALID_HOST_THREAD; 2059} 2060 2061void 2062ProcessGDBRemote::StopAsyncThread () 2063{ 2064 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 2065 2066 if (log) 2067 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2068 2069 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2070 2071 // Stop the stdio thread 2072 if (m_async_thread != LLDB_INVALID_HOST_THREAD) 2073 { 2074 Host::ThreadJoin (m_async_thread, NULL, NULL); 2075 } 2076} 2077 2078 2079void * 2080ProcessGDBRemote::AsyncThread (void *arg) 2081{ 2082 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2083 2084 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2085 if (log) 2086 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID()); 2087 2088 Listener listener ("ProcessGDBRemote::AsyncThread"); 2089 EventSP event_sp; 2090 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2091 eBroadcastBitAsyncThreadShouldExit; 2092 2093 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2094 { 2095 bool done = false; 2096 while (!done) 2097 { 2098 if (log) 2099 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2100 if (listener.WaitForEvent (NULL, event_sp)) 2101 { 2102 const uint32_t event_type = event_sp->GetType(); 2103 switch (event_type) 2104 { 2105 case eBroadcastBitAsyncContinue: 2106 { 2107 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2108 2109 if (continue_packet) 2110 { 2111 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2112 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2113 if (log) 2114 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2115 2116 process->SetPrivateState(eStateRunning); 2117 StringExtractorGDBRemote response; 2118 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2119 2120 switch (stop_state) 2121 { 2122 case eStateStopped: 2123 case eStateCrashed: 2124 case eStateSuspended: 2125 process->m_last_stop_packet = response; 2126 process->m_last_stop_packet.SetFilePos (0); 2127 process->SetPrivateState (stop_state); 2128 break; 2129 2130 case eStateExited: 2131 process->m_last_stop_packet = response; 2132 process->m_last_stop_packet.SetFilePos (0); 2133 response.SetFilePos(1); 2134 process->SetExitStatus(response.GetHexU8(), NULL); 2135 done = true; 2136 break; 2137 2138 case eStateInvalid: 2139 break; 2140 2141 default: 2142 process->SetPrivateState (stop_state); 2143 break; 2144 } 2145 } 2146 } 2147 break; 2148 2149 case eBroadcastBitAsyncThreadShouldExit: 2150 if (log) 2151 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2152 done = true; 2153 break; 2154 2155 default: 2156 if (log) 2157 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2158 done = true; 2159 break; 2160 } 2161 } 2162 else 2163 { 2164 if (log) 2165 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2166 done = true; 2167 } 2168 } 2169 } 2170 2171 if (log) 2172 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID()); 2173 2174 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2175 return NULL; 2176} 2177 2178lldb_private::unw_addr_space_t 2179ProcessGDBRemote::GetLibUnwindAddressSpace () 2180{ 2181 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED; 2182 2183 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType(); 2184 if (arch_cpu == ArchSpec::eCPU_i386) 2185 target_type = UNW_TARGET_I386; 2186 else if (arch_cpu == ArchSpec::eCPU_x86_64) 2187 target_type = UNW_TARGET_X86_64; 2188 2189 if (m_libunwind_addr_space) 2190 { 2191 if (m_libunwind_target_type != target_type) 2192 DestoryLibUnwindAddressSpace(); 2193 else 2194 return m_libunwind_addr_space; 2195 } 2196 unw_accessors_t callbacks = get_macosx_libunwind_callbacks (); 2197 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type); 2198 if (m_libunwind_addr_space) 2199 m_libunwind_target_type = target_type; 2200 else 2201 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED; 2202 return m_libunwind_addr_space; 2203} 2204 2205void 2206ProcessGDBRemote::DestoryLibUnwindAddressSpace () 2207{ 2208 if (m_libunwind_addr_space) 2209 { 2210 unw_destroy_addr_space (m_libunwind_addr_space); 2211 m_libunwind_addr_space = NULL; 2212 } 2213 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED; 2214} 2215 2216 2217const char * 2218ProcessGDBRemote::GetDispatchQueueNameForThread 2219( 2220 addr_t thread_dispatch_qaddr, 2221 std::string &dispatch_queue_name 2222) 2223{ 2224 dispatch_queue_name.clear(); 2225 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2226 { 2227 // Cache the dispatch_queue_offsets_addr value so we don't always have 2228 // to look it up 2229 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2230 { 2231 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib"))); 2232 if (module_sp.get() == NULL) 2233 return NULL; 2234 2235 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData); 2236 if (dispatch_queue_offsets_symbol) 2237 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this); 2238 2239 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2240 return NULL; 2241 } 2242 2243 uint8_t memory_buffer[8]; 2244 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize()); 2245 2246 // Excerpt from src/queue_private.h 2247 struct dispatch_queue_offsets_s 2248 { 2249 uint16_t dqo_version; 2250 uint16_t dqo_label; 2251 uint16_t dqo_label_size; 2252 } dispatch_queue_offsets; 2253 2254 2255 Error error; 2256 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2257 { 2258 uint32_t data_offset = 0; 2259 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2260 { 2261 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2262 { 2263 data_offset = 0; 2264 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2265 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2266 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2267 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2268 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2269 dispatch_queue_name.erase (bytes_read); 2270 } 2271 } 2272 } 2273 } 2274 if (dispatch_queue_name.empty()) 2275 return NULL; 2276 return dispatch_queue_name.c_str(); 2277} 2278 2279