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