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