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