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