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" 53 using namespace lldb; 54 using namespace lldb_private; 55 56 static inline uint16_t 57 get_random_port () 58 { 59 return (arc4random() % (UINT16_MAX - 1000u)) + 1000u; 60 } 61 62 63 const char * 64 ProcessGDBRemote::GetPluginNameStatic() 65 { 66 return "process.gdb-remote"; 67 } 68 69 const char * 70 ProcessGDBRemote::GetPluginDescriptionStatic() 71 { 72 return "GDB Remote protocol based debugging plug-in."; 73 } 74 75 void 76 ProcessGDBRemote::Terminate() 77 { 78 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 79 } 80 81 82 Process* 83 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener) 84 { 85 return new ProcessGDBRemote (target, listener); 86 } 87 88 bool 89 ProcessGDBRemote::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 //---------------------------------------------------------------------- 102 ProcessGDBRemote::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 //---------------------------------------------------------------------- 130 ProcessGDBRemote::~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 //---------------------------------------------------------------------- 148 const char * 149 ProcessGDBRemote::GetPluginName() 150 { 151 return "Process debugging plug-in that uses the GDB remote protocol"; 152 } 153 154 const char * 155 ProcessGDBRemote::GetShortPluginName() 156 { 157 return GetPluginNameStatic(); 158 } 159 160 uint32_t 161 ProcessGDBRemote::GetPluginVersion() 162 { 163 return 1; 164 } 165 166 void 167 ProcessGDBRemote::GetPluginCommandHelp (const char *command, Stream *strm) 168 { 169 strm->Printf("TODO: fill this in\n"); 170 } 171 172 Error 173 ProcessGDBRemote::ExecutePluginCommand (Args &command, Stream *strm) 174 { 175 Error error; 176 error.SetErrorString("No plug-in commands are currently supported."); 177 return error; 178 } 179 180 Log * 181 ProcessGDBRemote::EnablePluginLogging (Stream *strm, Args &command) 182 { 183 return NULL; 184 } 185 186 void 187 ProcessGDBRemote::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 334 Error 335 ProcessGDBRemote::WillLaunch (Module* module) 336 { 337 return WillLaunchOrAttach (); 338 } 339 340 Error 341 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 342 { 343 return WillLaunchOrAttach (); 344 } 345 346 Error 347 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 348 { 349 return WillLaunchOrAttach (); 350 } 351 352 Error 353 ProcessGDBRemote::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 //---------------------------------------------------------------------- 369 Error 370 ProcessGDBRemote::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 513 Error 514 ProcessGDBRemote::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 577 void 578 ProcessGDBRemote::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 628 void 629 ProcessGDBRemote::DidLaunch () 630 { 631 DidLaunchOrAttach (); 632 if (m_dynamic_loader_ap.get()) 633 m_dynamic_loader_ap->DidLaunch(); 634 } 635 636 Error 637 ProcessGDBRemote::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 720 size_t 721 ProcessGDBRemote::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 741 Error 742 ProcessGDBRemote::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 871 void 872 ProcessGDBRemote::DidAttach () 873 { 874 if (m_dynamic_loader_ap.get()) 875 m_dynamic_loader_ap->DidAttach(); 876 DidLaunchOrAttach (); 877 } 878 879 Error 880 ProcessGDBRemote::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 891 Error 892 ProcessGDBRemote::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 913 size_t 914 ProcessGDBRemote::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 960 uint32_t 961 ProcessGDBRemote::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 1012 StateType 1013 ProcessGDBRemote::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_size = exc_data.size(); 1102 1103 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1104 exc_type, 1105 exc_data_size, 1106 exc_data_size >= 1 ? exc_data[0] : 0, 1107 exc_data_size >= 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 1133 void 1134 ProcessGDBRemote::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 1154 Error 1155 ProcessGDBRemote::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 1173 Error 1174 ProcessGDBRemote::InterruptIfRunning 1175 ( 1176 bool discard_thread_plans, 1177 bool catch_stop_event, 1178 EventSP &stop_event_sp 1179 ) 1180 { 1181 Error error; 1182 1183 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1184 1185 bool paused_private_state_thread = false; 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) is_running=%i", 1189 discard_thread_plans, 1190 catch_stop_event, 1191 is_running); 1192 1193 if (discard_thread_plans) 1194 { 1195 if (log) 1196 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans"); 1197 m_thread_list.DiscardThreadPlans(); 1198 } 1199 if (is_running) 1200 { 1201 if (catch_stop_event) 1202 { 1203 if (log) 1204 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread"); 1205 PausePrivateStateThread(); 1206 paused_private_state_thread = true; 1207 } 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 (paused_private_state_thread) 1221 ResumePrivateStateThread(); 1222 return error; 1223 } 1224 1225 if (catch_stop_event) 1226 { 1227 // LISTEN HERE 1228 TimeValue timeout_time; 1229 timeout_time = TimeValue::Now(); 1230 timeout_time.OffsetWithSeconds(5); 1231 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp); 1232 1233 timed_out = state == eStateInvalid; 1234 if (log) 1235 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out); 1236 1237 if (timed_out) 1238 error.SetErrorString("unable to verify target stopped"); 1239 } 1240 1241 if (paused_private_state_thread) 1242 { 1243 if (log) 1244 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread"); 1245 ResumePrivateStateThread(); 1246 } 1247 } 1248 return error; 1249 } 1250 1251 Error 1252 ProcessGDBRemote::WillDetach () 1253 { 1254 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1255 if (log) 1256 log->Printf ("ProcessGDBRemote::WillDetach()"); 1257 1258 bool discard_thread_plans = true; 1259 bool catch_stop_event = true; 1260 EventSP event_sp; 1261 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp); 1262 } 1263 1264 Error 1265 ProcessGDBRemote::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 1297 Error 1298 ProcessGDBRemote::DoDestroy () 1299 { 1300 Error error; 1301 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1302 if (log) 1303 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1304 1305 // Interrupt if our inferior is running... 1306 if (m_gdb_comm.IsConnected()) 1307 { 1308 StringExtractorGDBRemote response; 1309 bool send_async = true; 1310 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, 2, send_async)) 1311 { 1312 char packet_cmd = response.GetChar(0); 1313 1314 if (packet_cmd == 'W' || packet_cmd == 'X') 1315 { 1316 m_last_stop_packet = response; 1317 SetExitStatus(response.GetHexU8(), NULL); 1318 } 1319 } 1320 else 1321 { 1322 SetExitStatus(SIGABRT, NULL); 1323 //error.SetErrorString("kill packet failed"); 1324 } 1325 } 1326 StopAsyncThread (); 1327 m_gdb_comm.StopReadThread(); 1328 KillDebugserverProcess (); 1329 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 1330 return error; 1331 } 1332 1333 //------------------------------------------------------------------ 1334 // Process Queries 1335 //------------------------------------------------------------------ 1336 1337 bool 1338 ProcessGDBRemote::IsAlive () 1339 { 1340 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 1341 } 1342 1343 addr_t 1344 ProcessGDBRemote::GetImageInfoAddress() 1345 { 1346 if (!m_gdb_comm.IsRunning()) 1347 { 1348 StringExtractorGDBRemote response; 1349 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false)) 1350 { 1351 if (response.IsNormalPacket()) 1352 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1353 } 1354 } 1355 return LLDB_INVALID_ADDRESS; 1356 } 1357 1358 DynamicLoader * 1359 ProcessGDBRemote::GetDynamicLoader() 1360 { 1361 return m_dynamic_loader_ap.get(); 1362 } 1363 1364 //------------------------------------------------------------------ 1365 // Process Memory 1366 //------------------------------------------------------------------ 1367 size_t 1368 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1369 { 1370 if (size > m_max_memory_size) 1371 { 1372 // Keep memory read sizes down to a sane limit. This function will be 1373 // called multiple times in order to complete the task by 1374 // lldb_private::Process so it is ok to do this. 1375 size = m_max_memory_size; 1376 } 1377 1378 char packet[64]; 1379 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1380 assert (packet_len + 1 < sizeof(packet)); 1381 StringExtractorGDBRemote response; 1382 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1383 { 1384 if (response.IsNormalPacket()) 1385 { 1386 error.Clear(); 1387 return response.GetHexBytes(buf, size, '\xdd'); 1388 } 1389 else if (response.IsErrorPacket()) 1390 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1391 else if (response.IsUnsupportedPacket()) 1392 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1393 else 1394 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1395 } 1396 else 1397 { 1398 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1399 } 1400 return 0; 1401 } 1402 1403 size_t 1404 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1405 { 1406 StreamString packet; 1407 packet.Printf("M%llx,%zx:", addr, size); 1408 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost); 1409 StringExtractorGDBRemote response; 1410 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true)) 1411 { 1412 if (response.IsOKPacket()) 1413 { 1414 error.Clear(); 1415 return size; 1416 } 1417 else if (response.IsErrorPacket()) 1418 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1419 else if (response.IsUnsupportedPacket()) 1420 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1421 else 1422 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1423 } 1424 else 1425 { 1426 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1427 } 1428 return 0; 1429 } 1430 1431 lldb::addr_t 1432 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1433 { 1434 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout); 1435 if (allocated_addr == LLDB_INVALID_ADDRESS) 1436 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions); 1437 else 1438 error.Clear(); 1439 return allocated_addr; 1440 } 1441 1442 Error 1443 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 1444 { 1445 Error error; 1446 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout)) 1447 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 1448 return error; 1449 } 1450 1451 1452 //------------------------------------------------------------------ 1453 // Process STDIO 1454 //------------------------------------------------------------------ 1455 1456 size_t 1457 ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error) 1458 { 1459 Mutex::Locker locker(m_stdio_mutex); 1460 size_t bytes_available = m_stdout_data.size(); 1461 if (bytes_available > 0) 1462 { 1463 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size); 1464 if (bytes_available > buf_size) 1465 { 1466 memcpy(buf, m_stdout_data.c_str(), buf_size); 1467 m_stdout_data.erase(0, buf_size); 1468 bytes_available = buf_size; 1469 } 1470 else 1471 { 1472 memcpy(buf, m_stdout_data.c_str(), bytes_available); 1473 m_stdout_data.clear(); 1474 1475 //ResetEventBits(eBroadcastBitSTDOUT); 1476 } 1477 } 1478 return bytes_available; 1479 } 1480 1481 size_t 1482 ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error) 1483 { 1484 // Can we get STDERR through the remote protocol? 1485 return 0; 1486 } 1487 1488 size_t 1489 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 1490 { 1491 if (m_stdio_communication.IsConnected()) 1492 { 1493 ConnectionStatus status; 1494 m_stdio_communication.Write(src, src_len, status, NULL); 1495 } 1496 return 0; 1497 } 1498 1499 Error 1500 ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 1501 { 1502 Error error; 1503 assert (bp_site != NULL); 1504 1505 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 1506 user_id_t site_id = bp_site->GetID(); 1507 const addr_t addr = bp_site->GetLoadAddress(); 1508 if (log) 1509 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr); 1510 1511 if (bp_site->IsEnabled()) 1512 { 1513 if (log) 1514 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 1515 return error; 1516 } 1517 else 1518 { 1519 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1520 1521 if (bp_site->HardwarePreferred()) 1522 { 1523 // Try and set hardware breakpoint, and if that fails, fall through 1524 // and set a software breakpoint? 1525 } 1526 1527 if (m_z0_supported) 1528 { 1529 char packet[64]; 1530 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size); 1531 assert (packet_len + 1 < sizeof(packet)); 1532 StringExtractorGDBRemote response; 1533 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1534 { 1535 if (response.IsUnsupportedPacket()) 1536 { 1537 // Disable z packet support and try again 1538 m_z0_supported = 0; 1539 return EnableBreakpoint (bp_site); 1540 } 1541 else if (response.IsOKPacket()) 1542 { 1543 bp_site->SetEnabled(true); 1544 bp_site->SetType (BreakpointSite::eExternal); 1545 return error; 1546 } 1547 else 1548 { 1549 uint8_t error_byte = response.GetError(); 1550 if (error_byte) 1551 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1552 } 1553 } 1554 } 1555 else 1556 { 1557 return EnableSoftwareBreakpoint (bp_site); 1558 } 1559 } 1560 1561 if (log) 1562 { 1563 const char *err_string = error.AsCString(); 1564 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 1565 bp_site->GetLoadAddress(), 1566 err_string ? err_string : "NULL"); 1567 } 1568 // We shouldn't reach here on a successful breakpoint enable... 1569 if (error.Success()) 1570 error.SetErrorToGenericError(); 1571 return error; 1572 } 1573 1574 Error 1575 ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 1576 { 1577 Error error; 1578 assert (bp_site != NULL); 1579 addr_t addr = bp_site->GetLoadAddress(); 1580 user_id_t site_id = bp_site->GetID(); 1581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 1582 if (log) 1583 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr); 1584 1585 if (bp_site->IsEnabled()) 1586 { 1587 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1588 1589 if (bp_site->IsHardware()) 1590 { 1591 // TODO: disable hardware breakpoint... 1592 } 1593 else 1594 { 1595 if (m_z0_supported) 1596 { 1597 char packet[64]; 1598 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size); 1599 assert (packet_len + 1 < sizeof(packet)); 1600 StringExtractorGDBRemote response; 1601 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1602 { 1603 if (response.IsUnsupportedPacket()) 1604 { 1605 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported."); 1606 } 1607 else if (response.IsOKPacket()) 1608 { 1609 if (log) 1610 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr); 1611 bp_site->SetEnabled(false); 1612 return error; 1613 } 1614 else 1615 { 1616 uint8_t error_byte = response.GetError(); 1617 if (error_byte) 1618 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1619 } 1620 } 1621 } 1622 else 1623 { 1624 return DisableSoftwareBreakpoint (bp_site); 1625 } 1626 } 1627 } 1628 else 1629 { 1630 if (log) 1631 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 1632 return error; 1633 } 1634 1635 if (error.Success()) 1636 error.SetErrorToGenericError(); 1637 return error; 1638 } 1639 1640 Error 1641 ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp) 1642 { 1643 Error error; 1644 if (wp) 1645 { 1646 user_id_t watchID = wp->GetID(); 1647 addr_t addr = wp->GetLoadAddress(); 1648 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 1649 if (log) 1650 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID); 1651 if (wp->IsEnabled()) 1652 { 1653 if (log) 1654 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 1655 return error; 1656 } 1657 else 1658 { 1659 // Pass down an appropriate z/Z packet... 1660 error.SetErrorString("watchpoints not supported"); 1661 } 1662 } 1663 else 1664 { 1665 error.SetErrorString("Watchpoint location argument was NULL."); 1666 } 1667 if (error.Success()) 1668 error.SetErrorToGenericError(); 1669 return error; 1670 } 1671 1672 Error 1673 ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp) 1674 { 1675 Error error; 1676 if (wp) 1677 { 1678 user_id_t watchID = wp->GetID(); 1679 1680 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 1681 1682 addr_t addr = wp->GetLoadAddress(); 1683 if (log) 1684 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr); 1685 1686 if (wp->IsHardware()) 1687 { 1688 // Pass down an appropriate z/Z packet... 1689 error.SetErrorString("watchpoints not supported"); 1690 } 1691 // TODO: clear software watchpoints if we implement them 1692 } 1693 else 1694 { 1695 error.SetErrorString("Watchpoint location argument was NULL."); 1696 } 1697 if (error.Success()) 1698 error.SetErrorToGenericError(); 1699 return error; 1700 } 1701 1702 void 1703 ProcessGDBRemote::Clear() 1704 { 1705 m_flags = 0; 1706 m_thread_list.Clear(); 1707 { 1708 Mutex::Locker locker(m_stdio_mutex); 1709 m_stdout_data.clear(); 1710 } 1711 } 1712 1713 Error 1714 ProcessGDBRemote::DoSignal (int signo) 1715 { 1716 Error error; 1717 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1718 if (log) 1719 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 1720 1721 if (!m_gdb_comm.SendAsyncSignal (signo)) 1722 error.SetErrorStringWithFormat("failed to send signal %i", signo); 1723 return error; 1724 } 1725 1726 //void 1727 //ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 1728 //{ 1729 // ProcessGDBRemote *process = (ProcessGDBRemote *)baton; 1730 // process->AppendSTDOUT(static_cast<const char *>(src), src_len); 1731 //} 1732 1733 //void 1734 //ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len) 1735 //{ 1736 // ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s); 1737 // Mutex::Locker locker(m_stdio_mutex); 1738 // m_stdout_data.append(s, len); 1739 // 1740 // // FIXME: Make a real data object for this and put it out. 1741 // BroadcastEventIfUnique (eBroadcastBitSTDOUT); 1742 //} 1743 1744 1745 Error 1746 ProcessGDBRemote::StartDebugserverProcess 1747 ( 1748 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 1749 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument 1750 char const *inferior_envp[], // Environment to pass along to the inferior program 1751 const char *stdin_path, 1752 const char *stdout_path, 1753 const char *stderr_path, 1754 const char *working_dir, 1755 bool launch_process, // Set to true if we are going to be launching a the process 1756 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 1757 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name" 1758 bool wait_for_launch, // Wait for the process named "attach_name" to launch 1759 uint32_t launch_flags, // Launch flags 1760 ArchSpec& inferior_arch // The arch of the inferior that we will launch 1761 ) 1762 { 1763 Error error; 1764 bool disable_aslr = (launch_flags & eLaunchFlagDisableASLR) != 0; 1765 bool no_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 1766 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 1767 { 1768 // If we locate debugserver, keep that located version around 1769 static FileSpec g_debugserver_file_spec; 1770 1771 FileSpec debugserver_file_spec; 1772 char debugserver_path[PATH_MAX]; 1773 1774 // Always check to see if we have an environment override for the path 1775 // to the debugserver to use and use it if we do. 1776 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 1777 if (env_debugserver_path) 1778 debugserver_file_spec.SetFile (env_debugserver_path, false); 1779 else 1780 debugserver_file_spec = g_debugserver_file_spec; 1781 bool debugserver_exists = debugserver_file_spec.Exists(); 1782 if (!debugserver_exists) 1783 { 1784 // The debugserver binary is in the LLDB.framework/Resources 1785 // directory. 1786 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 1787 { 1788 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 1789 debugserver_exists = debugserver_file_spec.Exists(); 1790 if (debugserver_exists) 1791 { 1792 g_debugserver_file_spec = debugserver_file_spec; 1793 } 1794 else 1795 { 1796 g_debugserver_file_spec.Clear(); 1797 debugserver_file_spec.Clear(); 1798 } 1799 } 1800 } 1801 1802 if (debugserver_exists) 1803 { 1804 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 1805 1806 m_stdio_communication.Clear(); 1807 posix_spawnattr_t attr; 1808 1809 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1810 1811 Error local_err; // Errors that don't affect the spawning. 1812 if (log) 1813 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString()); 1814 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX); 1815 if (error.Fail() || log) 1816 error.PutToLog(log.get(), "::posix_spawnattr_init ( &attr )"); 1817 if (error.Fail()) 1818 return error;; 1819 1820 #if !defined (__arm__) 1821 1822 // We don't need to do this for ARM, and we really shouldn't now 1823 // that we have multiple CPU subtypes and no posix_spawnattr call 1824 // that allows us to set which CPU subtype to launch... 1825 if (inferior_arch.GetType() == eArchTypeMachO) 1826 { 1827 cpu_type_t cpu = inferior_arch.GetCPUType(); 1828 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE) 1829 { 1830 size_t ocount = 0; 1831 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX); 1832 if (error.Fail() || log) 1833 error.PutToLog(log.get(), "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount); 1834 1835 if (error.Fail() != 0 || ocount != 1) 1836 return error; 1837 } 1838 } 1839 1840 #endif 1841 1842 Args debugserver_args; 1843 char arg_cstr[PATH_MAX]; 1844 1845 lldb_utility::PseudoTerminal pty; 1846 const char *stdio_path = NULL; 1847 if (launch_process && 1848 stdin_path == NULL && 1849 stdout_path == NULL && 1850 stderr_path == NULL && 1851 m_local_debugserver && 1852 no_stdio == false) 1853 { 1854 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 1855 stdio_path = pty.GetSlaveName (NULL, 0); 1856 } 1857 1858 // Start args with "debugserver /file/path -r --" 1859 debugserver_args.AppendArgument(debugserver_path); 1860 debugserver_args.AppendArgument(debugserver_url); 1861 // use native registers, not the GDB registers 1862 debugserver_args.AppendArgument("--native-regs"); 1863 // make debugserver run in its own session so signals generated by 1864 // special terminal key sequences (^C) don't affect debugserver 1865 debugserver_args.AppendArgument("--setsid"); 1866 1867 if (disable_aslr) 1868 debugserver_args.AppendArguments("--disable-aslr"); 1869 1870 // Only set the inferior 1871 if (launch_process) 1872 { 1873 if (no_stdio) 1874 debugserver_args.AppendArgument("--no-stdio"); 1875 else 1876 { 1877 if (stdin_path && stdout_path && stderr_path && 1878 strcmp(stdin_path, stdout_path) == 0 && 1879 strcmp(stdin_path, stderr_path) == 0) 1880 { 1881 stdio_path = stdin_path; 1882 stdin_path = stdout_path = stderr_path = NULL; 1883 } 1884 1885 if (stdio_path) 1886 { 1887 // All file handles to stdin, stdout, stderr are the same... 1888 debugserver_args.AppendArgument("--stdio-path"); 1889 debugserver_args.AppendArgument(stdio_path); 1890 } 1891 else 1892 { 1893 if (stdin_path == NULL && (stdout_path || stderr_path)) 1894 stdin_path = "/dev/null"; 1895 1896 if (stdout_path == NULL && (stdin_path || stderr_path)) 1897 stdout_path = "/dev/null"; 1898 1899 if (stderr_path == NULL && (stdin_path || stdout_path)) 1900 stderr_path = "/dev/null"; 1901 1902 if (stdin_path) 1903 { 1904 debugserver_args.AppendArgument("--stdin-path"); 1905 debugserver_args.AppendArgument(stdin_path); 1906 } 1907 if (stdout_path) 1908 { 1909 debugserver_args.AppendArgument("--stdout-path"); 1910 debugserver_args.AppendArgument(stdout_path); 1911 } 1912 if (stderr_path) 1913 { 1914 debugserver_args.AppendArgument("--stderr-path"); 1915 debugserver_args.AppendArgument(stderr_path); 1916 } 1917 } 1918 } 1919 } 1920 1921 if (working_dir) 1922 { 1923 debugserver_args.AppendArgument("--working-dir"); 1924 debugserver_args.AppendArgument(working_dir); 1925 } 1926 1927 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 1928 if (env_debugserver_log_file) 1929 { 1930 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 1931 debugserver_args.AppendArgument(arg_cstr); 1932 } 1933 1934 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 1935 if (env_debugserver_log_flags) 1936 { 1937 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 1938 debugserver_args.AppendArgument(arg_cstr); 1939 } 1940 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 1941 // debugserver_args.AppendArgument("--log-flags=0x800e0e"); 1942 1943 // Now append the program arguments 1944 if (launch_process) 1945 { 1946 if (inferior_argv) 1947 { 1948 // Terminate the debugserver args so we can now append the inferior args 1949 debugserver_args.AppendArgument("--"); 1950 1951 for (int i = 0; inferior_argv[i] != NULL; ++i) 1952 debugserver_args.AppendArgument (inferior_argv[i]); 1953 } 1954 else 1955 { 1956 // Will send environment entries with the 'QEnvironment:' packet 1957 // Will send arguments with the 'A' packet 1958 } 1959 } 1960 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 1961 { 1962 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 1963 debugserver_args.AppendArgument (arg_cstr); 1964 } 1965 else if (attach_name && attach_name[0]) 1966 { 1967 if (wait_for_launch) 1968 debugserver_args.AppendArgument ("--waitfor"); 1969 else 1970 debugserver_args.AppendArgument ("--attach"); 1971 debugserver_args.AppendArgument (attach_name); 1972 } 1973 1974 Error file_actions_err; 1975 posix_spawn_file_actions_t file_actions; 1976 #if DONT_CLOSE_DEBUGSERVER_STDIO 1977 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below."); 1978 #else 1979 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX); 1980 if (file_actions_err.Success()) 1981 { 1982 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO); 1983 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO); 1984 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO); 1985 } 1986 #endif 1987 1988 if (log) 1989 { 1990 StreamString strm; 1991 debugserver_args.Dump (&strm); 1992 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 1993 } 1994 1995 error.SetError (::posix_spawnp (&m_debugserver_pid, 1996 debugserver_path, 1997 file_actions_err.Success() ? &file_actions : NULL, 1998 &attr, 1999 debugserver_args.GetArgumentVector(), 2000 (char * const*)inferior_envp), 2001 eErrorTypePOSIX); 2002 2003 2004 ::posix_spawnattr_destroy (&attr); 2005 2006 if (file_actions_err.Success()) 2007 ::posix_spawn_file_actions_destroy (&file_actions); 2008 2009 // We have seen some cases where posix_spawnp was returning a valid 2010 // looking pid even when an error was returned, so clear it out 2011 if (error.Fail()) 2012 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2013 2014 if (error.Fail() || log) 2015 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); 2016 2017 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID && !no_stdio) 2018 { 2019 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) 2020 SetUpProcessInputReader (pty.ReleaseMasterFileDescriptor()); 2021 } 2022 } 2023 else 2024 { 2025 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n"); 2026 } 2027 2028 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2029 StartAsyncThread (); 2030 } 2031 return error; 2032 } 2033 2034 bool 2035 ProcessGDBRemote::MonitorDebugserverProcess 2036 ( 2037 void *callback_baton, 2038 lldb::pid_t debugserver_pid, 2039 int signo, // Zero for no signal 2040 int exit_status // Exit value of process if signal is zero 2041 ) 2042 { 2043 // We pass in the ProcessGDBRemote inferior process it and name it 2044 // "gdb_remote_pid". The process ID is passed in the "callback_baton" 2045 // pointer value itself, thus we need the double cast... 2046 2047 // "debugserver_pid" argument passed in is the process ID for 2048 // debugserver that we are tracking... 2049 2050 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2051 2052 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2053 if (log) 2054 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%i, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2055 2056 if (process) 2057 { 2058 // Sleep for a half a second to make sure our inferior process has 2059 // time to set its exit status before we set it incorrectly when 2060 // both the debugserver and the inferior process shut down. 2061 usleep (500000); 2062 // If our process hasn't yet exited, debugserver might have died. 2063 // If the process did exit, the we are reaping it. 2064 const StateType state = process->GetState(); 2065 2066 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2067 state != eStateInvalid && 2068 state != eStateUnloaded && 2069 state != eStateExited && 2070 state != eStateDetached) 2071 { 2072 char error_str[1024]; 2073 if (signo) 2074 { 2075 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2076 if (signal_cstr) 2077 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2078 else 2079 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2080 } 2081 else 2082 { 2083 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2084 } 2085 2086 process->SetExitStatus (-1, error_str); 2087 } 2088 // Debugserver has exited we need to let our ProcessGDBRemote 2089 // know that it no longer has a debugserver instance 2090 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2091 // We are returning true to this function below, so we can 2092 // forget about the monitor handle. 2093 process->m_debugserver_thread = LLDB_INVALID_HOST_THREAD; 2094 } 2095 return true; 2096 } 2097 2098 void 2099 ProcessGDBRemote::KillDebugserverProcess () 2100 { 2101 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2102 { 2103 ::kill (m_debugserver_pid, SIGINT); 2104 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2105 } 2106 } 2107 2108 void 2109 ProcessGDBRemote::Initialize() 2110 { 2111 static bool g_initialized = false; 2112 2113 if (g_initialized == false) 2114 { 2115 g_initialized = true; 2116 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2117 GetPluginDescriptionStatic(), 2118 CreateInstance); 2119 2120 Log::Callbacks log_callbacks = { 2121 ProcessGDBRemoteLog::DisableLog, 2122 ProcessGDBRemoteLog::EnableLog, 2123 ProcessGDBRemoteLog::ListLogCategories 2124 }; 2125 2126 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2127 } 2128 } 2129 2130 bool 2131 ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid) 2132 { 2133 if (m_curr_tid == tid) 2134 return true; 2135 2136 char packet[32]; 2137 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 2138 assert (packet_len + 1 < sizeof(packet)); 2139 StringExtractorGDBRemote response; 2140 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2141 { 2142 if (response.IsOKPacket()) 2143 { 2144 m_curr_tid = tid; 2145 return true; 2146 } 2147 } 2148 return false; 2149 } 2150 2151 bool 2152 ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid) 2153 { 2154 if (m_curr_tid_run == tid) 2155 return true; 2156 2157 char packet[32]; 2158 const int packet_len = ::snprintf (packet, sizeof(packet), "Hc%x", tid); 2159 assert (packet_len + 1 < sizeof(packet)); 2160 StringExtractorGDBRemote response; 2161 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2162 { 2163 if (response.IsOKPacket()) 2164 { 2165 m_curr_tid_run = tid; 2166 return true; 2167 } 2168 } 2169 return false; 2170 } 2171 2172 void 2173 ProcessGDBRemote::ResetGDBRemoteState () 2174 { 2175 // Reset and GDB remote state 2176 m_curr_tid = LLDB_INVALID_THREAD_ID; 2177 m_curr_tid_run = LLDB_INVALID_THREAD_ID; 2178 m_z0_supported = 1; 2179 } 2180 2181 2182 bool 2183 ProcessGDBRemote::StartAsyncThread () 2184 { 2185 ResetGDBRemoteState (); 2186 2187 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2188 2189 if (log) 2190 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2191 2192 // Create a thread that watches our internal state and controls which 2193 // events make it to clients (into the DCProcess event queue). 2194 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2195 return m_async_thread != LLDB_INVALID_HOST_THREAD; 2196 } 2197 2198 void 2199 ProcessGDBRemote::StopAsyncThread () 2200 { 2201 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2202 2203 if (log) 2204 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2205 2206 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2207 2208 // Stop the stdio thread 2209 if (m_async_thread != LLDB_INVALID_HOST_THREAD) 2210 { 2211 Host::ThreadJoin (m_async_thread, NULL, NULL); 2212 } 2213 } 2214 2215 2216 void * 2217 ProcessGDBRemote::AsyncThread (void *arg) 2218 { 2219 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2220 2221 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2222 if (log) 2223 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID()); 2224 2225 Listener listener ("ProcessGDBRemote::AsyncThread"); 2226 EventSP event_sp; 2227 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2228 eBroadcastBitAsyncThreadShouldExit; 2229 2230 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2231 { 2232 bool done = false; 2233 while (!done) 2234 { 2235 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2236 if (log) 2237 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2238 if (listener.WaitForEvent (NULL, event_sp)) 2239 { 2240 const uint32_t event_type = event_sp->GetType(); 2241 if (log) 2242 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2243 2244 switch (event_type) 2245 { 2246 case eBroadcastBitAsyncContinue: 2247 { 2248 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2249 2250 if (continue_packet) 2251 { 2252 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2253 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2254 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2255 if (log) 2256 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2257 2258 process->SetPrivateState(eStateRunning); 2259 StringExtractorGDBRemote response; 2260 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2261 2262 switch (stop_state) 2263 { 2264 case eStateStopped: 2265 case eStateCrashed: 2266 case eStateSuspended: 2267 process->m_last_stop_packet = response; 2268 process->m_last_stop_packet.SetFilePos (0); 2269 process->SetPrivateState (stop_state); 2270 break; 2271 2272 case eStateExited: 2273 process->m_last_stop_packet = response; 2274 process->m_last_stop_packet.SetFilePos (0); 2275 response.SetFilePos(1); 2276 process->SetExitStatus(response.GetHexU8(), NULL); 2277 done = true; 2278 break; 2279 2280 case eStateInvalid: 2281 break; 2282 2283 default: 2284 process->SetPrivateState (stop_state); 2285 break; 2286 } 2287 } 2288 } 2289 break; 2290 2291 case eBroadcastBitAsyncThreadShouldExit: 2292 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2293 if (log) 2294 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2295 done = true; 2296 break; 2297 2298 default: 2299 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2300 if (log) 2301 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2302 done = true; 2303 break; 2304 } 2305 } 2306 else 2307 { 2308 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2309 if (log) 2310 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2311 done = true; 2312 } 2313 } 2314 } 2315 2316 log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2317 if (log) 2318 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID()); 2319 2320 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2321 return NULL; 2322 } 2323 2324 const char * 2325 ProcessGDBRemote::GetDispatchQueueNameForThread 2326 ( 2327 addr_t thread_dispatch_qaddr, 2328 std::string &dispatch_queue_name 2329 ) 2330 { 2331 dispatch_queue_name.clear(); 2332 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2333 { 2334 // Cache the dispatch_queue_offsets_addr value so we don't always have 2335 // to look it up 2336 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2337 { 2338 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); 2339 const Symbol *dispatch_queue_offsets_symbol = NULL; 2340 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib", false))); 2341 if (module_sp) 2342 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2343 2344 if (dispatch_queue_offsets_symbol == NULL) 2345 { 2346 module_sp = GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libdispatch.dylib", false)); 2347 if (module_sp) 2348 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2349 } 2350 if (dispatch_queue_offsets_symbol) 2351 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(&m_target); 2352 2353 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2354 return NULL; 2355 } 2356 2357 uint8_t memory_buffer[8]; 2358 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize()); 2359 2360 // Excerpt from src/queue_private.h 2361 struct dispatch_queue_offsets_s 2362 { 2363 uint16_t dqo_version; 2364 uint16_t dqo_label; 2365 uint16_t dqo_label_size; 2366 } dispatch_queue_offsets; 2367 2368 2369 Error error; 2370 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2371 { 2372 uint32_t data_offset = 0; 2373 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2374 { 2375 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2376 { 2377 data_offset = 0; 2378 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2379 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2380 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2381 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2382 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2383 dispatch_queue_name.erase (bytes_read); 2384 } 2385 } 2386 } 2387 } 2388 if (dispatch_queue_name.empty()) 2389 return NULL; 2390 return dispatch_queue_name.c_str(); 2391 } 2392 2393 uint32_t 2394 ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2395 { 2396 // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 2397 // process and ask it for the list of processes. But if we are local, we can let the Host do it. 2398 if (m_local_debugserver) 2399 { 2400 return Host::ListProcessesMatchingName (name, matches, pids); 2401 } 2402 else 2403 { 2404 // FIXME: Implement talking to the remote debugserver. 2405 return 0; 2406 } 2407 2408 } 2409 2410 bool 2411 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 2412 lldb_private::StoppointCallbackContext *context, 2413 lldb::user_id_t break_id, 2414 lldb::user_id_t break_loc_id) 2415 { 2416 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 2417 // run so I can stop it if that's what I want to do. 2418 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2419 if (log) 2420 log->Printf("Hit New Thread Notification breakpoint."); 2421 return false; 2422 } 2423 2424 2425 bool 2426 ProcessGDBRemote::StartNoticingNewThreads() 2427 { 2428 static const char *bp_names[] = 2429 { 2430 "start_wqthread", 2431 "_pthread_start", 2432 NULL 2433 }; 2434 2435 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2436 size_t num_bps = m_thread_observation_bps.size(); 2437 if (num_bps != 0) 2438 { 2439 for (int i = 0; i < num_bps; i++) 2440 { 2441 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]); 2442 if (break_sp) 2443 { 2444 if (log) 2445 log->Printf("Enabled noticing new thread breakpoint."); 2446 break_sp->SetEnabled(true); 2447 } 2448 } 2449 } 2450 else 2451 { 2452 for (int i = 0; bp_names[i] != NULL; i++) 2453 { 2454 Breakpoint *breakpoint = m_target.CreateBreakpoint (NULL, bp_names[i], eFunctionNameTypeFull, true).get(); 2455 if (breakpoint) 2456 { 2457 if (log) 2458 log->Printf("Successfully created new thread notification breakpoint at \"%s\".", bp_names[i]); 2459 m_thread_observation_bps.push_back(breakpoint->GetID()); 2460 breakpoint->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 2461 } 2462 else 2463 { 2464 if (log) 2465 log->Printf("Failed to create new thread notification breakpoint."); 2466 return false; 2467 } 2468 } 2469 } 2470 2471 return true; 2472 } 2473 2474 bool 2475 ProcessGDBRemote::StopNoticingNewThreads() 2476 { 2477 size_t num_bps = m_thread_observation_bps.size(); 2478 if (num_bps != 0) 2479 { 2480 for (int i = 0; i < num_bps; i++) 2481 { 2482 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2483 2484 lldb::BreakpointSP break_sp = m_target.GetBreakpointByID(m_thread_observation_bps[i]); 2485 if (break_sp) 2486 { 2487 if (log) 2488 log->Printf ("Disabling new thread notification breakpoint."); 2489 break_sp->SetEnabled(false); 2490 } 2491 } 2492 } 2493 return true; 2494 } 2495 2496 2497