ProcessGDBRemote.cpp revision c4bbbfc7eed93a8c1e9483ac6524103f9a8e3d81
1//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10// C Includes 11#include <errno.h> 12#include <spawn.h> 13#include <stdlib.h> 14#include <sys/mman.h> // for mmap 15#include <sys/stat.h> 16#include <sys/types.h> 17#include <time.h> 18 19// C++ Includes 20#include <algorithm> 21#include <map> 22 23// Other libraries and framework includes 24 25#include "lldb/Breakpoint/Watchpoint.h" 26#include "lldb/Interpreter/Args.h" 27#include "lldb/Core/ArchSpec.h" 28#include "lldb/Core/Debugger.h" 29#include "lldb/Core/ConnectionFileDescriptor.h" 30#include "lldb/Host/FileSpec.h" 31#include "lldb/Core/InputReader.h" 32#include "lldb/Core/Module.h" 33#include "lldb/Core/PluginManager.h" 34#include "lldb/Core/State.h" 35#include "lldb/Core/StreamFile.h" 36#include "lldb/Core/StreamString.h" 37#include "lldb/Core/Timer.h" 38#include "lldb/Core/Value.h" 39#include "lldb/Host/TimeValue.h" 40#include "lldb/Symbol/ObjectFile.h" 41#include "lldb/Target/DynamicLoader.h" 42#include "lldb/Target/Target.h" 43#include "lldb/Target/TargetList.h" 44#include "lldb/Target/ThreadPlanCallFunction.h" 45#include "lldb/Utility/PseudoTerminal.h" 46 47// Project includes 48#include "lldb/Host/Host.h" 49#include "Plugins/Process/Utility/InferiorCallPOSIX.h" 50#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h" 51#include "Utility/StringExtractorGDBRemote.h" 52#include "GDBRemoteRegisterContext.h" 53#include "ProcessGDBRemote.h" 54#include "ProcessGDBRemoteLog.h" 55#include "ThreadGDBRemote.h" 56#include "StopInfoMachException.h" 57 58namespace lldb 59{ 60 // Provide a function that can easily dump the packet history if we know a 61 // ProcessGDBRemote * value (which we can get from logs or from debugging). 62 // We need the function in the lldb namespace so it makes it into the final 63 // executable since the LLDB shared library only exports stuff in the lldb 64 // namespace. This allows you to attach with a debugger and call this 65 // function and get the packet history dumped to a file. 66 void 67 DumpProcessGDBRemotePacketHistory (void *p, const char *path) 68 { 69 lldb_private::StreamFile strm; 70 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate)); 71 if (error.Success()) 72 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm); 73 } 74} 75 76 77#define DEBUGSERVER_BASENAME "debugserver" 78using namespace lldb; 79using namespace lldb_private; 80 81static bool rand_initialized = false; 82 83static inline uint16_t 84get_random_port () 85{ 86 if (!rand_initialized) 87 { 88 time_t seed = time(NULL); 89 90 rand_initialized = true; 91 srand(seed); 92 } 93 return (rand() % (UINT16_MAX - 1000u)) + 1000u; 94} 95 96 97const char * 98ProcessGDBRemote::GetPluginNameStatic() 99{ 100 return "gdb-remote"; 101} 102 103const char * 104ProcessGDBRemote::GetPluginDescriptionStatic() 105{ 106 return "GDB Remote protocol based debugging plug-in."; 107} 108 109void 110ProcessGDBRemote::Terminate() 111{ 112 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 113} 114 115 116lldb::ProcessSP 117ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path) 118{ 119 lldb::ProcessSP process_sp; 120 if (crash_file_path == NULL) 121 process_sp.reset (new ProcessGDBRemote (target, listener)); 122 return process_sp; 123} 124 125bool 126ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name) 127{ 128 if (plugin_specified_by_name) 129 return true; 130 131 // For now we are just making sure the file exists for a given module 132 Module *exe_module = target.GetExecutableModulePointer(); 133 if (exe_module) 134 { 135 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 136 // We can't debug core files... 137 switch (exe_objfile->GetType()) 138 { 139 case ObjectFile::eTypeInvalid: 140 case ObjectFile::eTypeCoreFile: 141 case ObjectFile::eTypeDebugInfo: 142 case ObjectFile::eTypeObjectFile: 143 case ObjectFile::eTypeSharedLibrary: 144 case ObjectFile::eTypeStubLibrary: 145 return false; 146 case ObjectFile::eTypeExecutable: 147 case ObjectFile::eTypeDynamicLinker: 148 case ObjectFile::eTypeUnknown: 149 break; 150 } 151 return exe_module->GetFileSpec().Exists(); 152 } 153 // However, if there is no executable module, we return true since we might be preparing to attach. 154 return true; 155} 156 157//---------------------------------------------------------------------- 158// ProcessGDBRemote constructor 159//---------------------------------------------------------------------- 160ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) : 161 Process (target, listener), 162 m_flags (0), 163 m_gdb_comm(false), 164 m_debugserver_pid (LLDB_INVALID_PROCESS_ID), 165 m_last_stop_packet (), 166 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal), 167 m_register_info (), 168 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"), 169 m_async_thread (LLDB_INVALID_HOST_THREAD), 170 m_thread_ids (), 171 m_continue_c_tids (), 172 m_continue_C_tids (), 173 m_continue_s_tids (), 174 m_continue_S_tids (), 175 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS), 176 m_max_memory_size (512), 177 m_addr_to_mmap_size (), 178 m_thread_create_bp_sp (), 179 m_waiting_for_attach (false), 180 m_destroy_tried_resuming (false) 181{ 182 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); 183 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue"); 184 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit"); 185} 186 187//---------------------------------------------------------------------- 188// Destructor 189//---------------------------------------------------------------------- 190ProcessGDBRemote::~ProcessGDBRemote() 191{ 192 // m_mach_process.UnregisterNotificationCallbacks (this); 193 Clear(); 194 // We need to call finalize on the process before destroying ourselves 195 // to make sure all of the broadcaster cleanup goes as planned. If we 196 // destruct this class, then Process::~Process() might have problems 197 // trying to fully destroy the broadcaster. 198 Finalize(); 199} 200 201//---------------------------------------------------------------------- 202// PluginInterface 203//---------------------------------------------------------------------- 204const char * 205ProcessGDBRemote::GetPluginName() 206{ 207 return "Process debugging plug-in that uses the GDB remote protocol"; 208} 209 210const char * 211ProcessGDBRemote::GetShortPluginName() 212{ 213 return GetPluginNameStatic(); 214} 215 216uint32_t 217ProcessGDBRemote::GetPluginVersion() 218{ 219 return 1; 220} 221 222void 223ProcessGDBRemote::BuildDynamicRegisterInfo (bool force) 224{ 225 if (!force && m_register_info.GetNumRegisters() > 0) 226 return; 227 228 char packet[128]; 229 m_register_info.Clear(); 230 uint32_t reg_offset = 0; 231 uint32_t reg_num = 0; 232 StringExtractorGDBRemote::ResponseType response_type; 233 for (response_type = StringExtractorGDBRemote::eResponse; 234 response_type == StringExtractorGDBRemote::eResponse; 235 ++reg_num) 236 { 237 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num); 238 assert (packet_len < sizeof(packet)); 239 StringExtractorGDBRemote response; 240 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false)) 241 { 242 response_type = response.GetResponseType(); 243 if (response_type == StringExtractorGDBRemote::eResponse) 244 { 245 std::string name; 246 std::string value; 247 ConstString reg_name; 248 ConstString alt_name; 249 ConstString set_name; 250 RegisterInfo reg_info = { NULL, // Name 251 NULL, // Alt name 252 0, // byte size 253 reg_offset, // offset 254 eEncodingUint, // encoding 255 eFormatHex, // formate 256 { 257 LLDB_INVALID_REGNUM, // GCC reg num 258 LLDB_INVALID_REGNUM, // DWARF reg num 259 LLDB_INVALID_REGNUM, // generic reg num 260 reg_num, // GDB reg num 261 reg_num // native register number 262 }, 263 NULL, 264 NULL 265 }; 266 267 while (response.GetNameColonValue(name, value)) 268 { 269 if (name.compare("name") == 0) 270 { 271 reg_name.SetCString(value.c_str()); 272 } 273 else if (name.compare("alt-name") == 0) 274 { 275 alt_name.SetCString(value.c_str()); 276 } 277 else if (name.compare("bitsize") == 0) 278 { 279 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT; 280 } 281 else if (name.compare("offset") == 0) 282 { 283 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0); 284 if (reg_offset != offset) 285 { 286 reg_offset = offset; 287 } 288 } 289 else if (name.compare("encoding") == 0) 290 { 291 if (value.compare("uint") == 0) 292 reg_info.encoding = eEncodingUint; 293 else if (value.compare("sint") == 0) 294 reg_info.encoding = eEncodingSint; 295 else if (value.compare("ieee754") == 0) 296 reg_info.encoding = eEncodingIEEE754; 297 else if (value.compare("vector") == 0) 298 reg_info.encoding = eEncodingVector; 299 } 300 else if (name.compare("format") == 0) 301 { 302 if (value.compare("binary") == 0) 303 reg_info.format = eFormatBinary; 304 else if (value.compare("decimal") == 0) 305 reg_info.format = eFormatDecimal; 306 else if (value.compare("hex") == 0) 307 reg_info.format = eFormatHex; 308 else if (value.compare("float") == 0) 309 reg_info.format = eFormatFloat; 310 else if (value.compare("vector-sint8") == 0) 311 reg_info.format = eFormatVectorOfSInt8; 312 else if (value.compare("vector-uint8") == 0) 313 reg_info.format = eFormatVectorOfUInt8; 314 else if (value.compare("vector-sint16") == 0) 315 reg_info.format = eFormatVectorOfSInt16; 316 else if (value.compare("vector-uint16") == 0) 317 reg_info.format = eFormatVectorOfUInt16; 318 else if (value.compare("vector-sint32") == 0) 319 reg_info.format = eFormatVectorOfSInt32; 320 else if (value.compare("vector-uint32") == 0) 321 reg_info.format = eFormatVectorOfUInt32; 322 else if (value.compare("vector-float32") == 0) 323 reg_info.format = eFormatVectorOfFloat32; 324 else if (value.compare("vector-uint128") == 0) 325 reg_info.format = eFormatVectorOfUInt128; 326 } 327 else if (name.compare("set") == 0) 328 { 329 set_name.SetCString(value.c_str()); 330 } 331 else if (name.compare("gcc") == 0) 332 { 333 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 334 } 335 else if (name.compare("dwarf") == 0) 336 { 337 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 338 } 339 else if (name.compare("generic") == 0) 340 { 341 if (value.compare("pc") == 0) 342 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_PC; 343 else if (value.compare("sp") == 0) 344 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_SP; 345 else if (value.compare("fp") == 0) 346 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FP; 347 else if (value.compare("ra") == 0) 348 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_RA; 349 else if (value.compare("flags") == 0) 350 reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_FLAGS; 351 else if (value.find("arg") == 0) 352 { 353 if (value.size() == 4) 354 { 355 switch (value[3]) 356 { 357 case '1': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG1; break; 358 case '2': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG2; break; 359 case '3': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG3; break; 360 case '4': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG4; break; 361 case '5': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG5; break; 362 case '6': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG6; break; 363 case '7': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG7; break; 364 case '8': reg_info.kinds[eRegisterKindGeneric] = LLDB_REGNUM_GENERIC_ARG8; break; 365 } 366 } 367 } 368 } 369 } 370 371 reg_info.byte_offset = reg_offset; 372 assert (reg_info.byte_size != 0); 373 reg_offset += reg_info.byte_size; 374 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 375 } 376 } 377 else 378 { 379 response_type = StringExtractorGDBRemote::eError; 380 break; 381 } 382 } 383 384 // We didn't get anything if the accumulated reg_num is zero. See if we are 385 // debugging ARM and fill with a hard coded register set until we can get an 386 // updated debugserver down on the devices. 387 // On the other hand, if the accumulated reg_num is positive, see if we can 388 // add composite registers to the existing primordial ones. 389 bool from_scratch = (reg_num == 0); 390 391 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 392 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture(); 393 if (!target_arch.IsValid()) 394 { 395 if (remote_arch.IsValid() 396 && remote_arch.GetMachine() == llvm::Triple::arm 397 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 398 m_register_info.HardcodeARMRegisters(from_scratch); 399 } 400 else if (target_arch.GetMachine() == llvm::Triple::arm) 401 { 402 m_register_info.HardcodeARMRegisters(from_scratch); 403 } 404 405 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64. 406 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64) 407 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64)) 408 m_register_info.Addx86_64ConvenienceRegisters(); 409 410 // At this point, we can finalize our register info. 411 m_register_info.Finalize (); 412} 413 414Error 415ProcessGDBRemote::WillLaunch (Module* module) 416{ 417 return WillLaunchOrAttach (); 418} 419 420Error 421ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 422{ 423 return WillLaunchOrAttach (); 424} 425 426Error 427ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 428{ 429 return WillLaunchOrAttach (); 430} 431 432Error 433ProcessGDBRemote::DoConnectRemote (const char *remote_url) 434{ 435 Error error (WillLaunchOrAttach ()); 436 437 if (error.Fail()) 438 return error; 439 440 error = ConnectToDebugserver (remote_url); 441 442 if (error.Fail()) 443 return error; 444 StartAsyncThread (); 445 446 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 447 if (pid == LLDB_INVALID_PROCESS_ID) 448 { 449 // We don't have a valid process ID, so note that we are connected 450 // and could now request to launch or attach, or get remote process 451 // listings... 452 SetPrivateState (eStateConnected); 453 } 454 else 455 { 456 // We have a valid process 457 SetID (pid); 458 GetThreadList(); 459 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false)) 460 { 461 const StateType state = SetThreadStopInfo (m_last_stop_packet); 462 if (state == eStateStopped) 463 { 464 SetPrivateState (state); 465 } 466 else 467 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state)); 468 } 469 else 470 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url); 471 } 472 473 if (error.Success() 474 && !GetTarget().GetArchitecture().IsValid() 475 && m_gdb_comm.GetHostArchitecture().IsValid()) 476 { 477 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture()); 478 } 479 480 return error; 481} 482 483Error 484ProcessGDBRemote::WillLaunchOrAttach () 485{ 486 Error error; 487 m_stdio_communication.Clear (); 488 return error; 489} 490 491//---------------------------------------------------------------------- 492// Process Control 493//---------------------------------------------------------------------- 494Error 495ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info) 496{ 497 Error error; 498 499 uint32_t launch_flags = launch_info.GetFlags().Get(); 500 const char *stdin_path = NULL; 501 const char *stdout_path = NULL; 502 const char *stderr_path = NULL; 503 const char *working_dir = launch_info.GetWorkingDirectory(); 504 505 const ProcessLaunchInfo::FileAction *file_action; 506 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 507 if (file_action) 508 { 509 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 510 stdin_path = file_action->GetPath(); 511 } 512 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 513 if (file_action) 514 { 515 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 516 stdout_path = file_action->GetPath(); 517 } 518 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 519 if (file_action) 520 { 521 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 522 stderr_path = file_action->GetPath(); 523 } 524 525 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 526 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 527 // ::LogSetLogFile ("/dev/stdout"); 528 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 529 530 ObjectFile * object_file = exe_module->GetObjectFile(); 531 if (object_file) 532 { 533 char host_port[128]; 534 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 535 char connect_url[128]; 536 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 537 538 // Make sure we aren't already connected? 539 if (!m_gdb_comm.IsConnected()) 540 { 541 error = StartDebugserverProcess (host_port, launch_info); 542 if (error.Fail()) 543 { 544 if (log) 545 log->Printf("failed to start debugserver process: %s", error.AsCString()); 546 return error; 547 } 548 549 error = ConnectToDebugserver (connect_url); 550 } 551 552 if (error.Success()) 553 { 554 lldb_utility::PseudoTerminal pty; 555 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 556 557 // If the debugserver is local and we aren't disabling STDIO, lets use 558 // a pseudo terminal to instead of relying on the 'O' packets for stdio 559 // since 'O' packets can really slow down debugging if the inferior 560 // does a lot of output. 561 PlatformSP platform_sp (m_target.GetPlatform()); 562 if (platform_sp && platform_sp->IsHost() && !disable_stdio) 563 { 564 const char *slave_name = NULL; 565 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) 566 { 567 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 568 slave_name = pty.GetSlaveName (NULL, 0); 569 } 570 if (stdin_path == NULL) 571 stdin_path = slave_name; 572 573 if (stdout_path == NULL) 574 stdout_path = slave_name; 575 576 if (stderr_path == NULL) 577 stderr_path = slave_name; 578 } 579 580 // Set STDIN to /dev/null if we want STDIO disabled or if either 581 // STDOUT or STDERR have been set to something and STDIN hasn't 582 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path))) 583 stdin_path = "/dev/null"; 584 585 // Set STDOUT to /dev/null if we want STDIO disabled or if either 586 // STDIN or STDERR have been set to something and STDOUT hasn't 587 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path))) 588 stdout_path = "/dev/null"; 589 590 // Set STDERR to /dev/null if we want STDIO disabled or if either 591 // STDIN or STDOUT have been set to something and STDERR hasn't 592 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path))) 593 stderr_path = "/dev/null"; 594 595 if (stdin_path) 596 m_gdb_comm.SetSTDIN (stdin_path); 597 if (stdout_path) 598 m_gdb_comm.SetSTDOUT (stdout_path); 599 if (stderr_path) 600 m_gdb_comm.SetSTDERR (stderr_path); 601 602 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR); 603 604 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName()); 605 606 if (working_dir && working_dir[0]) 607 { 608 m_gdb_comm.SetWorkingDir (working_dir); 609 } 610 611 // Send the environment and the program + arguments after we connect 612 const Args &environment = launch_info.GetEnvironmentEntries(); 613 if (environment.GetArgumentCount()) 614 { 615 size_t num_environment_entries = environment.GetArgumentCount(); 616 for (size_t i=0; i<num_environment_entries; ++i) 617 { 618 const char *env_entry = environment.GetArgumentAtIndex(i); 619 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0) 620 break; 621 } 622 } 623 624 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10); 625 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector()); 626 if (arg_packet_err == 0) 627 { 628 std::string error_str; 629 if (m_gdb_comm.GetLaunchSuccess (error_str)) 630 { 631 SetID (m_gdb_comm.GetCurrentProcessID ()); 632 } 633 else 634 { 635 error.SetErrorString (error_str.c_str()); 636 } 637 } 638 else 639 { 640 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err); 641 } 642 643 m_gdb_comm.SetPacketTimeout (old_packet_timeout); 644 645 if (GetID() == LLDB_INVALID_PROCESS_ID) 646 { 647 if (log) 648 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 649 KillDebugserverProcess (); 650 return error; 651 } 652 653 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false)) 654 { 655 SetPrivateState (SetThreadStopInfo (m_last_stop_packet)); 656 657 if (!disable_stdio) 658 { 659 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) 660 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor()); 661 } 662 } 663 } 664 else 665 { 666 if (log) 667 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 668 } 669 } 670 else 671 { 672 // Set our user ID to an invalid process ID. 673 SetID(LLDB_INVALID_PROCESS_ID); 674 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s", 675 exe_module->GetFileSpec().GetFilename().AsCString(), 676 exe_module->GetArchitecture().GetArchitectureName()); 677 } 678 return error; 679 680} 681 682 683Error 684ProcessGDBRemote::ConnectToDebugserver (const char *connect_url) 685{ 686 Error error; 687 // Sleep and wait a bit for debugserver to start to listen... 688 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor()); 689 if (conn_ap.get()) 690 { 691 const uint32_t max_retry_count = 50; 692 uint32_t retry_count = 0; 693 while (!m_gdb_comm.IsConnected()) 694 { 695 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) 696 { 697 m_gdb_comm.SetConnection (conn_ap.release()); 698 break; 699 } 700 retry_count++; 701 702 if (retry_count >= max_retry_count) 703 break; 704 705 usleep (100000); 706 } 707 } 708 709 if (!m_gdb_comm.IsConnected()) 710 { 711 if (error.Success()) 712 error.SetErrorString("not connected to remote gdb server"); 713 return error; 714 } 715 716 // We always seem to be able to open a connection to a local port 717 // so we need to make sure we can then send data to it. If we can't 718 // then we aren't actually connected to anything, so try and do the 719 // handshake with the remote GDB server and make sure that goes 720 // alright. 721 if (!m_gdb_comm.HandshakeWithServer (NULL)) 722 { 723 m_gdb_comm.Disconnect(); 724 if (error.Success()) 725 error.SetErrorString("not connected to remote gdb server"); 726 return error; 727 } 728 m_gdb_comm.ResetDiscoverableSettings(); 729 m_gdb_comm.QueryNoAckModeSupported (); 730 m_gdb_comm.GetThreadSuffixSupported (); 731 m_gdb_comm.GetListThreadsInStopReplySupported (); 732 m_gdb_comm.GetHostInfo (); 733 m_gdb_comm.GetVContSupported ('c'); 734 735 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount(); 736 for (size_t idx = 0; idx < num_cmds; idx++) 737 { 738 StringExtractorGDBRemote response; 739 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx)); 740 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); 741 } 742 return error; 743} 744 745void 746ProcessGDBRemote::DidLaunchOrAttach () 747{ 748 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 749 if (log) 750 log->Printf ("ProcessGDBRemote::DidLaunch()"); 751 if (GetID() != LLDB_INVALID_PROCESS_ID) 752 { 753 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; 754 755 BuildDynamicRegisterInfo (false); 756 757 // See if the GDB server supports the qHostInfo information 758 759 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture(); 760 if (gdb_remote_arch.IsValid()) 761 { 762 ArchSpec &target_arch = GetTarget().GetArchitecture(); 763 764 if (target_arch.IsValid()) 765 { 766 // If the remote host is ARM and we have apple as the vendor, then 767 // ARM executables and shared libraries can have mixed ARM architectures. 768 // You can have an armv6 executable, and if the host is armv7, then the 769 // system will load the best possible architecture for all shared libraries 770 // it has, so we really need to take the remote host architecture as our 771 // defacto architecture in this case. 772 773 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm && 774 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 775 { 776 target_arch = gdb_remote_arch; 777 } 778 else 779 { 780 // Fill in what is missing in the triple 781 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple(); 782 llvm::Triple &target_triple = target_arch.GetTriple(); 783 if (target_triple.getVendorName().size() == 0) 784 { 785 target_triple.setVendor (remote_triple.getVendor()); 786 787 if (target_triple.getOSName().size() == 0) 788 { 789 target_triple.setOS (remote_triple.getOS()); 790 791 if (target_triple.getEnvironmentName().size() == 0) 792 target_triple.setEnvironment (remote_triple.getEnvironment()); 793 } 794 } 795 } 796 } 797 else 798 { 799 // The target doesn't have a valid architecture yet, set it from 800 // the architecture we got from the remote GDB server 801 target_arch = gdb_remote_arch; 802 } 803 } 804 } 805} 806 807void 808ProcessGDBRemote::DidLaunch () 809{ 810 DidLaunchOrAttach (); 811} 812 813Error 814ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid) 815{ 816 ProcessAttachInfo attach_info; 817 return DoAttachToProcessWithID(attach_pid, attach_info); 818} 819 820Error 821ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) 822{ 823 Error error; 824 // Clear out and clean up from any current state 825 Clear(); 826 if (attach_pid != LLDB_INVALID_PROCESS_ID) 827 { 828 // Make sure we aren't already connected? 829 if (!m_gdb_comm.IsConnected()) 830 { 831 char host_port[128]; 832 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 833 char connect_url[128]; 834 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 835 836 error = StartDebugserverProcess (host_port, attach_info); 837 838 if (error.Fail()) 839 { 840 const char *error_string = error.AsCString(); 841 if (error_string == NULL) 842 error_string = "unable to launch " DEBUGSERVER_BASENAME; 843 844 SetExitStatus (-1, error_string); 845 } 846 else 847 { 848 error = ConnectToDebugserver (connect_url); 849 } 850 } 851 852 if (error.Success()) 853 { 854 char packet[64]; 855 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid); 856 SetID (attach_pid); 857 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len)); 858 } 859 } 860 return error; 861} 862 863size_t 864ProcessGDBRemote::AttachInputReaderCallback 865( 866 void *baton, 867 InputReader *reader, 868 lldb::InputReaderAction notification, 869 const char *bytes, 870 size_t bytes_len 871) 872{ 873 if (notification == eInputReaderGotToken) 874 { 875 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton; 876 if (gdb_process->m_waiting_for_attach) 877 gdb_process->m_waiting_for_attach = false; 878 reader->SetIsDone(true); 879 return 1; 880 } 881 return 0; 882} 883 884Error 885ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info) 886{ 887 Error error; 888 // Clear out and clean up from any current state 889 Clear(); 890 891 if (process_name && process_name[0]) 892 { 893 // Make sure we aren't already connected? 894 if (!m_gdb_comm.IsConnected()) 895 { 896 char host_port[128]; 897 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 898 char connect_url[128]; 899 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 900 901 error = StartDebugserverProcess (host_port, attach_info); 902 if (error.Fail()) 903 { 904 const char *error_string = error.AsCString(); 905 if (error_string == NULL) 906 error_string = "unable to launch " DEBUGSERVER_BASENAME; 907 908 SetExitStatus (-1, error_string); 909 } 910 else 911 { 912 error = ConnectToDebugserver (connect_url); 913 } 914 } 915 916 if (error.Success()) 917 { 918 StreamString packet; 919 920 if (wait_for_launch) 921 packet.PutCString("vAttachWait"); 922 else 923 packet.PutCString("vAttachName"); 924 packet.PutChar(';'); 925 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 926 927 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize())); 928 929 } 930 } 931 return error; 932} 933 934 935void 936ProcessGDBRemote::DidAttach () 937{ 938 DidLaunchOrAttach (); 939} 940 941Error 942ProcessGDBRemote::WillResume () 943{ 944 m_continue_c_tids.clear(); 945 m_continue_C_tids.clear(); 946 m_continue_s_tids.clear(); 947 m_continue_S_tids.clear(); 948 return Error(); 949} 950 951Error 952ProcessGDBRemote::DoResume () 953{ 954 Error error; 955 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 956 if (log) 957 log->Printf ("ProcessGDBRemote::Resume()"); 958 959 Listener listener ("gdb-remote.resume-packet-sent"); 960 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 961 { 962 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 963 964 StreamString continue_packet; 965 bool continue_packet_error = false; 966 if (m_gdb_comm.HasAnyVContSupport ()) 967 { 968 continue_packet.PutCString ("vCont"); 969 970 if (!m_continue_c_tids.empty()) 971 { 972 if (m_gdb_comm.GetVContSupported ('c')) 973 { 974 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos) 975 continue_packet.Printf(";c:%4.4llx", *t_pos); 976 } 977 else 978 continue_packet_error = true; 979 } 980 981 if (!continue_packet_error && !m_continue_C_tids.empty()) 982 { 983 if (m_gdb_comm.GetVContSupported ('C')) 984 { 985 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos) 986 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first); 987 } 988 else 989 continue_packet_error = true; 990 } 991 992 if (!continue_packet_error && !m_continue_s_tids.empty()) 993 { 994 if (m_gdb_comm.GetVContSupported ('s')) 995 { 996 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos) 997 continue_packet.Printf(";s:%4.4llx", *t_pos); 998 } 999 else 1000 continue_packet_error = true; 1001 } 1002 1003 if (!continue_packet_error && !m_continue_S_tids.empty()) 1004 { 1005 if (m_gdb_comm.GetVContSupported ('S')) 1006 { 1007 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos) 1008 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first); 1009 } 1010 else 1011 continue_packet_error = true; 1012 } 1013 1014 if (continue_packet_error) 1015 continue_packet.GetString().clear(); 1016 } 1017 else 1018 continue_packet_error = true; 1019 1020 if (continue_packet_error) 1021 { 1022 // Either no vCont support, or we tried to use part of the vCont 1023 // packet that wasn't supported by the remote GDB server. 1024 // We need to try and make a simple packet that can do our continue 1025 const size_t num_threads = GetThreadList().GetSize(); 1026 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1027 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1028 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1029 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1030 if (num_continue_c_tids > 0) 1031 { 1032 if (num_continue_c_tids == num_threads) 1033 { 1034 // All threads are resuming... 1035 m_gdb_comm.SetCurrentThreadForRun (-1); 1036 continue_packet.PutChar ('c'); 1037 continue_packet_error = false; 1038 } 1039 else if (num_continue_c_tids == 1 && 1040 num_continue_C_tids == 0 && 1041 num_continue_s_tids == 0 && 1042 num_continue_S_tids == 0 ) 1043 { 1044 // Only one thread is continuing 1045 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 1046 continue_packet.PutChar ('c'); 1047 continue_packet_error = false; 1048 } 1049 } 1050 1051 if (continue_packet_error && num_continue_C_tids > 0) 1052 { 1053 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1054 num_continue_C_tids > 0 && 1055 num_continue_s_tids == 0 && 1056 num_continue_S_tids == 0 ) 1057 { 1058 const int continue_signo = m_continue_C_tids.front().second; 1059 // Only one thread is continuing 1060 if (num_continue_C_tids > 1) 1061 { 1062 // More that one thread with a signal, yet we don't have 1063 // vCont support and we are being asked to resume each 1064 // thread with a signal, we need to make sure they are 1065 // all the same signal, or we can't issue the continue 1066 // accurately with the current support... 1067 if (num_continue_C_tids > 1) 1068 { 1069 continue_packet_error = false; 1070 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1071 { 1072 if (m_continue_C_tids[i].second != continue_signo) 1073 continue_packet_error = true; 1074 } 1075 } 1076 if (!continue_packet_error) 1077 m_gdb_comm.SetCurrentThreadForRun (-1); 1078 } 1079 else 1080 { 1081 // Set the continue thread ID 1082 continue_packet_error = false; 1083 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1084 } 1085 if (!continue_packet_error) 1086 { 1087 // Add threads continuing with the same signo... 1088 continue_packet.Printf("C%2.2x", continue_signo); 1089 } 1090 } 1091 } 1092 1093 if (continue_packet_error && num_continue_s_tids > 0) 1094 { 1095 if (num_continue_s_tids == num_threads) 1096 { 1097 // All threads are resuming... 1098 m_gdb_comm.SetCurrentThreadForRun (-1); 1099 continue_packet.PutChar ('s'); 1100 continue_packet_error = false; 1101 } 1102 else if (num_continue_c_tids == 0 && 1103 num_continue_C_tids == 0 && 1104 num_continue_s_tids == 1 && 1105 num_continue_S_tids == 0 ) 1106 { 1107 // Only one thread is stepping 1108 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1109 continue_packet.PutChar ('s'); 1110 continue_packet_error = false; 1111 } 1112 } 1113 1114 if (!continue_packet_error && num_continue_S_tids > 0) 1115 { 1116 if (num_continue_S_tids == num_threads) 1117 { 1118 const int step_signo = m_continue_S_tids.front().second; 1119 // Are all threads trying to step with the same signal? 1120 continue_packet_error = false; 1121 if (num_continue_S_tids > 1) 1122 { 1123 for (size_t i=1; i<num_threads; ++i) 1124 { 1125 if (m_continue_S_tids[i].second != step_signo) 1126 continue_packet_error = true; 1127 } 1128 } 1129 if (!continue_packet_error) 1130 { 1131 // Add threads stepping with the same signo... 1132 m_gdb_comm.SetCurrentThreadForRun (-1); 1133 continue_packet.Printf("S%2.2x", step_signo); 1134 } 1135 } 1136 else if (num_continue_c_tids == 0 && 1137 num_continue_C_tids == 0 && 1138 num_continue_s_tids == 0 && 1139 num_continue_S_tids == 1 ) 1140 { 1141 // Only one thread is stepping with signal 1142 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1143 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1144 continue_packet_error = false; 1145 } 1146 } 1147 } 1148 1149 if (continue_packet_error) 1150 { 1151 error.SetErrorString ("can't make continue packet for this resume"); 1152 } 1153 else 1154 { 1155 EventSP event_sp; 1156 TimeValue timeout; 1157 timeout = TimeValue::Now(); 1158 timeout.OffsetWithSeconds (5); 1159 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 1160 { 1161 error.SetErrorString ("Trying to resume but the async thread is dead."); 1162 if (log) 1163 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead."); 1164 return error; 1165 } 1166 1167 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1168 1169 if (listener.WaitForEvent (&timeout, event_sp) == false) 1170 { 1171 error.SetErrorString("Resume timed out."); 1172 if (log) 1173 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out."); 1174 } 1175 else if (event_sp->BroadcasterIs (&m_async_broadcaster)) 1176 { 1177 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back."); 1178 if (log) 1179 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back."); 1180 return error; 1181 } 1182 } 1183 } 1184 1185 return error; 1186} 1187 1188void 1189ProcessGDBRemote::ClearThreadIDList () 1190{ 1191 Mutex::Locker locker(m_thread_list.GetMutex()); 1192 m_thread_ids.clear(); 1193} 1194 1195bool 1196ProcessGDBRemote::UpdateThreadIDList () 1197{ 1198 Mutex::Locker locker(m_thread_list.GetMutex()); 1199 bool sequence_mutex_unavailable = false; 1200 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable); 1201 if (sequence_mutex_unavailable) 1202 { 1203 return false; // We just didn't get the list 1204 } 1205 return true; 1206} 1207 1208bool 1209ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1210{ 1211 // locker will keep a mutex locked until it goes out of scope 1212 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1213 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1214 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID()); 1215 1216 size_t num_thread_ids = m_thread_ids.size(); 1217 // The "m_thread_ids" thread ID list should always be updated after each stop 1218 // reply packet, but in case it isn't, update it here. 1219 if (num_thread_ids == 0) 1220 { 1221 if (!UpdateThreadIDList ()) 1222 return false; 1223 num_thread_ids = m_thread_ids.size(); 1224 } 1225 1226 if (num_thread_ids > 0) 1227 { 1228 for (size_t i=0; i<num_thread_ids; ++i) 1229 { 1230 tid_t tid = m_thread_ids[i]; 1231 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false)); 1232 if (!thread_sp) 1233 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid)); 1234 new_thread_list.AddThread(thread_sp); 1235 } 1236 } 1237 1238 return true; 1239} 1240 1241 1242StateType 1243ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 1244{ 1245 stop_packet.SetFilePos (0); 1246 const char stop_type = stop_packet.GetChar(); 1247 switch (stop_type) 1248 { 1249 case 'T': 1250 case 'S': 1251 { 1252 if (GetStopID() == 0) 1253 { 1254 // Our first stop, make sure we have a process ID, and also make 1255 // sure we know about our registers 1256 if (GetID() == LLDB_INVALID_PROCESS_ID) 1257 { 1258 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 1259 if (pid != LLDB_INVALID_PROCESS_ID) 1260 SetID (pid); 1261 } 1262 BuildDynamicRegisterInfo (true); 1263 } 1264 // Stop with signal and thread info 1265 const uint8_t signo = stop_packet.GetHexU8(); 1266 std::string name; 1267 std::string value; 1268 std::string thread_name; 1269 std::string reason; 1270 std::string description; 1271 uint32_t exc_type = 0; 1272 std::vector<addr_t> exc_data; 1273 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1274 uint32_t exc_data_count = 0; 1275 ThreadSP thread_sp; 1276 1277 while (stop_packet.GetNameColonValue(name, value)) 1278 { 1279 if (name.compare("metype") == 0) 1280 { 1281 // exception type in big endian hex 1282 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 1283 } 1284 else if (name.compare("mecount") == 0) 1285 { 1286 // exception count in big endian hex 1287 exc_data_count = Args::StringToUInt32 (value.c_str(), 0, 16); 1288 } 1289 else if (name.compare("medata") == 0) 1290 { 1291 // exception data in big endian hex 1292 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1293 } 1294 else if (name.compare("thread") == 0) 1295 { 1296 // thread in big endian hex 1297 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1298 // m_thread_list does have its own mutex, but we need to 1299 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...) 1300 // and the m_thread_list.AddThread(...) so it doesn't change on us 1301 Mutex::Locker locker (m_thread_list.GetMutex ()); 1302 thread_sp = m_thread_list.FindThreadByID(tid, false); 1303 if (!thread_sp) 1304 { 1305 // Create the thread if we need to 1306 thread_sp.reset (new ThreadGDBRemote (shared_from_this(), tid)); 1307 m_thread_list.AddThread(thread_sp); 1308 } 1309 } 1310 else if (name.compare("threads") == 0) 1311 { 1312 Mutex::Locker locker(m_thread_list.GetMutex()); 1313 m_thread_ids.clear(); 1314 // A comma separated list of all threads in the current 1315 // process that includes the thread for this stop reply 1316 // packet 1317 size_t comma_pos; 1318 lldb::tid_t tid; 1319 while ((comma_pos = value.find(',')) != std::string::npos) 1320 { 1321 value[comma_pos] = '\0'; 1322 // thread in big endian hex 1323 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1324 if (tid != LLDB_INVALID_THREAD_ID) 1325 m_thread_ids.push_back (tid); 1326 value.erase(0, comma_pos + 1); 1327 1328 } 1329 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1330 if (tid != LLDB_INVALID_THREAD_ID) 1331 m_thread_ids.push_back (tid); 1332 } 1333 else if (name.compare("hexname") == 0) 1334 { 1335 StringExtractor name_extractor; 1336 // Swap "value" over into "name_extractor" 1337 name_extractor.GetStringRef().swap(value); 1338 // Now convert the HEX bytes into a string value 1339 name_extractor.GetHexByteString (value); 1340 thread_name.swap (value); 1341 } 1342 else if (name.compare("name") == 0) 1343 { 1344 thread_name.swap (value); 1345 } 1346 else if (name.compare("qaddr") == 0) 1347 { 1348 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1349 } 1350 else if (name.compare("reason") == 0) 1351 { 1352 reason.swap(value); 1353 } 1354 else if (name.compare("description") == 0) 1355 { 1356 StringExtractor desc_extractor; 1357 // Swap "value" over into "name_extractor" 1358 desc_extractor.GetStringRef().swap(value); 1359 // Now convert the HEX bytes into a string value 1360 desc_extractor.GetHexByteString (thread_name); 1361 } 1362 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1])) 1363 { 1364 // We have a register number that contains an expedited 1365 // register value. Lets supply this register to our thread 1366 // so it won't have to go and read it. 1367 if (thread_sp) 1368 { 1369 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16); 1370 1371 if (reg != UINT32_MAX) 1372 { 1373 StringExtractor reg_value_extractor; 1374 // Swap "value" over into "reg_value_extractor" 1375 reg_value_extractor.GetStringRef().swap(value); 1376 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor)) 1377 { 1378 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'", 1379 name.c_str(), 1380 reg, 1381 reg, 1382 reg_value_extractor.GetStringRef().c_str(), 1383 stop_packet.GetStringRef().c_str()); 1384 } 1385 } 1386 } 1387 } 1388 } 1389 1390 if (thread_sp) 1391 { 1392 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1393 1394 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1395 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1396 if (exc_type != 0) 1397 { 1398 const size_t exc_data_size = exc_data.size(); 1399 1400 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1401 exc_type, 1402 exc_data_size, 1403 exc_data_size >= 1 ? exc_data[0] : 0, 1404 exc_data_size >= 2 ? exc_data[1] : 0, 1405 exc_data_size >= 3 ? exc_data[2] : 0)); 1406 } 1407 else 1408 { 1409 bool handled = false; 1410 if (!reason.empty()) 1411 { 1412 if (reason.compare("trace") == 0) 1413 { 1414 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1415 handled = true; 1416 } 1417 else if (reason.compare("breakpoint") == 0) 1418 { 1419 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1420 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1421 if (bp_site_sp) 1422 { 1423 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1424 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1425 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1426 handled = true; 1427 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1428 { 1429 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1430 } 1431 else 1432 { 1433 StopInfoSP invalid_stop_info_sp; 1434 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1435 } 1436 } 1437 1438 } 1439 else if (reason.compare("trap") == 0) 1440 { 1441 // Let the trap just use the standard signal stop reason below... 1442 } 1443 else if (reason.compare("watchpoint") == 0) 1444 { 1445 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1446 // TODO: locate the watchpoint somehow... 1447 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1448 handled = true; 1449 } 1450 else if (reason.compare("exception") == 0) 1451 { 1452 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1453 handled = true; 1454 } 1455 } 1456 1457 if (signo) 1458 { 1459 if (signo == SIGTRAP) 1460 { 1461 // Currently we are going to assume SIGTRAP means we are either 1462 // hitting a breakpoint or hardware single stepping. 1463 handled = true; 1464 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1465 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1466 1467 if (bp_site_sp) 1468 { 1469 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1470 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1471 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1472 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1473 { 1474 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1475 } 1476 else 1477 { 1478 StopInfoSP invalid_stop_info_sp; 1479 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1480 } 1481 } 1482 else 1483 { 1484 // TODO: check for breakpoint or trap opcode in case there is a hard 1485 // coded software trap 1486 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1487 } 1488 } 1489 if (!handled) 1490 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1491 } 1492 else 1493 { 1494 StopInfoSP invalid_stop_info_sp; 1495 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1496 } 1497 1498 if (!description.empty()) 1499 { 1500 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ()); 1501 if (stop_info_sp) 1502 { 1503 stop_info_sp->SetDescription (description.c_str()); 1504 } 1505 else 1506 { 1507 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1508 } 1509 } 1510 } 1511 } 1512 return eStateStopped; 1513 } 1514 break; 1515 1516 case 'W': 1517 // process exited 1518 return eStateExited; 1519 1520 default: 1521 break; 1522 } 1523 return eStateInvalid; 1524} 1525 1526void 1527ProcessGDBRemote::RefreshStateAfterStop () 1528{ 1529 Mutex::Locker locker(m_thread_list.GetMutex()); 1530 m_thread_ids.clear(); 1531 // Set the thread stop info. It might have a "threads" key whose value is 1532 // a list of all thread IDs in the current process, so m_thread_ids might 1533 // get set. 1534 SetThreadStopInfo (m_last_stop_packet); 1535 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 1536 if (m_thread_ids.empty()) 1537 { 1538 // No, we need to fetch the thread list manually 1539 UpdateThreadIDList(); 1540 } 1541 1542 // Let all threads recover from stopping and do any clean up based 1543 // on the previous thread state (if any). 1544 m_thread_list.RefreshStateAfterStop(); 1545 1546} 1547 1548Error 1549ProcessGDBRemote::DoHalt (bool &caused_stop) 1550{ 1551 Error error; 1552 1553 bool timed_out = false; 1554 Mutex::Locker locker; 1555 1556 if (m_public_state.GetValue() == eStateAttaching) 1557 { 1558 // We are being asked to halt during an attach. We need to just close 1559 // our file handle and debugserver will go away, and we can be done... 1560 m_gdb_comm.Disconnect(); 1561 } 1562 else 1563 { 1564 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 1565 { 1566 if (timed_out) 1567 error.SetErrorString("timed out sending interrupt packet"); 1568 else 1569 error.SetErrorString("unknown error sending interrupt packet"); 1570 } 1571 1572 caused_stop = m_gdb_comm.GetInterruptWasSent (); 1573 } 1574 return error; 1575} 1576 1577Error 1578ProcessGDBRemote::InterruptIfRunning 1579( 1580 bool discard_thread_plans, 1581 bool catch_stop_event, 1582 EventSP &stop_event_sp 1583) 1584{ 1585 Error error; 1586 1587 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1588 1589 bool paused_private_state_thread = false; 1590 const bool is_running = m_gdb_comm.IsRunning(); 1591 if (log) 1592 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i", 1593 discard_thread_plans, 1594 catch_stop_event, 1595 is_running); 1596 1597 if (discard_thread_plans) 1598 { 1599 if (log) 1600 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans"); 1601 m_thread_list.DiscardThreadPlans(); 1602 } 1603 if (is_running) 1604 { 1605 if (catch_stop_event) 1606 { 1607 if (log) 1608 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread"); 1609 PausePrivateStateThread(); 1610 paused_private_state_thread = true; 1611 } 1612 1613 bool timed_out = false; 1614 Mutex::Locker locker; 1615 1616 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out)) 1617 { 1618 if (timed_out) 1619 error.SetErrorString("timed out sending interrupt packet"); 1620 else 1621 error.SetErrorString("unknown error sending interrupt packet"); 1622 if (paused_private_state_thread) 1623 ResumePrivateStateThread(); 1624 return error; 1625 } 1626 1627 if (catch_stop_event) 1628 { 1629 // LISTEN HERE 1630 TimeValue timeout_time; 1631 timeout_time = TimeValue::Now(); 1632 timeout_time.OffsetWithSeconds(5); 1633 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp); 1634 1635 timed_out = state == eStateInvalid; 1636 if (log) 1637 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out); 1638 1639 if (timed_out) 1640 error.SetErrorString("unable to verify target stopped"); 1641 } 1642 1643 if (paused_private_state_thread) 1644 { 1645 if (log) 1646 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread"); 1647 ResumePrivateStateThread(); 1648 } 1649 } 1650 return error; 1651} 1652 1653Error 1654ProcessGDBRemote::WillDetach () 1655{ 1656 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1657 if (log) 1658 log->Printf ("ProcessGDBRemote::WillDetach()"); 1659 1660 bool discard_thread_plans = true; 1661 bool catch_stop_event = true; 1662 EventSP event_sp; 1663 1664 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is 1665 // needed. This shouldn't be a feature of a particular plugin. 1666 1667 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp); 1668} 1669 1670Error 1671ProcessGDBRemote::DoDetach() 1672{ 1673 Error error; 1674 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1675 if (log) 1676 log->Printf ("ProcessGDBRemote::DoDetach()"); 1677 1678 DisableAllBreakpointSites (); 1679 1680 m_thread_list.DiscardThreadPlans(); 1681 1682 bool success = m_gdb_comm.Detach (); 1683 if (log) 1684 { 1685 if (success) 1686 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1687 else 1688 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed"); 1689 } 1690 // Sleep for one second to let the process get all detached... 1691 StopAsyncThread (); 1692 1693 SetPrivateState (eStateDetached); 1694 ResumePrivateStateThread(); 1695 1696 //KillDebugserverProcess (); 1697 return error; 1698} 1699 1700 1701Error 1702ProcessGDBRemote::DoDestroy () 1703{ 1704 Error error; 1705 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1706 if (log) 1707 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1708 1709 // There is a bug in older iOS debugservers where they don't shut down the process 1710 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 1711 // this can cause problems with restarting. So we check to see if any of our threads are stopped 1712 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 1713 // destroy it again. 1714 // 1715 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 1716 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 1717 // the debugservers with this bug are equal. There really should be a better way to test this! 1718 // 1719 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 1720 // get called here to destroy again and we're still at a breakpoint or exception, then we should 1721 // just do the straight-forward kill. 1722 // 1723 // And of course, if we weren't able to stop the process by the time we get here, it isn't 1724 // necessary (or helpful) to do any of this. 1725 1726 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 1727 { 1728 PlatformSP platform_sp = GetTarget().GetPlatform(); 1729 1730 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 1731 if (platform_sp 1732 && platform_sp->GetName() 1733 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0) 1734 { 1735 if (m_destroy_tried_resuming) 1736 { 1737 if (log) 1738 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again."); 1739 } 1740 else 1741 { 1742 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 1743 // but we really need it to happen here and it doesn't matter if we do it twice. 1744 m_thread_list.DiscardThreadPlans(); 1745 DisableAllBreakpointSites(); 1746 1747 bool stop_looks_like_crash = false; 1748 ThreadList &threads = GetThreadList(); 1749 1750 { 1751 Mutex::Locker(threads.GetMutex()); 1752 1753 size_t num_threads = threads.GetSize(); 1754 for (size_t i = 0; i < num_threads; i++) 1755 { 1756 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1757 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1758 StopReason reason = eStopReasonInvalid; 1759 if (stop_info_sp) 1760 reason = stop_info_sp->GetStopReason(); 1761 if (reason == eStopReasonBreakpoint 1762 || reason == eStopReasonException) 1763 { 1764 if (log) 1765 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.", 1766 thread_sp->GetID(), 1767 stop_info_sp->GetDescription()); 1768 stop_looks_like_crash = true; 1769 break; 1770 } 1771 } 1772 } 1773 1774 if (stop_looks_like_crash) 1775 { 1776 if (log) 1777 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 1778 m_destroy_tried_resuming = true; 1779 1780 // If we are going to run again before killing, it would be good to suspend all the threads 1781 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 1782 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 1783 // have to run the risk of letting those threads proceed a bit. 1784 1785 { 1786 Mutex::Locker(threads.GetMutex()); 1787 1788 size_t num_threads = threads.GetSize(); 1789 for (size_t i = 0; i < num_threads; i++) 1790 { 1791 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1792 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1793 StopReason reason = eStopReasonInvalid; 1794 if (stop_info_sp) 1795 reason = stop_info_sp->GetStopReason(); 1796 if (reason != eStopReasonBreakpoint 1797 && reason != eStopReasonException) 1798 { 1799 if (log) 1800 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.", 1801 thread_sp->GetID()); 1802 thread_sp->SetResumeState(eStateSuspended); 1803 } 1804 } 1805 } 1806 Resume (); 1807 return Destroy(); 1808 } 1809 } 1810 } 1811 } 1812 1813 // Interrupt if our inferior is running... 1814 int exit_status = SIGABRT; 1815 std::string exit_string; 1816 1817 if (m_gdb_comm.IsConnected()) 1818 { 1819 if (m_public_state.GetValue() != eStateAttaching) 1820 { 1821 1822 StringExtractorGDBRemote response; 1823 bool send_async = true; 1824 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async)) 1825 { 1826 char packet_cmd = response.GetChar(0); 1827 1828 if (packet_cmd == 'W' || packet_cmd == 'X') 1829 { 1830 SetLastStopPacket (response); 1831 ClearThreadIDList (); 1832 exit_status = response.GetHexU8(); 1833 } 1834 else 1835 { 1836 if (log) 1837 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 1838 exit_string.assign("got unexpected response to k packet: "); 1839 exit_string.append(response.GetStringRef()); 1840 } 1841 } 1842 else 1843 { 1844 if (log) 1845 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1846 exit_string.assign("failed to send the k packet"); 1847 } 1848 } 1849 else 1850 { 1851 if (log) 1852 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1853 exit_string.assign ("killing while attaching."); 1854 } 1855 } 1856 else 1857 { 1858 // If we missed setting the exit status on the way out, do it here. 1859 // NB set exit status can be called multiple times, the first one sets the status. 1860 exit_string.assign("destroying when not connected to debugserver"); 1861 } 1862 1863 SetExitStatus(exit_status, exit_string.c_str()); 1864 1865 StopAsyncThread (); 1866 KillDebugserverProcess (); 1867 return error; 1868} 1869 1870//------------------------------------------------------------------ 1871// Process Queries 1872//------------------------------------------------------------------ 1873 1874bool 1875ProcessGDBRemote::IsAlive () 1876{ 1877 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 1878} 1879 1880addr_t 1881ProcessGDBRemote::GetImageInfoAddress() 1882{ 1883 return m_gdb_comm.GetShlibInfoAddr(); 1884} 1885 1886//------------------------------------------------------------------ 1887// Process Memory 1888//------------------------------------------------------------------ 1889size_t 1890ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1891{ 1892 if (size > m_max_memory_size) 1893 { 1894 // Keep memory read sizes down to a sane limit. This function will be 1895 // called multiple times in order to complete the task by 1896 // lldb_private::Process so it is ok to do this. 1897 size = m_max_memory_size; 1898 } 1899 1900 char packet[64]; 1901 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1902 assert (packet_len + 1 < sizeof(packet)); 1903 StringExtractorGDBRemote response; 1904 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true)) 1905 { 1906 if (response.IsNormalResponse()) 1907 { 1908 error.Clear(); 1909 return response.GetHexBytes(buf, size, '\xdd'); 1910 } 1911 else if (response.IsErrorResponse()) 1912 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1913 else if (response.IsUnsupportedResponse()) 1914 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1915 else 1916 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1917 } 1918 else 1919 { 1920 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1921 } 1922 return 0; 1923} 1924 1925size_t 1926ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1927{ 1928 if (size > m_max_memory_size) 1929 { 1930 // Keep memory read sizes down to a sane limit. This function will be 1931 // called multiple times in order to complete the task by 1932 // lldb_private::Process so it is ok to do this. 1933 size = m_max_memory_size; 1934 } 1935 1936 StreamString packet; 1937 packet.Printf("M%llx,%zx:", addr, size); 1938 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1939 StringExtractorGDBRemote response; 1940 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true)) 1941 { 1942 if (response.IsOKResponse()) 1943 { 1944 error.Clear(); 1945 return size; 1946 } 1947 else if (response.IsErrorResponse()) 1948 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1949 else if (response.IsUnsupportedResponse()) 1950 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1951 else 1952 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1953 } 1954 else 1955 { 1956 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1957 } 1958 return 0; 1959} 1960 1961lldb::addr_t 1962ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1963{ 1964 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 1965 1966 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 1967 switch (supported) 1968 { 1969 case eLazyBoolCalculate: 1970 case eLazyBoolYes: 1971 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 1972 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 1973 return allocated_addr; 1974 1975 case eLazyBoolNo: 1976 // Call mmap() to create memory in the inferior.. 1977 unsigned prot = 0; 1978 if (permissions & lldb::ePermissionsReadable) 1979 prot |= eMmapProtRead; 1980 if (permissions & lldb::ePermissionsWritable) 1981 prot |= eMmapProtWrite; 1982 if (permissions & lldb::ePermissionsExecutable) 1983 prot |= eMmapProtExec; 1984 1985 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 1986 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 1987 m_addr_to_mmap_size[allocated_addr] = size; 1988 else 1989 allocated_addr = LLDB_INVALID_ADDRESS; 1990 break; 1991 } 1992 1993 if (allocated_addr == LLDB_INVALID_ADDRESS) 1994 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 1995 else 1996 error.Clear(); 1997 return allocated_addr; 1998} 1999 2000Error 2001ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 2002 MemoryRegionInfo ®ion_info) 2003{ 2004 2005 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 2006 return error; 2007} 2008 2009Error 2010ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 2011{ 2012 2013 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 2014 return error; 2015} 2016 2017Error 2018ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 2019{ 2020 Error error; 2021 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2022 2023 switch (supported) 2024 { 2025 case eLazyBoolCalculate: 2026 // We should never be deallocating memory without allocating memory 2027 // first so we should never get eLazyBoolCalculate 2028 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 2029 break; 2030 2031 case eLazyBoolYes: 2032 if (!m_gdb_comm.DeallocateMemory (addr)) 2033 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2034 break; 2035 2036 case eLazyBoolNo: 2037 // Call munmap() to deallocate memory in the inferior.. 2038 { 2039 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2040 if (pos != m_addr_to_mmap_size.end() && 2041 InferiorCallMunmap(this, addr, pos->second)) 2042 m_addr_to_mmap_size.erase (pos); 2043 else 2044 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2045 } 2046 break; 2047 } 2048 2049 return error; 2050} 2051 2052 2053//------------------------------------------------------------------ 2054// Process STDIO 2055//------------------------------------------------------------------ 2056size_t 2057ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 2058{ 2059 if (m_stdio_communication.IsConnected()) 2060 { 2061 ConnectionStatus status; 2062 m_stdio_communication.Write(src, src_len, status, NULL); 2063 } 2064 return 0; 2065} 2066 2067Error 2068ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 2069{ 2070 Error error; 2071 assert (bp_site != NULL); 2072 2073 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2074 user_id_t site_id = bp_site->GetID(); 2075 const addr_t addr = bp_site->GetLoadAddress(); 2076 if (log) 2077 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr); 2078 2079 if (bp_site->IsEnabled()) 2080 { 2081 if (log) 2082 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 2083 return error; 2084 } 2085 else 2086 { 2087 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2088 2089 if (bp_site->HardwarePreferred()) 2090 { 2091 // Try and set hardware breakpoint, and if that fails, fall through 2092 // and set a software breakpoint? 2093 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware)) 2094 { 2095 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 2096 { 2097 bp_site->SetEnabled(true); 2098 bp_site->SetType (BreakpointSite::eHardware); 2099 return error; 2100 } 2101 } 2102 } 2103 2104 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware)) 2105 { 2106 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 2107 { 2108 bp_site->SetEnabled(true); 2109 bp_site->SetType (BreakpointSite::eExternal); 2110 return error; 2111 } 2112 } 2113 2114 return EnableSoftwareBreakpoint (bp_site); 2115 } 2116 2117 if (log) 2118 { 2119 const char *err_string = error.AsCString(); 2120 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 2121 bp_site->GetLoadAddress(), 2122 err_string ? err_string : "NULL"); 2123 } 2124 // We shouldn't reach here on a successful breakpoint enable... 2125 if (error.Success()) 2126 error.SetErrorToGenericError(); 2127 return error; 2128} 2129 2130Error 2131ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 2132{ 2133 Error error; 2134 assert (bp_site != NULL); 2135 addr_t addr = bp_site->GetLoadAddress(); 2136 user_id_t site_id = bp_site->GetID(); 2137 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2138 if (log) 2139 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr); 2140 2141 if (bp_site->IsEnabled()) 2142 { 2143 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2144 2145 BreakpointSite::Type bp_type = bp_site->GetType(); 2146 switch (bp_type) 2147 { 2148 case BreakpointSite::eSoftware: 2149 error = DisableSoftwareBreakpoint (bp_site); 2150 break; 2151 2152 case BreakpointSite::eHardware: 2153 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2154 error.SetErrorToGenericError(); 2155 break; 2156 2157 case BreakpointSite::eExternal: 2158 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2159 error.SetErrorToGenericError(); 2160 break; 2161 } 2162 if (error.Success()) 2163 bp_site->SetEnabled(false); 2164 } 2165 else 2166 { 2167 if (log) 2168 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 2169 return error; 2170 } 2171 2172 if (error.Success()) 2173 error.SetErrorToGenericError(); 2174 return error; 2175} 2176 2177// Pre-requisite: wp != NULL. 2178static GDBStoppointType 2179GetGDBStoppointType (Watchpoint *wp) 2180{ 2181 assert(wp); 2182 bool watch_read = wp->WatchpointRead(); 2183 bool watch_write = wp->WatchpointWrite(); 2184 2185 // watch_read and watch_write cannot both be false. 2186 assert(watch_read || watch_write); 2187 if (watch_read && watch_write) 2188 return eWatchpointReadWrite; 2189 else if (watch_read) 2190 return eWatchpointRead; 2191 else // Must be watch_write, then. 2192 return eWatchpointWrite; 2193} 2194 2195Error 2196ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp) 2197{ 2198 Error error; 2199 if (wp) 2200 { 2201 user_id_t watchID = wp->GetID(); 2202 addr_t addr = wp->GetLoadAddress(); 2203 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2204 if (log) 2205 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID); 2206 if (wp->IsEnabled()) 2207 { 2208 if (log) 2209 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 2210 return error; 2211 } 2212 2213 GDBStoppointType type = GetGDBStoppointType(wp); 2214 // Pass down an appropriate z/Z packet... 2215 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 2216 { 2217 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 2218 { 2219 wp->SetEnabled(true); 2220 return error; 2221 } 2222 else 2223 error.SetErrorString("sending gdb watchpoint packet failed"); 2224 } 2225 else 2226 error.SetErrorString("watchpoints not supported"); 2227 } 2228 else 2229 { 2230 error.SetErrorString("Watchpoint argument was NULL."); 2231 } 2232 if (error.Success()) 2233 error.SetErrorToGenericError(); 2234 return error; 2235} 2236 2237Error 2238ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp) 2239{ 2240 Error error; 2241 if (wp) 2242 { 2243 user_id_t watchID = wp->GetID(); 2244 2245 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2246 2247 addr_t addr = wp->GetLoadAddress(); 2248 if (log) 2249 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr); 2250 2251 if (!wp->IsEnabled()) 2252 { 2253 if (log) 2254 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 2255 return error; 2256 } 2257 2258 if (wp->IsHardware()) 2259 { 2260 GDBStoppointType type = GetGDBStoppointType(wp); 2261 // Pass down an appropriate z/Z packet... 2262 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 2263 { 2264 wp->SetEnabled(false); 2265 return error; 2266 } 2267 else 2268 error.SetErrorString("sending gdb watchpoint packet failed"); 2269 } 2270 // TODO: clear software watchpoints if we implement them 2271 } 2272 else 2273 { 2274 error.SetErrorString("Watchpoint argument was NULL."); 2275 } 2276 if (error.Success()) 2277 error.SetErrorToGenericError(); 2278 return error; 2279} 2280 2281void 2282ProcessGDBRemote::Clear() 2283{ 2284 m_flags = 0; 2285 m_thread_list.Clear(); 2286} 2287 2288Error 2289ProcessGDBRemote::DoSignal (int signo) 2290{ 2291 Error error; 2292 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2293 if (log) 2294 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2295 2296 if (!m_gdb_comm.SendAsyncSignal (signo)) 2297 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2298 return error; 2299} 2300 2301Error 2302ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) 2303{ 2304 ProcessLaunchInfo launch_info; 2305 return StartDebugserverProcess(debugserver_url, launch_info); 2306} 2307 2308Error 2309ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 2310{ 2311 Error error; 2312 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2313 { 2314 // If we locate debugserver, keep that located version around 2315 static FileSpec g_debugserver_file_spec; 2316 2317 ProcessLaunchInfo debugserver_launch_info; 2318 char debugserver_path[PATH_MAX]; 2319 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile(); 2320 2321 // Always check to see if we have an environment override for the path 2322 // to the debugserver to use and use it if we do. 2323 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 2324 if (env_debugserver_path) 2325 debugserver_file_spec.SetFile (env_debugserver_path, false); 2326 else 2327 debugserver_file_spec = g_debugserver_file_spec; 2328 bool debugserver_exists = debugserver_file_spec.Exists(); 2329 if (!debugserver_exists) 2330 { 2331 // The debugserver binary is in the LLDB.framework/Resources 2332 // directory. 2333 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 2334 { 2335 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 2336 debugserver_exists = debugserver_file_spec.Exists(); 2337 if (debugserver_exists) 2338 { 2339 g_debugserver_file_spec = debugserver_file_spec; 2340 } 2341 else 2342 { 2343 g_debugserver_file_spec.Clear(); 2344 debugserver_file_spec.Clear(); 2345 } 2346 } 2347 } 2348 2349 if (debugserver_exists) 2350 { 2351 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 2352 2353 m_stdio_communication.Clear(); 2354 2355 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2356 2357 Args &debugserver_args = debugserver_launch_info.GetArguments(); 2358 char arg_cstr[PATH_MAX]; 2359 2360 // Start args with "debugserver /file/path -r --" 2361 debugserver_args.AppendArgument(debugserver_path); 2362 debugserver_args.AppendArgument(debugserver_url); 2363 // use native registers, not the GDB registers 2364 debugserver_args.AppendArgument("--native-regs"); 2365 // make debugserver run in its own session so signals generated by 2366 // special terminal key sequences (^C) don't affect debugserver 2367 debugserver_args.AppendArgument("--setsid"); 2368 2369 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 2370 if (env_debugserver_log_file) 2371 { 2372 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 2373 debugserver_args.AppendArgument(arg_cstr); 2374 } 2375 2376 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 2377 if (env_debugserver_log_flags) 2378 { 2379 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 2380 debugserver_args.AppendArgument(arg_cstr); 2381 } 2382// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 2383// debugserver_args.AppendArgument("--log-flags=0x802e0e"); 2384 2385 // We currently send down all arguments, attach pids, or attach 2386 // process names in dedicated GDB server packets, so we don't need 2387 // to pass them as arguments. This is currently because of all the 2388 // things we need to setup prior to launching: the environment, 2389 // current working dir, file actions, etc. 2390#if 0 2391 // Now append the program arguments 2392 if (inferior_argv) 2393 { 2394 // Terminate the debugserver args so we can now append the inferior args 2395 debugserver_args.AppendArgument("--"); 2396 2397 for (int i = 0; inferior_argv[i] != NULL; ++i) 2398 debugserver_args.AppendArgument (inferior_argv[i]); 2399 } 2400 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 2401 { 2402 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 2403 debugserver_args.AppendArgument (arg_cstr); 2404 } 2405 else if (attach_name && attach_name[0]) 2406 { 2407 if (wait_for_launch) 2408 debugserver_args.AppendArgument ("--waitfor"); 2409 else 2410 debugserver_args.AppendArgument ("--attach"); 2411 debugserver_args.AppendArgument (attach_name); 2412 } 2413#endif 2414 2415 ProcessLaunchInfo::FileAction file_action; 2416 2417 // Close STDIN, STDOUT and STDERR. We might need to redirect them 2418 // to "/dev/null" if we run into any problems. 2419 file_action.Close (STDIN_FILENO); 2420 debugserver_launch_info.AppendFileAction (file_action); 2421 file_action.Close (STDOUT_FILENO); 2422 debugserver_launch_info.AppendFileAction (file_action); 2423 file_action.Close (STDERR_FILENO); 2424 debugserver_launch_info.AppendFileAction (file_action); 2425 2426 if (log) 2427 { 2428 StreamString strm; 2429 debugserver_args.Dump (&strm); 2430 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 2431 } 2432 2433 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 2434 debugserver_launch_info.SetUserID(process_info.GetUserID()); 2435 2436 error = Host::LaunchProcess(debugserver_launch_info); 2437 2438 if (error.Success ()) 2439 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 2440 else 2441 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2442 2443 if (error.Fail() || log) 2444 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path); 2445 } 2446 else 2447 { 2448 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME); 2449 } 2450 2451 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2452 StartAsyncThread (); 2453 } 2454 return error; 2455} 2456 2457bool 2458ProcessGDBRemote::MonitorDebugserverProcess 2459( 2460 void *callback_baton, 2461 lldb::pid_t debugserver_pid, 2462 bool exited, // True if the process did exit 2463 int signo, // Zero for no signal 2464 int exit_status // Exit value of process if signal is zero 2465) 2466{ 2467 // The baton is a "ProcessGDBRemote *". Now this class might be gone 2468 // and might not exist anymore, so we need to carefully try to get the 2469 // target for this process first since we have a race condition when 2470 // we are done running between getting the notice that the inferior 2471 // process has died and the debugserver that was debugging this process. 2472 // In our test suite, we are also continually running process after 2473 // process, so we must be very careful to make sure: 2474 // 1 - process object hasn't been deleted already 2475 // 2 - that a new process object hasn't been recreated in its place 2476 2477 // "debugserver_pid" argument passed in is the process ID for 2478 // debugserver that we are tracking... 2479 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2480 2481 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2482 2483 // Get a shared pointer to the target that has a matching process pointer. 2484 // This target could be gone, or the target could already have a new process 2485 // object inside of it 2486 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 2487 2488 if (log) 2489 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2490 2491 if (target_sp) 2492 { 2493 // We found a process in a target that matches, but another thread 2494 // might be in the process of launching a new process that will 2495 // soon replace it, so get a shared pointer to the process so we 2496 // can keep it alive. 2497 ProcessSP process_sp (target_sp->GetProcessSP()); 2498 // Now we have a shared pointer to the process that can't go away on us 2499 // so we now make sure it was the same as the one passed in, and also make 2500 // sure that our previous "process *" didn't get deleted and have a new 2501 // "process *" created in its place with the same pointer. To verify this 2502 // we make sure the process has our debugserver process ID. If we pass all 2503 // of these tests, then we are sure that this process is the one we were 2504 // looking for. 2505 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 2506 { 2507 // Sleep for a half a second to make sure our inferior process has 2508 // time to set its exit status before we set it incorrectly when 2509 // both the debugserver and the inferior process shut down. 2510 usleep (500000); 2511 // If our process hasn't yet exited, debugserver might have died. 2512 // If the process did exit, the we are reaping it. 2513 const StateType state = process->GetState(); 2514 2515 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2516 state != eStateInvalid && 2517 state != eStateUnloaded && 2518 state != eStateExited && 2519 state != eStateDetached) 2520 { 2521 char error_str[1024]; 2522 if (signo) 2523 { 2524 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2525 if (signal_cstr) 2526 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2527 else 2528 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2529 } 2530 else 2531 { 2532 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2533 } 2534 2535 process->SetExitStatus (-1, error_str); 2536 } 2537 // Debugserver has exited we need to let our ProcessGDBRemote 2538 // know that it no longer has a debugserver instance 2539 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2540 } 2541 } 2542 return true; 2543} 2544 2545void 2546ProcessGDBRemote::KillDebugserverProcess () 2547{ 2548 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2549 { 2550 ::kill (m_debugserver_pid, SIGINT); 2551 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2552 } 2553} 2554 2555void 2556ProcessGDBRemote::Initialize() 2557{ 2558 static bool g_initialized = false; 2559 2560 if (g_initialized == false) 2561 { 2562 g_initialized = true; 2563 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2564 GetPluginDescriptionStatic(), 2565 CreateInstance); 2566 2567 Log::Callbacks log_callbacks = { 2568 ProcessGDBRemoteLog::DisableLog, 2569 ProcessGDBRemoteLog::EnableLog, 2570 ProcessGDBRemoteLog::ListLogCategories 2571 }; 2572 2573 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2574 } 2575} 2576 2577bool 2578ProcessGDBRemote::StartAsyncThread () 2579{ 2580 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2581 2582 if (log) 2583 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2584 2585 // Create a thread that watches our internal state and controls which 2586 // events make it to clients (into the DCProcess event queue). 2587 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2588 return IS_VALID_LLDB_HOST_THREAD(m_async_thread); 2589} 2590 2591void 2592ProcessGDBRemote::StopAsyncThread () 2593{ 2594 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2595 2596 if (log) 2597 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2598 2599 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2600 2601 // This will shut down the async thread. 2602 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2603 2604 // Stop the stdio thread 2605 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2606 { 2607 Host::ThreadJoin (m_async_thread, NULL, NULL); 2608 } 2609} 2610 2611 2612void * 2613ProcessGDBRemote::AsyncThread (void *arg) 2614{ 2615 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2616 2617 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2618 if (log) 2619 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID()); 2620 2621 Listener listener ("ProcessGDBRemote::AsyncThread"); 2622 EventSP event_sp; 2623 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2624 eBroadcastBitAsyncThreadShouldExit; 2625 2626 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2627 { 2628 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2629 2630 bool done = false; 2631 while (!done) 2632 { 2633 if (log) 2634 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2635 if (listener.WaitForEvent (NULL, event_sp)) 2636 { 2637 const uint32_t event_type = event_sp->GetType(); 2638 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2639 { 2640 if (log) 2641 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2642 2643 switch (event_type) 2644 { 2645 case eBroadcastBitAsyncContinue: 2646 { 2647 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2648 2649 if (continue_packet) 2650 { 2651 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2652 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2653 if (log) 2654 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2655 2656 if (::strstr (continue_cstr, "vAttach") == NULL) 2657 process->SetPrivateState(eStateRunning); 2658 StringExtractorGDBRemote response; 2659 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2660 2661 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 2662 // The thread ID list might be contained within the "response", or the stop reply packet that 2663 // caused the stop. So clear it now before we give the stop reply packet to the process 2664 // using the process->SetLastStopPacket()... 2665 process->ClearThreadIDList (); 2666 2667 switch (stop_state) 2668 { 2669 case eStateStopped: 2670 case eStateCrashed: 2671 case eStateSuspended: 2672 process->SetLastStopPacket (response); 2673 process->SetPrivateState (stop_state); 2674 break; 2675 2676 case eStateExited: 2677 process->SetLastStopPacket (response); 2678 process->ClearThreadIDList(); 2679 response.SetFilePos(1); 2680 process->SetExitStatus(response.GetHexU8(), NULL); 2681 done = true; 2682 break; 2683 2684 case eStateInvalid: 2685 process->SetExitStatus(-1, "lost connection"); 2686 break; 2687 2688 default: 2689 process->SetPrivateState (stop_state); 2690 break; 2691 } 2692 } 2693 } 2694 break; 2695 2696 case eBroadcastBitAsyncThreadShouldExit: 2697 if (log) 2698 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2699 done = true; 2700 break; 2701 2702 default: 2703 if (log) 2704 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2705 done = true; 2706 break; 2707 } 2708 } 2709 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 2710 { 2711 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 2712 { 2713 process->SetExitStatus (-1, "lost connection"); 2714 done = true; 2715 } 2716 } 2717 } 2718 else 2719 { 2720 if (log) 2721 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2722 done = true; 2723 } 2724 } 2725 } 2726 2727 if (log) 2728 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID()); 2729 2730 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2731 return NULL; 2732} 2733 2734const char * 2735ProcessGDBRemote::GetDispatchQueueNameForThread 2736( 2737 addr_t thread_dispatch_qaddr, 2738 std::string &dispatch_queue_name 2739) 2740{ 2741 dispatch_queue_name.clear(); 2742 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2743 { 2744 // Cache the dispatch_queue_offsets_addr value so we don't always have 2745 // to look it up 2746 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2747 { 2748 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); 2749 const Symbol *dispatch_queue_offsets_symbol = NULL; 2750 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false)); 2751 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec)); 2752 if (module_sp) 2753 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2754 2755 if (dispatch_queue_offsets_symbol == NULL) 2756 { 2757 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false)); 2758 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec); 2759 if (module_sp) 2760 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2761 } 2762 if (dispatch_queue_offsets_symbol) 2763 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target); 2764 2765 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2766 return NULL; 2767 } 2768 2769 uint8_t memory_buffer[8]; 2770 DataExtractor data (memory_buffer, 2771 sizeof(memory_buffer), 2772 m_target.GetArchitecture().GetByteOrder(), 2773 m_target.GetArchitecture().GetAddressByteSize()); 2774 2775 // Excerpt from src/queue_private.h 2776 struct dispatch_queue_offsets_s 2777 { 2778 uint16_t dqo_version; 2779 uint16_t dqo_label; 2780 uint16_t dqo_label_size; 2781 } dispatch_queue_offsets; 2782 2783 2784 Error error; 2785 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2786 { 2787 uint32_t data_offset = 0; 2788 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2789 { 2790 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2791 { 2792 data_offset = 0; 2793 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2794 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2795 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2796 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2797 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2798 dispatch_queue_name.erase (bytes_read); 2799 } 2800 } 2801 } 2802 } 2803 if (dispatch_queue_name.empty()) 2804 return NULL; 2805 return dispatch_queue_name.c_str(); 2806} 2807 2808//uint32_t 2809//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2810//{ 2811// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 2812// // process and ask it for the list of processes. But if we are local, we can let the Host do it. 2813// if (m_local_debugserver) 2814// { 2815// return Host::ListProcessesMatchingName (name, matches, pids); 2816// } 2817// else 2818// { 2819// // FIXME: Implement talking to the remote debugserver. 2820// return 0; 2821// } 2822// 2823//} 2824// 2825bool 2826ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 2827 lldb_private::StoppointCallbackContext *context, 2828 lldb::user_id_t break_id, 2829 lldb::user_id_t break_loc_id) 2830{ 2831 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 2832 // run so I can stop it if that's what I want to do. 2833 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2834 if (log) 2835 log->Printf("Hit New Thread Notification breakpoint."); 2836 return false; 2837} 2838 2839 2840bool 2841ProcessGDBRemote::StartNoticingNewThreads() 2842{ 2843 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2844 if (m_thread_create_bp_sp) 2845 { 2846 if (log && log->GetVerbose()) 2847 log->Printf("Enabled noticing new thread breakpoint."); 2848 m_thread_create_bp_sp->SetEnabled(true); 2849 } 2850 else 2851 { 2852 PlatformSP platform_sp (m_target.GetPlatform()); 2853 if (platform_sp) 2854 { 2855 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 2856 if (m_thread_create_bp_sp) 2857 { 2858 if (log && log->GetVerbose()) 2859 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 2860 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 2861 } 2862 else 2863 { 2864 if (log) 2865 log->Printf("Failed to create new thread notification breakpoint."); 2866 } 2867 } 2868 } 2869 return m_thread_create_bp_sp.get() != NULL; 2870} 2871 2872bool 2873ProcessGDBRemote::StopNoticingNewThreads() 2874{ 2875 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2876 if (log && log->GetVerbose()) 2877 log->Printf ("Disabling new thread notification breakpoint."); 2878 2879 if (m_thread_create_bp_sp) 2880 m_thread_create_bp_sp->SetEnabled(false); 2881 2882 return true; 2883} 2884 2885 2886