1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 #include <errno.h> 12 #include <mach/mach.h> 13 #include <mach-o/dyld.h> 14 #include <spawn.h> 15 #include <sys/fcntl.h> 16 #include <sys/types.h> 17 #include <sys/ptrace.h> 18 #include <sys/stat.h> 19 #include <sys/sysctl.h> 20 #include <unistd.h> 21 22 // C++ Includes 23 #include <algorithm> 24 #include <map> 25 26 // Other libraries and framework includes 27 28 #include "lldb/Breakpoint/WatchpointLocation.h" 29 #include "lldb/Interpreter/Args.h" 30 #include "lldb/Core/ArchSpec.h" 31 #include "lldb/Core/Debugger.h" 32 #include "lldb/Core/ConnectionFileDescriptor.h" 33 #include "lldb/Core/FileSpec.h" 34 #include "lldb/Core/InputReader.h" 35 #include "lldb/Core/Module.h" 36 #include "lldb/Core/PluginManager.h" 37 #include "lldb/Core/State.h" 38 #include "lldb/Core/StreamString.h" 39 #include "lldb/Core/Timer.h" 40 #include "lldb/Host/TimeValue.h" 41 #include "lldb/Symbol/ObjectFile.h" 42 #include "lldb/Target/DynamicLoader.h" 43 #include "lldb/Target/Target.h" 44 #include "lldb/Target/TargetList.h" 45 #include "lldb/Utility/PseudoTerminal.h" 46 47 // Project includes 48 #include "lldb/Host/Host.h" 49 #include "StringExtractorGDBRemote.h" 50 #include "GDBRemoteRegisterContext.h" 51 #include "ProcessGDBRemote.h" 52 #include "ProcessGDBRemoteLog.h" 53 #include "ThreadGDBRemote.h" 54 #include "libunwind.h" 55 #include "MacOSXLibunwindCallbacks.h" 56 57 #if defined (__i386__) || defined (__x86_64__) 58 #define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_I386_BPT 59 #define MACH_EXC_DATA0_TRACE EXC_I386_SGL 60 #elif defined (__powerpc__) || defined (__ppc__) || defined (__ppc64__) 61 #define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_PPC_BREAKPOINT 62 #elif defined (__arm__) 63 #define MACH_EXC_DATA0_SOFTWARE_BREAKPOINT EXC_ARM_BREAKPOINT 64 #endif 65 66 67 #define DEBUGSERVER_BASENAME "debugserver" 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 (reg_offset != offset) 249 { 250 reg_offset = offset; 251 } 252 } 253 else if (name.compare("encoding") == 0) 254 { 255 if (value.compare("uint") == 0) 256 reg_info.encoding = eEncodingUint; 257 else if (value.compare("sint") == 0) 258 reg_info.encoding = eEncodingSint; 259 else if (value.compare("ieee754") == 0) 260 reg_info.encoding = eEncodingIEEE754; 261 else if (value.compare("vector") == 0) 262 reg_info.encoding = eEncodingVector; 263 } 264 else if (name.compare("format") == 0) 265 { 266 if (value.compare("binary") == 0) 267 reg_info.format = eFormatBinary; 268 else if (value.compare("decimal") == 0) 269 reg_info.format = eFormatDecimal; 270 else if (value.compare("hex") == 0) 271 reg_info.format = eFormatHex; 272 else if (value.compare("float") == 0) 273 reg_info.format = eFormatFloat; 274 else if (value.compare("vector-sint8") == 0) 275 reg_info.format = eFormatVectorOfSInt8; 276 else if (value.compare("vector-uint8") == 0) 277 reg_info.format = eFormatVectorOfUInt8; 278 else if (value.compare("vector-sint16") == 0) 279 reg_info.format = eFormatVectorOfSInt16; 280 else if (value.compare("vector-uint16") == 0) 281 reg_info.format = eFormatVectorOfUInt16; 282 else if (value.compare("vector-sint32") == 0) 283 reg_info.format = eFormatVectorOfSInt32; 284 else if (value.compare("vector-uint32") == 0) 285 reg_info.format = eFormatVectorOfUInt32; 286 else if (value.compare("vector-float32") == 0) 287 reg_info.format = eFormatVectorOfFloat32; 288 else if (value.compare("vector-uint128") == 0) 289 reg_info.format = eFormatVectorOfUInt128; 290 } 291 else if (name.compare("set") == 0) 292 { 293 set_name.SetCString(value.c_str()); 294 } 295 else if (name.compare("gcc") == 0) 296 { 297 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 298 } 299 else if (name.compare("dwarf") == 0) 300 { 301 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 302 } 303 else if (name.compare("generic") == 0) 304 { 305 if (value.compare("pc") == 0) 306 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; 307 else if (value.compare("sp") == 0) 308 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP; 309 else if (value.compare("fp") == 0) 310 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP; 311 else if (value.compare("ra") == 0) 312 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA; 313 else if (value.compare("flags") == 0) 314 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS; 315 } 316 } 317 318 reg_info.byte_offset = reg_offset; 319 assert (reg_info.byte_size != 0); 320 reg_offset += reg_info.byte_size; 321 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 322 } 323 } 324 else 325 { 326 packet_type = StringExtractorGDBRemote::eError; 327 } 328 } 329 330 if (reg_num == 0) 331 { 332 // We didn't get anything. See if we are debugging ARM and fill with 333 // a hard coded register set until we can get an updated debugserver 334 // down on the devices. 335 ArchSpec arm_arch ("arm"); 336 if (GetTarget().GetArchitecture() == arm_arch) 337 m_register_info.HardcodeARMRegisters(); 338 } 339 m_register_info.Finalize (); 340 } 341 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 ArchSpec::CPU arch_cpu = m_arch_spec.GetGenericCPUType(); 879 switch (arch_cpu) 880 { 881 case ArchSpec::eCPU_i386: 882 case ArchSpec::eCPU_x86_64: 883 trap_opcode = g_i386_breakpoint_opcode; 884 trap_opcode_size = sizeof(g_i386_breakpoint_opcode); 885 break; 886 887 case ArchSpec::eCPU_arm: 888 // TODO: fill this in for ARM. We need to dig up the symbol for 889 // the address in the breakpoint locaiton and figure out if it is 890 // an ARM or Thumb breakpoint. 891 trap_opcode = g_arm_breakpoint_opcode; 892 trap_opcode_size = sizeof(g_arm_breakpoint_opcode); 893 break; 894 895 case ArchSpec::eCPU_ppc: 896 case ArchSpec::eCPU_ppc64: 897 trap_opcode = g_ppc_breakpoint_opcode; 898 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode); 899 break; 900 901 default: 902 assert(!"Unhandled architecture in ProcessMacOSX::GetSoftwareBreakpointTrapOpcode()"); 903 break; 904 } 905 906 if (trap_opcode && trap_opcode_size) 907 { 908 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size)) 909 return trap_opcode_size; 910 } 911 return 0; 912 } 913 914 uint32_t 915 ProcessGDBRemote::UpdateThreadListIfNeeded () 916 { 917 // locker will keep a mutex locked until it goes out of scope 918 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD); 919 if (log && log->GetMask().IsSet(GDBR_LOG_VERBOSE)) 920 log->Printf ("ProcessGDBRemote::%s (pid = %i)", __FUNCTION__, GetID()); 921 922 const uint32_t stop_id = GetStopID(); 923 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 924 { 925 // Update the thread list's stop id immediately so we don't recurse into this function. 926 ThreadList curr_thread_list (this); 927 curr_thread_list.SetStopID(stop_id); 928 929 Error err; 930 StringExtractorGDBRemote response; 931 for (m_gdb_comm.SendPacketAndWaitForResponse("qfThreadInfo", response, 1, false); 932 response.IsNormalPacket(); 933 m_gdb_comm.SendPacketAndWaitForResponse("qsThreadInfo", response, 1, false)) 934 { 935 char ch = response.GetChar(); 936 if (ch == 'l') 937 break; 938 if (ch == 'm') 939 { 940 do 941 { 942 tid_t tid = response.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID); 943 944 if (tid != LLDB_INVALID_THREAD_ID) 945 { 946 ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false)); 947 if (thread_sp) 948 thread_sp->GetRegisterContext()->Invalidate(); 949 else 950 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 951 curr_thread_list.AddThread(thread_sp); 952 } 953 954 ch = response.GetChar(); 955 } while (ch == ','); 956 } 957 } 958 959 m_thread_list = curr_thread_list; 960 961 SetThreadStopInfo (m_last_stop_packet); 962 } 963 return GetThreadList().GetSize(false); 964 } 965 966 967 StateType 968 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 969 { 970 const char stop_type = stop_packet.GetChar(); 971 switch (stop_type) 972 { 973 case 'T': 974 case 'S': 975 { 976 // Stop with signal and thread info 977 const uint8_t signo = stop_packet.GetHexU8(); 978 std::string name; 979 std::string value; 980 std::string thread_name; 981 uint32_t exc_type = 0; 982 std::vector<uint64_t> exc_data; 983 uint32_t tid = LLDB_INVALID_THREAD_ID; 984 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 985 uint32_t exc_data_count = 0; 986 while (stop_packet.GetNameColonValue(name, value)) 987 { 988 if (name.compare("metype") == 0) 989 { 990 // exception type in big endian hex 991 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 992 } 993 else if (name.compare("mecount") == 0) 994 { 995 // exception count in big endian hex 996 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16); 997 } 998 else if (name.compare("medata") == 0) 999 { 1000 // exception data in big endian hex 1001 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1002 } 1003 else if (name.compare("thread") == 0) 1004 { 1005 // thread in big endian hex 1006 tid = Args::StringToUInt32 (value.c_str(), 0, 16); 1007 } 1008 else if (name.compare("name") == 0) 1009 { 1010 thread_name.swap (value); 1011 } 1012 else if (name.compare("dispatchqaddr") == 0) 1013 { 1014 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1015 } 1016 } 1017 ThreadSP thread_sp (m_thread_list.FindThreadByID(tid, false)); 1018 1019 if (thread_sp) 1020 { 1021 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1022 1023 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1024 gdb_thread->SetName (thread_name.empty() ? thread_name.c_str() : NULL); 1025 Thread::StopInfo& stop_info = gdb_thread->GetStopInfoRef(); 1026 gdb_thread->SetStopInfoStopID (GetStopID()); 1027 if (exc_type != 0) 1028 { 1029 if (exc_type == EXC_SOFTWARE && exc_data.size() == 2 && exc_data[0] == EXC_SOFT_SIGNAL) 1030 { 1031 stop_info.SetStopReasonWithSignal(exc_data[1]); 1032 } 1033 #if defined (MACH_EXC_DATA0_SOFTWARE_BREAKPOINT) 1034 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_SOFTWARE_BREAKPOINT) 1035 { 1036 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1037 lldb::BreakpointSiteSP bp_site_sp = GetBreakpointSiteList().FindByAddress(pc); 1038 if (!bp_site_sp) 1039 { 1040 //log->Printf("got EXC_BREAKPOINT at 0x%llx but didn't find a breakpoint site.\n", pc); 1041 stop_info.SetStopReasonWithException(exc_type, exc_data.size()); 1042 for (uint32_t i=0; i<exc_data.size(); ++i) 1043 stop_info.SetExceptionDataAtIndex(i, exc_data[i]); 1044 } 1045 else 1046 { 1047 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1048 { 1049 stop_info.Clear (); 1050 stop_info.SetStopReasonWithBreakpointSiteID (bp_site_sp->GetID()); 1051 } 1052 else 1053 { 1054 stop_info.Clear (); 1055 stop_info.SetStopReasonToNone(); 1056 } 1057 1058 } 1059 } 1060 #endif 1061 #if defined (MACH_EXC_DATA0_TRACE) 1062 else if (exc_type == EXC_BREAKPOINT && exc_data[0] == MACH_EXC_DATA0_TRACE) 1063 { 1064 stop_info.SetStopReasonToTrace (); 1065 } 1066 #endif 1067 else 1068 { 1069 stop_info.SetStopReasonWithException(exc_type, exc_data.size()); 1070 for (uint32_t i=0; i<exc_data.size(); ++i) 1071 stop_info.SetExceptionDataAtIndex(i, exc_data[i]); 1072 } 1073 } 1074 else if (signo) 1075 { 1076 stop_info.SetStopReasonWithSignal(signo); 1077 } 1078 else 1079 { 1080 stop_info.SetStopReasonToNone(); 1081 } 1082 } 1083 return eStateStopped; 1084 } 1085 break; 1086 1087 case 'W': 1088 // process exited 1089 return eStateExited; 1090 1091 default: 1092 break; 1093 } 1094 return eStateInvalid; 1095 } 1096 1097 void 1098 ProcessGDBRemote::RefreshStateAfterStop () 1099 { 1100 // We must be attaching if we don't already have a valid architecture 1101 if (!m_arch_spec.IsValid()) 1102 { 1103 Module *exe_module = GetTarget().GetExecutableModule().get(); 1104 if (exe_module) 1105 m_arch_spec = exe_module->GetArchitecture(); 1106 } 1107 // Let all threads recover from stopping and do any clean up based 1108 // on the previous thread state (if any). 1109 m_thread_list.RefreshStateAfterStop(); 1110 1111 // Discover new threads: 1112 UpdateThreadListIfNeeded (); 1113 } 1114 1115 Error 1116 ProcessGDBRemote::DoHalt () 1117 { 1118 Error error; 1119 if (m_gdb_comm.IsRunning()) 1120 { 1121 bool timed_out = false; 1122 if (!m_gdb_comm.SendInterrupt (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 const StateType state = m_private_state.GetValue(); 1138 1139 if (IsRunning(state)) 1140 error.SetErrorString("Process must be stopped in order to detach."); 1141 1142 return error; 1143 } 1144 1145 1146 Error 1147 ProcessGDBRemote::DoDestroy () 1148 { 1149 Error error; 1150 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1151 if (log) 1152 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1153 1154 // Interrupt if our inferior is running... 1155 m_gdb_comm.SendInterrupt (1); 1156 DisableAllBreakpointSites (); 1157 SetExitStatus(-1, "process killed"); 1158 1159 StringExtractorGDBRemote response; 1160 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2, false)) 1161 { 1162 if (log) 1163 { 1164 if (response.IsOKPacket()) 1165 log->Printf ("ProcessGDBRemote::DoDestroy() kill was successful"); 1166 else 1167 log->Printf ("ProcessGDBRemote::DoDestroy() kill failed: %s", response.GetStringRef().c_str()); 1168 } 1169 } 1170 1171 StopAsyncThread (); 1172 m_gdb_comm.StopReadThread(); 1173 KillDebugserverProcess (); 1174 return error; 1175 } 1176 1177 ByteOrder 1178 ProcessGDBRemote::GetByteOrder () const 1179 { 1180 return m_byte_order; 1181 } 1182 1183 //------------------------------------------------------------------ 1184 // Process Queries 1185 //------------------------------------------------------------------ 1186 1187 bool 1188 ProcessGDBRemote::IsAlive () 1189 { 1190 return m_gdb_comm.IsConnected(); 1191 } 1192 1193 addr_t 1194 ProcessGDBRemote::GetImageInfoAddress() 1195 { 1196 if (!m_gdb_comm.IsRunning()) 1197 { 1198 StringExtractorGDBRemote response; 1199 if (m_gdb_comm.SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, 2, false)) 1200 { 1201 if (response.IsNormalPacket()) 1202 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1203 } 1204 } 1205 return LLDB_INVALID_ADDRESS; 1206 } 1207 1208 DynamicLoader * 1209 ProcessGDBRemote::GetDynamicLoader() 1210 { 1211 return m_dynamic_loader_ap.get(); 1212 } 1213 1214 //------------------------------------------------------------------ 1215 // Process Memory 1216 //------------------------------------------------------------------ 1217 size_t 1218 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1219 { 1220 if (size > m_max_memory_size) 1221 { 1222 // Keep memory read sizes down to a sane limit. This function will be 1223 // called multiple times in order to complete the task by 1224 // lldb_private::Process so it is ok to do this. 1225 size = m_max_memory_size; 1226 } 1227 1228 char packet[64]; 1229 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1230 assert (packet_len + 1 < sizeof(packet)); 1231 StringExtractorGDBRemote response; 1232 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1233 { 1234 if (response.IsNormalPacket()) 1235 { 1236 error.Clear(); 1237 return response.GetHexBytes(buf, size, '\xdd'); 1238 } 1239 else if (response.IsErrorPacket()) 1240 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1241 else if (response.IsUnsupportedPacket()) 1242 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1243 else 1244 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1245 } 1246 else 1247 { 1248 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1249 } 1250 return 0; 1251 } 1252 1253 size_t 1254 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1255 { 1256 StreamString packet; 1257 packet.Printf("M%llx,%zx:", addr, size); 1258 packet.PutBytesAsRawHex8(buf, size, eByteOrderHost, eByteOrderHost); 1259 StringExtractorGDBRemote response; 1260 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, 2, true)) 1261 { 1262 if (response.IsOKPacket()) 1263 { 1264 error.Clear(); 1265 return size; 1266 } 1267 else if (response.IsErrorPacket()) 1268 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1269 else if (response.IsUnsupportedPacket()) 1270 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1271 else 1272 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1273 } 1274 else 1275 { 1276 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1277 } 1278 return 0; 1279 } 1280 1281 lldb::addr_t 1282 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1283 { 1284 addr_t allocated_addr = m_gdb_comm.AllocateMemory (size, permissions, m_packet_timeout); 1285 if (allocated_addr == LLDB_INVALID_ADDRESS) 1286 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %u", size, permissions); 1287 else 1288 error.Clear(); 1289 return allocated_addr; 1290 } 1291 1292 Error 1293 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 1294 { 1295 Error error; 1296 if (!m_gdb_comm.DeallocateMemory (addr, m_packet_timeout)) 1297 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 1298 return error; 1299 } 1300 1301 1302 //------------------------------------------------------------------ 1303 // Process STDIO 1304 //------------------------------------------------------------------ 1305 1306 size_t 1307 ProcessGDBRemote::GetSTDOUT (char *buf, size_t buf_size, Error &error) 1308 { 1309 Mutex::Locker locker(m_stdio_mutex); 1310 size_t bytes_available = m_stdout_data.size(); 1311 if (bytes_available > 0) 1312 { 1313 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (&%p[%u]) ...", __FUNCTION__, buf, buf_size); 1314 if (bytes_available > buf_size) 1315 { 1316 memcpy(buf, m_stdout_data.data(), buf_size); 1317 m_stdout_data.erase(0, buf_size); 1318 bytes_available = buf_size; 1319 } 1320 else 1321 { 1322 memcpy(buf, m_stdout_data.data(), bytes_available); 1323 m_stdout_data.clear(); 1324 1325 //ResetEventBits(eBroadcastBitSTDOUT); 1326 } 1327 } 1328 return bytes_available; 1329 } 1330 1331 size_t 1332 ProcessGDBRemote::GetSTDERR (char *buf, size_t buf_size, Error &error) 1333 { 1334 // Can we get STDERR through the remote protocol? 1335 return 0; 1336 } 1337 1338 size_t 1339 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 1340 { 1341 if (m_stdio_communication.IsConnected()) 1342 { 1343 ConnectionStatus status; 1344 m_stdio_communication.Write(src, src_len, status, NULL); 1345 } 1346 return 0; 1347 } 1348 1349 Error 1350 ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 1351 { 1352 Error error; 1353 assert (bp_site != NULL); 1354 1355 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS); 1356 user_id_t site_id = bp_site->GetID(); 1357 const addr_t addr = bp_site->GetLoadAddress(); 1358 if (log) 1359 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx", site_id, (uint64_t)addr); 1360 1361 if (bp_site->IsEnabled()) 1362 { 1363 if (log) 1364 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %d) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 1365 return error; 1366 } 1367 else 1368 { 1369 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1370 1371 if (bp_site->HardwarePreferred()) 1372 { 1373 // Try and set hardware breakpoint, and if that fails, fall through 1374 // and set a software breakpoint? 1375 } 1376 1377 if (m_z0_supported) 1378 { 1379 char packet[64]; 1380 const int packet_len = ::snprintf (packet, sizeof(packet), "Z0,%llx,%zx", addr, bp_op_size); 1381 assert (packet_len + 1 < sizeof(packet)); 1382 StringExtractorGDBRemote response; 1383 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1384 { 1385 if (response.IsUnsupportedPacket()) 1386 { 1387 // Disable z packet support and try again 1388 m_z0_supported = 0; 1389 return EnableBreakpoint (bp_site); 1390 } 1391 else if (response.IsOKPacket()) 1392 { 1393 bp_site->SetEnabled(true); 1394 bp_site->SetType (BreakpointSite::eExternal); 1395 return error; 1396 } 1397 else 1398 { 1399 uint8_t error_byte = response.GetError(); 1400 if (error_byte) 1401 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1402 } 1403 } 1404 } 1405 else 1406 { 1407 return EnableSoftwareBreakpoint (bp_site); 1408 } 1409 } 1410 1411 if (log) 1412 { 1413 const char *err_string = error.AsCString(); 1414 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 1415 bp_site->GetLoadAddress(), 1416 err_string ? err_string : "NULL"); 1417 } 1418 // We shouldn't reach here on a successful breakpoint enable... 1419 if (error.Success()) 1420 error.SetErrorToGenericError(); 1421 return error; 1422 } 1423 1424 Error 1425 ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 1426 { 1427 Error error; 1428 assert (bp_site != NULL); 1429 addr_t addr = bp_site->GetLoadAddress(); 1430 user_id_t site_id = bp_site->GetID(); 1431 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS); 1432 if (log) 1433 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx", site_id, (uint64_t)addr); 1434 1435 if (bp_site->IsEnabled()) 1436 { 1437 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 1438 1439 if (bp_site->IsHardware()) 1440 { 1441 // TODO: disable hardware breakpoint... 1442 } 1443 else 1444 { 1445 if (m_z0_supported) 1446 { 1447 char packet[64]; 1448 const int packet_len = ::snprintf (packet, sizeof(packet), "z0,%llx,%zx", addr, bp_op_size); 1449 assert (packet_len + 1 < sizeof(packet)); 1450 StringExtractorGDBRemote response; 1451 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, true)) 1452 { 1453 if (response.IsUnsupportedPacket()) 1454 { 1455 error.SetErrorString("Breakpoint site was set with Z packet, yet remote debugserver states z packets are not supported."); 1456 } 1457 else if (response.IsOKPacket()) 1458 { 1459 if (log) 1460 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS", site_id, (uint64_t)addr); 1461 bp_site->SetEnabled(false); 1462 return error; 1463 } 1464 else 1465 { 1466 uint8_t error_byte = response.GetError(); 1467 if (error_byte) 1468 error.SetErrorStringWithFormat("%x packet failed with error: %i (0x%2.2x).\n", packet, error_byte, error_byte); 1469 } 1470 } 1471 } 1472 else 1473 { 1474 return DisableSoftwareBreakpoint (bp_site); 1475 } 1476 } 1477 } 1478 else 1479 { 1480 if (log) 1481 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %d) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 1482 return error; 1483 } 1484 1485 if (error.Success()) 1486 error.SetErrorToGenericError(); 1487 return error; 1488 } 1489 1490 Error 1491 ProcessGDBRemote::EnableWatchpoint (WatchpointLocation *wp) 1492 { 1493 Error error; 1494 if (wp) 1495 { 1496 user_id_t watchID = wp->GetID(); 1497 addr_t addr = wp->GetLoadAddress(); 1498 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS); 1499 if (log) 1500 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %d)", watchID); 1501 if (wp->IsEnabled()) 1502 { 1503 if (log) 1504 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 1505 return error; 1506 } 1507 else 1508 { 1509 // Pass down an appropriate z/Z packet... 1510 error.SetErrorString("watchpoints not supported"); 1511 } 1512 } 1513 else 1514 { 1515 error.SetErrorString("Watchpoint location argument was NULL."); 1516 } 1517 if (error.Success()) 1518 error.SetErrorToGenericError(); 1519 return error; 1520 } 1521 1522 Error 1523 ProcessGDBRemote::DisableWatchpoint (WatchpointLocation *wp) 1524 { 1525 Error error; 1526 if (wp) 1527 { 1528 user_id_t watchID = wp->GetID(); 1529 1530 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS); 1531 1532 addr_t addr = wp->GetLoadAddress(); 1533 if (log) 1534 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %d) addr = 0x%8.8llx", watchID, (uint64_t)addr); 1535 1536 if (wp->IsHardware()) 1537 { 1538 // Pass down an appropriate z/Z packet... 1539 error.SetErrorString("watchpoints not supported"); 1540 } 1541 // TODO: clear software watchpoints if we implement them 1542 } 1543 else 1544 { 1545 error.SetErrorString("Watchpoint location argument was NULL."); 1546 } 1547 if (error.Success()) 1548 error.SetErrorToGenericError(); 1549 return error; 1550 } 1551 1552 void 1553 ProcessGDBRemote::Clear() 1554 { 1555 m_flags = 0; 1556 m_thread_list.Clear(); 1557 { 1558 Mutex::Locker locker(m_stdio_mutex); 1559 m_stdout_data.clear(); 1560 } 1561 DestoryLibUnwindAddressSpace(); 1562 } 1563 1564 Error 1565 ProcessGDBRemote::DoSignal (int signo) 1566 { 1567 Error error; 1568 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1569 if (log) 1570 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 1571 1572 if (!m_gdb_comm.SendAsyncSignal (signo)) 1573 error.SetErrorStringWithFormat("failed to send signal %i", signo); 1574 return error; 1575 } 1576 1577 1578 Error 1579 ProcessGDBRemote::DoDetach() 1580 { 1581 Error error; 1582 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 1583 if (log) 1584 log->Printf ("ProcessGDBRemote::DoDetach()"); 1585 1586 // if (DoSIGSTOP (true)) 1587 // { 1588 // CloseChildFileDescriptors (); 1589 // 1590 // // Scope for "locker" so we can reply to all of our exceptions (the SIGSTOP 1591 // // exception). 1592 // { 1593 // Mutex::Locker locker(m_exception_messages_mutex); 1594 // ReplyToAllExceptions(); 1595 // } 1596 // 1597 // // Shut down the exception thread and cleanup our exception remappings 1598 // Task().ShutDownExceptionThread(); 1599 // 1600 // pid_t pid = GetID(); 1601 // 1602 // // Detach from our process while we are stopped. 1603 // errno = 0; 1604 // 1605 // // Detach from our process 1606 // ::ptrace (PT_DETACH, pid, (caddr_t)1, 0); 1607 // 1608 // error.SetErrorToErrno(); 1609 // 1610 // if (log || error.Fail()) 1611 // error.PutToLog(log, "::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid); 1612 // 1613 // // Resume our task 1614 // Task().Resume(); 1615 // 1616 // // NULL our task out as we have already retored all exception ports 1617 // Task().Clear(); 1618 // 1619 // // Clear out any notion of the process we once were 1620 // Clear(); 1621 // 1622 // SetPrivateState (eStateDetached); 1623 // return true; 1624 // } 1625 return error; 1626 } 1627 1628 void 1629 ProcessGDBRemote::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 1630 { 1631 ProcessGDBRemote *process = (ProcessGDBRemote *)baton; 1632 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 1633 } 1634 1635 void 1636 ProcessGDBRemote::AppendSTDOUT (const char* s, size_t len) 1637 { 1638 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PROCESS, "ProcessGDBRemote::%s (<%d> %s) ...", __FUNCTION__, len, s); 1639 Mutex::Locker locker(m_stdio_mutex); 1640 m_stdout_data.append(s, len); 1641 1642 // FIXME: Make a real data object for this and put it out. 1643 BroadcastEventIfUnique (eBroadcastBitSTDOUT); 1644 } 1645 1646 1647 Error 1648 ProcessGDBRemote::StartDebugserverProcess 1649 ( 1650 const char *debugserver_url, // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 1651 char const *inferior_argv[], // Arguments for the inferior program including the path to the inferior itself as the first argument 1652 char const *inferior_envp[], // Environment to pass along to the inferior program 1653 char const *stdio_path, 1654 lldb::pid_t attach_pid, // If inferior inferior_argv == NULL, and attach_pid != LLDB_INVALID_PROCESS_ID then attach to this attach_pid 1655 const char *attach_name, // Wait for the next process to launch whose basename matches "attach_name" 1656 bool wait_for_launch, // Wait for the process named "attach_name" to launch 1657 ArchSpec& inferior_arch // The arch of the inferior that we will launch 1658 ) 1659 { 1660 Error error; 1661 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 1662 { 1663 // If we locate debugserver, keep that located version around 1664 static FileSpec g_debugserver_file_spec; 1665 1666 FileSpec debugserver_file_spec; 1667 char debugserver_path[PATH_MAX]; 1668 1669 // Always check to see if we have an environment override for the path 1670 // to the debugserver to use and use it if we do. 1671 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 1672 if (env_debugserver_path) 1673 debugserver_file_spec.SetFile (env_debugserver_path); 1674 else 1675 debugserver_file_spec = g_debugserver_file_spec; 1676 bool debugserver_exists = debugserver_file_spec.Exists(); 1677 if (!debugserver_exists) 1678 { 1679 // The debugserver binary is in the LLDB.framework/Resources 1680 // directory. 1681 FileSpec framework_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)lldb_private::Initialize)); 1682 const char *framework_dir = framework_file_spec.GetDirectory().AsCString(); 1683 const char *lldb_framework = ::strstr (framework_dir, "/LLDB.framework"); 1684 1685 if (lldb_framework) 1686 { 1687 int len = lldb_framework - framework_dir + strlen ("/LLDB.framework"); 1688 ::snprintf (debugserver_path, 1689 sizeof(debugserver_path), 1690 "%.*s/Resources/%s", 1691 len, 1692 framework_dir, 1693 DEBUGSERVER_BASENAME); 1694 debugserver_file_spec.SetFile (debugserver_path); 1695 debugserver_exists = debugserver_file_spec.Exists(); 1696 } 1697 1698 if (debugserver_exists) 1699 { 1700 g_debugserver_file_spec = debugserver_file_spec; 1701 } 1702 else 1703 { 1704 g_debugserver_file_spec.Clear(); 1705 debugserver_file_spec.Clear(); 1706 } 1707 } 1708 1709 if (debugserver_exists) 1710 { 1711 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 1712 1713 m_stdio_communication.Clear(); 1714 posix_spawnattr_t attr; 1715 1716 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 1717 1718 Error local_err; // Errors that don't affect the spawning. 1719 if (log) 1720 log->Printf ("%s ( path='%s', argv=%p, envp=%p, arch=%s )", __FUNCTION__, debugserver_path, inferior_argv, inferior_envp, inferior_arch.AsCString()); 1721 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX); 1722 if (error.Fail() || log) 1723 error.PutToLog(log, "::posix_spawnattr_init ( &attr )"); 1724 if (error.Fail()) 1725 return error;; 1726 1727 #if !defined (__arm__) 1728 1729 // We don't need to do this for ARM, and we really shouldn't now that we 1730 // have multiple CPU subtypes and no posix_spawnattr call that allows us 1731 // to set which CPU subtype to launch... 1732 if (inferior_arch.GetType() == eArchTypeMachO) 1733 { 1734 cpu_type_t cpu = inferior_arch.GetCPUType(); 1735 if (cpu != 0 && cpu != UINT32_MAX && cpu != LLDB_INVALID_CPUTYPE) 1736 { 1737 size_t ocount = 0; 1738 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX); 1739 if (error.Fail() || log) 1740 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu, ocount); 1741 1742 if (error.Fail() != 0 || ocount != 1) 1743 return error; 1744 } 1745 } 1746 1747 #endif 1748 1749 Args debugserver_args; 1750 char arg_cstr[PATH_MAX]; 1751 bool launch_process = true; 1752 1753 if (inferior_argv == NULL && attach_pid != LLDB_INVALID_PROCESS_ID) 1754 launch_process = false; 1755 else if (attach_name) 1756 launch_process = false; // Wait for a process whose basename matches that in inferior_argv[0] 1757 1758 bool pass_stdio_path_to_debugserver = true; 1759 lldb_utility::PseudoTerminal pty; 1760 if (stdio_path == NULL) 1761 { 1762 pass_stdio_path_to_debugserver = false; 1763 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 1764 { 1765 struct termios stdin_termios; 1766 if (::tcgetattr (pty.GetMasterFileDescriptor(), &stdin_termios) == 0) 1767 { 1768 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing 1769 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time 1770 ::tcsetattr (pty.GetMasterFileDescriptor(), TCSANOW, &stdin_termios); 1771 } 1772 stdio_path = pty.GetSlaveName (NULL, 0); 1773 } 1774 } 1775 1776 // Start args with "debugserver /file/path -r --" 1777 debugserver_args.AppendArgument(debugserver_path); 1778 debugserver_args.AppendArgument(debugserver_url); 1779 debugserver_args.AppendArgument("--native-regs"); // use native registers, not the GDB registers 1780 debugserver_args.AppendArgument("--setsid"); // make debugserver run in its own session so 1781 // signals generated by special terminal key 1782 // sequences (^C) don't affect debugserver 1783 1784 // Only set the inferior 1785 if (launch_process) 1786 { 1787 if (stdio_path && pass_stdio_path_to_debugserver) 1788 { 1789 debugserver_args.AppendArgument("-s"); // short for --stdio-path 1790 StreamString strm; 1791 strm.Printf("'%s'", stdio_path); 1792 debugserver_args.AppendArgument(strm.GetData()); // path to file to have inferior open as it's STDIO 1793 } 1794 } 1795 1796 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 1797 if (env_debugserver_log_file) 1798 { 1799 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 1800 debugserver_args.AppendArgument(arg_cstr); 1801 } 1802 1803 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 1804 if (env_debugserver_log_flags) 1805 { 1806 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 1807 debugserver_args.AppendArgument(arg_cstr); 1808 } 1809 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 1810 // debugserver_args.AppendArgument("--log-flags=0x800e0e"); 1811 1812 // Now append the program arguments 1813 if (launch_process) 1814 { 1815 if (inferior_argv) 1816 { 1817 // Terminate the debugserver args so we can now append the inferior args 1818 debugserver_args.AppendArgument("--"); 1819 1820 for (int i = 0; inferior_argv[i] != NULL; ++i) 1821 debugserver_args.AppendArgument (inferior_argv[i]); 1822 } 1823 else 1824 { 1825 // Will send environment entries with the 'QEnvironment:' packet 1826 // Will send arguments with the 'A' packet 1827 } 1828 } 1829 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 1830 { 1831 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 1832 debugserver_args.AppendArgument (arg_cstr); 1833 } 1834 else if (attach_name && attach_name[0]) 1835 { 1836 if (wait_for_launch) 1837 debugserver_args.AppendArgument ("--waitfor"); 1838 else 1839 debugserver_args.AppendArgument ("--attach"); 1840 debugserver_args.AppendArgument (attach_name); 1841 } 1842 1843 Error file_actions_err; 1844 posix_spawn_file_actions_t file_actions; 1845 #if DONT_CLOSE_DEBUGSERVER_STDIO 1846 file_actions_err.SetErrorString ("Remove this after uncommenting the code block below."); 1847 #else 1848 file_actions_err.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX); 1849 if (file_actions_err.Success()) 1850 { 1851 ::posix_spawn_file_actions_addclose (&file_actions, STDIN_FILENO); 1852 ::posix_spawn_file_actions_addclose (&file_actions, STDOUT_FILENO); 1853 ::posix_spawn_file_actions_addclose (&file_actions, STDERR_FILENO); 1854 } 1855 #endif 1856 1857 if (log) 1858 { 1859 StreamString strm; 1860 debugserver_args.Dump (&strm); 1861 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 1862 } 1863 1864 error.SetError(::posix_spawnp (&m_debugserver_pid, 1865 debugserver_path, 1866 file_actions_err.Success() ? &file_actions : NULL, 1867 &attr, 1868 debugserver_args.GetArgumentVector(), 1869 (char * const*)inferior_envp), 1870 eErrorTypePOSIX); 1871 1872 if (file_actions_err.Success()) 1873 ::posix_spawn_file_actions_destroy (&file_actions); 1874 1875 // We have seen some cases where posix_spawnp was returning a valid 1876 // looking pid even when an error was returned, so clear it out 1877 if (error.Fail()) 1878 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1879 1880 if (error.Fail() || log) 1881 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); 1882 1883 // if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1884 // { 1885 // std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor (pty.ReleaseMasterFileDescriptor(), true)); 1886 // if (conn_ap.get()) 1887 // { 1888 // m_stdio_communication.SetConnection(conn_ap.release()); 1889 // if (m_stdio_communication.IsConnected()) 1890 // { 1891 // m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 1892 // m_stdio_communication.StartReadThread(); 1893 // } 1894 // } 1895 // } 1896 } 1897 else 1898 { 1899 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n"); 1900 } 1901 1902 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1903 StartAsyncThread (); 1904 } 1905 return error; 1906 } 1907 1908 bool 1909 ProcessGDBRemote::MonitorDebugserverProcess 1910 ( 1911 void *callback_baton, 1912 lldb::pid_t debugserver_pid, 1913 int signo, // Zero for no signal 1914 int exit_status // Exit value of process if signal is zero 1915 ) 1916 { 1917 // We pass in the ProcessGDBRemote inferior process it and name it 1918 // "gdb_remote_pid". The process ID is passed in the "callback_baton" 1919 // pointer value itself, thus we need the double cast... 1920 1921 // "debugserver_pid" argument passed in is the process ID for 1922 // debugserver that we are tracking... 1923 1924 lldb::pid_t gdb_remote_pid = (lldb::pid_t)(intptr_t)callback_baton; 1925 TargetSP target_sp(Debugger::FindTargetWithProcessID (gdb_remote_pid)); 1926 if (target_sp) 1927 { 1928 ProcessSP process_sp (target_sp->GetProcessSP()); 1929 if (process_sp) 1930 { 1931 // Sleep for a half a second to make sure our inferior process has 1932 // time to set its exit status before we set it incorrectly when 1933 // both the debugserver and the inferior process shut down. 1934 usleep (500000); 1935 // If our process hasn't yet exited, debugserver might have died. 1936 // If the process did exit, the we are reaping it. 1937 if (process_sp->GetState() != eStateExited) 1938 { 1939 char error_str[1024]; 1940 if (signo) 1941 { 1942 const char *signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1943 if (signal_cstr) 1944 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 1945 else 1946 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 1947 } 1948 else 1949 { 1950 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 1951 } 1952 1953 process_sp->SetExitStatus (-1, error_str); 1954 } 1955 else 1956 { 1957 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)process_sp.get(); 1958 // Debugserver has exited we need to let our ProcessGDBRemote 1959 // know that it no longer has a debugserver instance 1960 gdb_process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1961 // We are returning true to this function below, so we can 1962 // forget about the monitor handle. 1963 gdb_process->m_debugserver_monitor = 0; 1964 } 1965 } 1966 } 1967 return true; 1968 } 1969 1970 void 1971 ProcessGDBRemote::KillDebugserverProcess () 1972 { 1973 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 1974 { 1975 ::kill (m_debugserver_pid, SIGINT); 1976 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 1977 } 1978 } 1979 1980 void 1981 ProcessGDBRemote::Initialize() 1982 { 1983 static bool g_initialized = false; 1984 1985 if (g_initialized == false) 1986 { 1987 g_initialized = true; 1988 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1989 GetPluginDescriptionStatic(), 1990 CreateInstance); 1991 1992 Log::Callbacks log_callbacks = { 1993 ProcessGDBRemoteLog::DisableLog, 1994 ProcessGDBRemoteLog::EnableLog, 1995 ProcessGDBRemoteLog::ListLogCategories 1996 }; 1997 1998 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 1999 } 2000 } 2001 2002 bool 2003 ProcessGDBRemote::SetCurrentGDBRemoteThread (int tid) 2004 { 2005 if (m_curr_tid == tid) 2006 return true; 2007 2008 char packet[32]; 2009 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 2010 assert (packet_len + 1 < sizeof(packet)); 2011 StringExtractorGDBRemote response; 2012 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2013 { 2014 if (response.IsOKPacket()) 2015 { 2016 m_curr_tid = tid; 2017 return true; 2018 } 2019 } 2020 return false; 2021 } 2022 2023 bool 2024 ProcessGDBRemote::SetCurrentGDBRemoteThreadForRun (int tid) 2025 { 2026 if (m_curr_tid_run == tid) 2027 return true; 2028 2029 char packet[32]; 2030 const int packet_len = ::snprintf (packet, sizeof(packet), "Hg%x", tid); 2031 assert (packet_len + 1 < sizeof(packet)); 2032 StringExtractorGDBRemote response; 2033 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, 2, false)) 2034 { 2035 if (response.IsOKPacket()) 2036 { 2037 m_curr_tid_run = tid; 2038 return true; 2039 } 2040 } 2041 return false; 2042 } 2043 2044 void 2045 ProcessGDBRemote::ResetGDBRemoteState () 2046 { 2047 // Reset and GDB remote state 2048 m_curr_tid = LLDB_INVALID_THREAD_ID; 2049 m_curr_tid_run = LLDB_INVALID_THREAD_ID; 2050 m_z0_supported = 1; 2051 } 2052 2053 2054 bool 2055 ProcessGDBRemote::StartAsyncThread () 2056 { 2057 ResetGDBRemoteState (); 2058 2059 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 2060 2061 if (log) 2062 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2063 2064 // Create a thread that watches our internal state and controls which 2065 // events make it to clients (into the DCProcess event queue). 2066 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2067 return m_async_thread != LLDB_INVALID_HOST_THREAD; 2068 } 2069 2070 void 2071 ProcessGDBRemote::StopAsyncThread () 2072 { 2073 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS); 2074 2075 if (log) 2076 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2077 2078 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2079 2080 // Stop the stdio thread 2081 if (m_async_thread != LLDB_INVALID_HOST_THREAD) 2082 { 2083 Host::ThreadJoin (m_async_thread, NULL, NULL); 2084 } 2085 } 2086 2087 2088 void * 2089 ProcessGDBRemote::AsyncThread (void *arg) 2090 { 2091 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2092 2093 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS); 2094 if (log) 2095 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID()); 2096 2097 Listener listener ("ProcessGDBRemote::AsyncThread"); 2098 EventSP event_sp; 2099 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2100 eBroadcastBitAsyncThreadShouldExit; 2101 2102 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2103 { 2104 bool done = false; 2105 while (!done) 2106 { 2107 if (log) 2108 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2109 if (listener.WaitForEvent (NULL, event_sp)) 2110 { 2111 const uint32_t event_type = event_sp->GetType(); 2112 switch (event_type) 2113 { 2114 case eBroadcastBitAsyncContinue: 2115 { 2116 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2117 2118 if (continue_packet) 2119 { 2120 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2121 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2122 if (log) 2123 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2124 2125 process->SetPrivateState(eStateRunning); 2126 StringExtractorGDBRemote response; 2127 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2128 2129 switch (stop_state) 2130 { 2131 case eStateStopped: 2132 case eStateCrashed: 2133 case eStateSuspended: 2134 process->m_last_stop_packet = response; 2135 process->m_last_stop_packet.SetFilePos (0); 2136 process->SetPrivateState (stop_state); 2137 break; 2138 2139 case eStateExited: 2140 process->m_last_stop_packet = response; 2141 process->m_last_stop_packet.SetFilePos (0); 2142 response.SetFilePos(1); 2143 process->SetExitStatus(response.GetHexU8(), NULL); 2144 done = true; 2145 break; 2146 2147 case eStateInvalid: 2148 break; 2149 2150 default: 2151 process->SetPrivateState (stop_state); 2152 break; 2153 } 2154 } 2155 } 2156 break; 2157 2158 case eBroadcastBitAsyncThreadShouldExit: 2159 if (log) 2160 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2161 done = true; 2162 break; 2163 2164 default: 2165 if (log) 2166 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2167 done = true; 2168 break; 2169 } 2170 } 2171 else 2172 { 2173 if (log) 2174 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2175 done = true; 2176 } 2177 } 2178 } 2179 2180 if (log) 2181 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID()); 2182 2183 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2184 return NULL; 2185 } 2186 2187 lldb_private::unw_addr_space_t 2188 ProcessGDBRemote::GetLibUnwindAddressSpace () 2189 { 2190 unw_targettype_t target_type = UNW_TARGET_UNSPECIFIED; 2191 2192 ArchSpec::CPU arch_cpu = m_target.GetArchitecture().GetGenericCPUType(); 2193 if (arch_cpu == ArchSpec::eCPU_i386) 2194 target_type = UNW_TARGET_I386; 2195 else if (arch_cpu == ArchSpec::eCPU_x86_64) 2196 target_type = UNW_TARGET_X86_64; 2197 2198 if (m_libunwind_addr_space) 2199 { 2200 if (m_libunwind_target_type != target_type) 2201 DestoryLibUnwindAddressSpace(); 2202 else 2203 return m_libunwind_addr_space; 2204 } 2205 unw_accessors_t callbacks = get_macosx_libunwind_callbacks (); 2206 m_libunwind_addr_space = unw_create_addr_space (&callbacks, target_type); 2207 if (m_libunwind_addr_space) 2208 m_libunwind_target_type = target_type; 2209 else 2210 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED; 2211 return m_libunwind_addr_space; 2212 } 2213 2214 void 2215 ProcessGDBRemote::DestoryLibUnwindAddressSpace () 2216 { 2217 if (m_libunwind_addr_space) 2218 { 2219 unw_destroy_addr_space (m_libunwind_addr_space); 2220 m_libunwind_addr_space = NULL; 2221 } 2222 m_libunwind_target_type = UNW_TARGET_UNSPECIFIED; 2223 } 2224 2225 2226 const char * 2227 ProcessGDBRemote::GetDispatchQueueNameForThread 2228 ( 2229 addr_t thread_dispatch_qaddr, 2230 std::string &dispatch_queue_name 2231 ) 2232 { 2233 dispatch_queue_name.clear(); 2234 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2235 { 2236 // Cache the dispatch_queue_offsets_addr value so we don't always have 2237 // to look it up 2238 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2239 { 2240 ModuleSP module_sp(GetTarget().GetImages().FindFirstModuleForFileSpec (FileSpec("libSystem.B.dylib"))); 2241 if (module_sp.get() == NULL) 2242 return NULL; 2243 2244 const Symbol *dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (ConstString("dispatch_queue_offsets"), eSymbolTypeData); 2245 if (dispatch_queue_offsets_symbol) 2246 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetValue().GetLoadAddress(this); 2247 2248 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2249 return NULL; 2250 } 2251 2252 uint8_t memory_buffer[8]; 2253 DataExtractor data(memory_buffer, sizeof(memory_buffer), GetByteOrder(), GetAddressByteSize()); 2254 2255 // Excerpt from src/queue_private.h 2256 struct dispatch_queue_offsets_s 2257 { 2258 uint16_t dqo_version; 2259 uint16_t dqo_label; 2260 uint16_t dqo_label_size; 2261 } dispatch_queue_offsets; 2262 2263 2264 Error error; 2265 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2266 { 2267 uint32_t data_offset = 0; 2268 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2269 { 2270 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2271 { 2272 data_offset = 0; 2273 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2274 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2275 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2276 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2277 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2278 dispatch_queue_name.erase (bytes_read); 2279 } 2280 } 2281 } 2282 } 2283 if (dispatch_queue_name.empty()) 2284 return NULL; 2285 return dispatch_queue_name.c_str(); 2286 } 2287 2288