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 58 namespace 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" 78 using namespace lldb; 79 using namespace lldb_private; 80 81 static bool rand_initialized = false; 82 83 static inline uint16_t 84 get_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 97 const char * 98 ProcessGDBRemote::GetPluginNameStatic() 99 { 100 return "gdb-remote"; 101 } 102 103 const char * 104 ProcessGDBRemote::GetPluginDescriptionStatic() 105 { 106 return "GDB Remote protocol based debugging plug-in."; 107 } 108 109 void 110 ProcessGDBRemote::Terminate() 111 { 112 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 113 } 114 115 116 lldb::ProcessSP 117 ProcessGDBRemote::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 125 bool 126 ProcessGDBRemote::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 //---------------------------------------------------------------------- 160 ProcessGDBRemote::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 //---------------------------------------------------------------------- 190 ProcessGDBRemote::~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 //---------------------------------------------------------------------- 204 const char * 205 ProcessGDBRemote::GetPluginName() 206 { 207 return "Process debugging plug-in that uses the GDB remote protocol"; 208 } 209 210 const char * 211 ProcessGDBRemote::GetShortPluginName() 212 { 213 return GetPluginNameStatic(); 214 } 215 216 uint32_t 217 ProcessGDBRemote::GetPluginVersion() 218 { 219 return 1; 220 } 221 222 void 223 ProcessGDBRemote::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 414 Error 415 ProcessGDBRemote::WillLaunch (Module* module) 416 { 417 return WillLaunchOrAttach (); 418 } 419 420 Error 421 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 422 { 423 return WillLaunchOrAttach (); 424 } 425 426 Error 427 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 428 { 429 return WillLaunchOrAttach (); 430 } 431 432 Error 433 ProcessGDBRemote::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 483 Error 484 ProcessGDBRemote::WillLaunchOrAttach () 485 { 486 Error error; 487 m_stdio_communication.Clear (); 488 return error; 489 } 490 491 //---------------------------------------------------------------------- 492 // Process Control 493 //---------------------------------------------------------------------- 494 Error 495 ProcessGDBRemote::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 683 Error 684 ProcessGDBRemote::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 745 void 746 ProcessGDBRemote::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 807 void 808 ProcessGDBRemote::DidLaunch () 809 { 810 DidLaunchOrAttach (); 811 } 812 813 Error 814 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid) 815 { 816 ProcessAttachInfo attach_info; 817 return DoAttachToProcessWithID(attach_pid, attach_info); 818 } 819 820 Error 821 ProcessGDBRemote::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 863 size_t 864 ProcessGDBRemote::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 884 Error 885 ProcessGDBRemote::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 935 void 936 ProcessGDBRemote::DidAttach () 937 { 938 DidLaunchOrAttach (); 939 } 940 941 Error 942 ProcessGDBRemote::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 951 Error 952 ProcessGDBRemote::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 1188 void 1189 ProcessGDBRemote::ClearThreadIDList () 1190 { 1191 Mutex::Locker locker(m_thread_list.GetMutex()); 1192 m_thread_ids.clear(); 1193 } 1194 1195 bool 1196 ProcessGDBRemote::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 1208 bool 1209 ProcessGDBRemote::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 1242 StateType 1243 ProcessGDBRemote::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 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1427 { 1428 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1429 handled = true; 1430 } 1431 } 1432 1433 if (!handled) 1434 { 1435 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1436 } 1437 } 1438 else if (reason.compare("trap") == 0) 1439 { 1440 // Let the trap just use the standard signal stop reason below... 1441 } 1442 else if (reason.compare("watchpoint") == 0) 1443 { 1444 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1445 // TODO: locate the watchpoint somehow... 1446 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1447 handled = true; 1448 } 1449 else if (reason.compare("exception") == 0) 1450 { 1451 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1452 handled = true; 1453 } 1454 } 1455 1456 if (signo) 1457 { 1458 if (signo == SIGTRAP) 1459 { 1460 // Currently we are going to assume SIGTRAP means we are either 1461 // hitting a breakpoint or hardware single stepping. 1462 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1463 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1464 if (bp_site_sp) 1465 { 1466 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1467 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1468 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1469 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1470 { 1471 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1472 handled = true; 1473 } 1474 } 1475 if (!handled) 1476 { 1477 // TODO: check for breakpoint or trap opcode in case there is a hard 1478 // coded software trap 1479 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1480 handled = true; 1481 } 1482 } 1483 if (!handled) 1484 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1485 } 1486 else 1487 { 1488 StopInfoSP invalid_stop_info_sp; 1489 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1490 } 1491 1492 if (!description.empty()) 1493 { 1494 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ()); 1495 if (stop_info_sp) 1496 { 1497 stop_info_sp->SetDescription (description.c_str()); 1498 } 1499 else 1500 { 1501 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1502 } 1503 } 1504 } 1505 } 1506 return eStateStopped; 1507 } 1508 break; 1509 1510 case 'W': 1511 // process exited 1512 return eStateExited; 1513 1514 default: 1515 break; 1516 } 1517 return eStateInvalid; 1518 } 1519 1520 void 1521 ProcessGDBRemote::RefreshStateAfterStop () 1522 { 1523 Mutex::Locker locker(m_thread_list.GetMutex()); 1524 m_thread_ids.clear(); 1525 // Set the thread stop info. It might have a "threads" key whose value is 1526 // a list of all thread IDs in the current process, so m_thread_ids might 1527 // get set. 1528 SetThreadStopInfo (m_last_stop_packet); 1529 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 1530 if (m_thread_ids.empty()) 1531 { 1532 // No, we need to fetch the thread list manually 1533 UpdateThreadIDList(); 1534 } 1535 1536 // Let all threads recover from stopping and do any clean up based 1537 // on the previous thread state (if any). 1538 m_thread_list.RefreshStateAfterStop(); 1539 1540 } 1541 1542 Error 1543 ProcessGDBRemote::DoHalt (bool &caused_stop) 1544 { 1545 Error error; 1546 1547 bool timed_out = false; 1548 Mutex::Locker locker; 1549 1550 if (m_public_state.GetValue() == eStateAttaching) 1551 { 1552 // We are being asked to halt during an attach. We need to just close 1553 // our file handle and debugserver will go away, and we can be done... 1554 m_gdb_comm.Disconnect(); 1555 } 1556 else 1557 { 1558 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 1559 { 1560 if (timed_out) 1561 error.SetErrorString("timed out sending interrupt packet"); 1562 else 1563 error.SetErrorString("unknown error sending interrupt packet"); 1564 } 1565 1566 caused_stop = m_gdb_comm.GetInterruptWasSent (); 1567 } 1568 return error; 1569 } 1570 1571 Error 1572 ProcessGDBRemote::InterruptIfRunning 1573 ( 1574 bool discard_thread_plans, 1575 bool catch_stop_event, 1576 EventSP &stop_event_sp 1577 ) 1578 { 1579 Error error; 1580 1581 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1582 1583 bool paused_private_state_thread = false; 1584 const bool is_running = m_gdb_comm.IsRunning(); 1585 if (log) 1586 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i", 1587 discard_thread_plans, 1588 catch_stop_event, 1589 is_running); 1590 1591 if (discard_thread_plans) 1592 { 1593 if (log) 1594 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans"); 1595 m_thread_list.DiscardThreadPlans(); 1596 } 1597 if (is_running) 1598 { 1599 if (catch_stop_event) 1600 { 1601 if (log) 1602 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread"); 1603 PausePrivateStateThread(); 1604 paused_private_state_thread = true; 1605 } 1606 1607 bool timed_out = false; 1608 Mutex::Locker locker; 1609 1610 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out)) 1611 { 1612 if (timed_out) 1613 error.SetErrorString("timed out sending interrupt packet"); 1614 else 1615 error.SetErrorString("unknown error sending interrupt packet"); 1616 if (paused_private_state_thread) 1617 ResumePrivateStateThread(); 1618 return error; 1619 } 1620 1621 if (catch_stop_event) 1622 { 1623 // LISTEN HERE 1624 TimeValue timeout_time; 1625 timeout_time = TimeValue::Now(); 1626 timeout_time.OffsetWithSeconds(5); 1627 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp); 1628 1629 timed_out = state == eStateInvalid; 1630 if (log) 1631 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out); 1632 1633 if (timed_out) 1634 error.SetErrorString("unable to verify target stopped"); 1635 } 1636 1637 if (paused_private_state_thread) 1638 { 1639 if (log) 1640 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread"); 1641 ResumePrivateStateThread(); 1642 } 1643 } 1644 return error; 1645 } 1646 1647 Error 1648 ProcessGDBRemote::WillDetach () 1649 { 1650 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1651 if (log) 1652 log->Printf ("ProcessGDBRemote::WillDetach()"); 1653 1654 bool discard_thread_plans = true; 1655 bool catch_stop_event = true; 1656 EventSP event_sp; 1657 1658 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is 1659 // needed. This shouldn't be a feature of a particular plugin. 1660 1661 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp); 1662 } 1663 1664 Error 1665 ProcessGDBRemote::DoDetach() 1666 { 1667 Error error; 1668 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1669 if (log) 1670 log->Printf ("ProcessGDBRemote::DoDetach()"); 1671 1672 DisableAllBreakpointSites (); 1673 1674 m_thread_list.DiscardThreadPlans(); 1675 1676 bool success = m_gdb_comm.Detach (); 1677 if (log) 1678 { 1679 if (success) 1680 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1681 else 1682 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed"); 1683 } 1684 // Sleep for one second to let the process get all detached... 1685 StopAsyncThread (); 1686 1687 SetPrivateState (eStateDetached); 1688 ResumePrivateStateThread(); 1689 1690 //KillDebugserverProcess (); 1691 return error; 1692 } 1693 1694 1695 Error 1696 ProcessGDBRemote::DoDestroy () 1697 { 1698 Error error; 1699 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1700 if (log) 1701 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1702 1703 // There is a bug in older iOS debugservers where they don't shut down the process 1704 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 1705 // this can cause problems with restarting. So we check to see if any of our threads are stopped 1706 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 1707 // destroy it again. 1708 // 1709 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 1710 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 1711 // the debugservers with this bug are equal. There really should be a better way to test this! 1712 // 1713 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 1714 // get called here to destroy again and we're still at a breakpoint or exception, then we should 1715 // just do the straight-forward kill. 1716 // 1717 // And of course, if we weren't able to stop the process by the time we get here, it isn't 1718 // necessary (or helpful) to do any of this. 1719 1720 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 1721 { 1722 PlatformSP platform_sp = GetTarget().GetPlatform(); 1723 1724 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 1725 if (platform_sp 1726 && platform_sp->GetName() 1727 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0) 1728 { 1729 if (m_destroy_tried_resuming) 1730 { 1731 if (log) 1732 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again."); 1733 } 1734 else 1735 { 1736 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 1737 // but we really need it to happen here and it doesn't matter if we do it twice. 1738 m_thread_list.DiscardThreadPlans(); 1739 DisableAllBreakpointSites(); 1740 1741 bool stop_looks_like_crash = false; 1742 ThreadList &threads = GetThreadList(); 1743 1744 { 1745 Mutex::Locker(threads.GetMutex()); 1746 1747 size_t num_threads = threads.GetSize(); 1748 for (size_t i = 0; i < num_threads; i++) 1749 { 1750 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1751 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1752 StopReason reason = eStopReasonInvalid; 1753 if (stop_info_sp) 1754 reason = stop_info_sp->GetStopReason(); 1755 if (reason == eStopReasonBreakpoint 1756 || reason == eStopReasonException) 1757 { 1758 if (log) 1759 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.", 1760 thread_sp->GetID(), 1761 stop_info_sp->GetDescription()); 1762 stop_looks_like_crash = true; 1763 break; 1764 } 1765 } 1766 } 1767 1768 if (stop_looks_like_crash) 1769 { 1770 if (log) 1771 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 1772 m_destroy_tried_resuming = true; 1773 1774 // If we are going to run again before killing, it would be good to suspend all the threads 1775 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 1776 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 1777 // have to run the risk of letting those threads proceed a bit. 1778 1779 { 1780 Mutex::Locker(threads.GetMutex()); 1781 1782 size_t num_threads = threads.GetSize(); 1783 for (size_t i = 0; i < num_threads; i++) 1784 { 1785 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1786 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1787 StopReason reason = eStopReasonInvalid; 1788 if (stop_info_sp) 1789 reason = stop_info_sp->GetStopReason(); 1790 if (reason != eStopReasonBreakpoint 1791 && reason != eStopReasonException) 1792 { 1793 if (log) 1794 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.", 1795 thread_sp->GetID()); 1796 thread_sp->SetResumeState(eStateSuspended); 1797 } 1798 } 1799 } 1800 Resume (); 1801 return Destroy(); 1802 } 1803 } 1804 } 1805 } 1806 1807 // Interrupt if our inferior is running... 1808 int exit_status = SIGABRT; 1809 std::string exit_string; 1810 1811 if (m_gdb_comm.IsConnected()) 1812 { 1813 if (m_public_state.GetValue() != eStateAttaching) 1814 { 1815 1816 StringExtractorGDBRemote response; 1817 bool send_async = true; 1818 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async)) 1819 { 1820 char packet_cmd = response.GetChar(0); 1821 1822 if (packet_cmd == 'W' || packet_cmd == 'X') 1823 { 1824 SetLastStopPacket (response); 1825 ClearThreadIDList (); 1826 exit_status = response.GetHexU8(); 1827 } 1828 else 1829 { 1830 if (log) 1831 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 1832 exit_string.assign("got unexpected response to k packet: "); 1833 exit_string.append(response.GetStringRef()); 1834 } 1835 } 1836 else 1837 { 1838 if (log) 1839 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1840 exit_string.assign("failed to send the k packet"); 1841 } 1842 } 1843 else 1844 { 1845 if (log) 1846 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1847 exit_string.assign ("killing while attaching."); 1848 } 1849 } 1850 else 1851 { 1852 // If we missed setting the exit status on the way out, do it here. 1853 // NB set exit status can be called multiple times, the first one sets the status. 1854 exit_string.assign("destroying when not connected to debugserver"); 1855 } 1856 1857 SetExitStatus(exit_status, exit_string.c_str()); 1858 1859 StopAsyncThread (); 1860 KillDebugserverProcess (); 1861 return error; 1862 } 1863 1864 //------------------------------------------------------------------ 1865 // Process Queries 1866 //------------------------------------------------------------------ 1867 1868 bool 1869 ProcessGDBRemote::IsAlive () 1870 { 1871 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 1872 } 1873 1874 addr_t 1875 ProcessGDBRemote::GetImageInfoAddress() 1876 { 1877 return m_gdb_comm.GetShlibInfoAddr(); 1878 } 1879 1880 //------------------------------------------------------------------ 1881 // Process Memory 1882 //------------------------------------------------------------------ 1883 size_t 1884 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1885 { 1886 if (size > m_max_memory_size) 1887 { 1888 // Keep memory read sizes down to a sane limit. This function will be 1889 // called multiple times in order to complete the task by 1890 // lldb_private::Process so it is ok to do this. 1891 size = m_max_memory_size; 1892 } 1893 1894 char packet[64]; 1895 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%zx", (uint64_t)addr, size); 1896 assert (packet_len + 1 < sizeof(packet)); 1897 StringExtractorGDBRemote response; 1898 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true)) 1899 { 1900 if (response.IsNormalResponse()) 1901 { 1902 error.Clear(); 1903 return response.GetHexBytes(buf, size, '\xdd'); 1904 } 1905 else if (response.IsErrorResponse()) 1906 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1907 else if (response.IsUnsupportedResponse()) 1908 error.SetErrorStringWithFormat("'%s' packet unsupported", packet); 1909 else 1910 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet, response.GetStringRef().c_str()); 1911 } 1912 else 1913 { 1914 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 1915 } 1916 return 0; 1917 } 1918 1919 size_t 1920 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 1921 { 1922 if (size > m_max_memory_size) 1923 { 1924 // Keep memory read sizes down to a sane limit. This function will be 1925 // called multiple times in order to complete the task by 1926 // lldb_private::Process so it is ok to do this. 1927 size = m_max_memory_size; 1928 } 1929 1930 StreamString packet; 1931 packet.Printf("M%llx,%zx:", addr, size); 1932 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1933 StringExtractorGDBRemote response; 1934 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true)) 1935 { 1936 if (response.IsOKResponse()) 1937 { 1938 error.Clear(); 1939 return size; 1940 } 1941 else if (response.IsErrorResponse()) 1942 error.SetErrorStringWithFormat("gdb remote returned an error: %s", response.GetStringRef().c_str()); 1943 else if (response.IsUnsupportedResponse()) 1944 error.SetErrorStringWithFormat("'%s' packet unsupported", packet.GetString().c_str()); 1945 else 1946 error.SetErrorStringWithFormat("unexpected response to '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 1947 } 1948 else 1949 { 1950 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 1951 } 1952 return 0; 1953 } 1954 1955 lldb::addr_t 1956 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 1957 { 1958 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 1959 1960 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 1961 switch (supported) 1962 { 1963 case eLazyBoolCalculate: 1964 case eLazyBoolYes: 1965 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 1966 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 1967 return allocated_addr; 1968 1969 case eLazyBoolNo: 1970 // Call mmap() to create memory in the inferior.. 1971 unsigned prot = 0; 1972 if (permissions & lldb::ePermissionsReadable) 1973 prot |= eMmapProtRead; 1974 if (permissions & lldb::ePermissionsWritable) 1975 prot |= eMmapProtWrite; 1976 if (permissions & lldb::ePermissionsExecutable) 1977 prot |= eMmapProtExec; 1978 1979 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 1980 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 1981 m_addr_to_mmap_size[allocated_addr] = size; 1982 else 1983 allocated_addr = LLDB_INVALID_ADDRESS; 1984 break; 1985 } 1986 1987 if (allocated_addr == LLDB_INVALID_ADDRESS) 1988 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 1989 else 1990 error.Clear(); 1991 return allocated_addr; 1992 } 1993 1994 Error 1995 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 1996 MemoryRegionInfo ®ion_info) 1997 { 1998 1999 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 2000 return error; 2001 } 2002 2003 Error 2004 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 2005 { 2006 2007 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 2008 return error; 2009 } 2010 2011 Error 2012 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 2013 { 2014 Error error; 2015 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2016 2017 switch (supported) 2018 { 2019 case eLazyBoolCalculate: 2020 // We should never be deallocating memory without allocating memory 2021 // first so we should never get eLazyBoolCalculate 2022 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 2023 break; 2024 2025 case eLazyBoolYes: 2026 if (!m_gdb_comm.DeallocateMemory (addr)) 2027 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2028 break; 2029 2030 case eLazyBoolNo: 2031 // Call munmap() to deallocate memory in the inferior.. 2032 { 2033 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2034 if (pos != m_addr_to_mmap_size.end() && 2035 InferiorCallMunmap(this, addr, pos->second)) 2036 m_addr_to_mmap_size.erase (pos); 2037 else 2038 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2039 } 2040 break; 2041 } 2042 2043 return error; 2044 } 2045 2046 2047 //------------------------------------------------------------------ 2048 // Process STDIO 2049 //------------------------------------------------------------------ 2050 size_t 2051 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 2052 { 2053 if (m_stdio_communication.IsConnected()) 2054 { 2055 ConnectionStatus status; 2056 m_stdio_communication.Write(src, src_len, status, NULL); 2057 } 2058 return 0; 2059 } 2060 2061 Error 2062 ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 2063 { 2064 Error error; 2065 assert (bp_site != NULL); 2066 2067 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2068 user_id_t site_id = bp_site->GetID(); 2069 const addr_t addr = bp_site->GetLoadAddress(); 2070 if (log) 2071 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr); 2072 2073 if (bp_site->IsEnabled()) 2074 { 2075 if (log) 2076 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 2077 return error; 2078 } 2079 else 2080 { 2081 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2082 2083 if (bp_site->HardwarePreferred()) 2084 { 2085 // Try and set hardware breakpoint, and if that fails, fall through 2086 // and set a software breakpoint? 2087 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware)) 2088 { 2089 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 2090 { 2091 bp_site->SetEnabled(true); 2092 bp_site->SetType (BreakpointSite::eHardware); 2093 return error; 2094 } 2095 } 2096 } 2097 2098 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware)) 2099 { 2100 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 2101 { 2102 bp_site->SetEnabled(true); 2103 bp_site->SetType (BreakpointSite::eExternal); 2104 return error; 2105 } 2106 } 2107 2108 return EnableSoftwareBreakpoint (bp_site); 2109 } 2110 2111 if (log) 2112 { 2113 const char *err_string = error.AsCString(); 2114 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 2115 bp_site->GetLoadAddress(), 2116 err_string ? err_string : "NULL"); 2117 } 2118 // We shouldn't reach here on a successful breakpoint enable... 2119 if (error.Success()) 2120 error.SetErrorToGenericError(); 2121 return error; 2122 } 2123 2124 Error 2125 ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 2126 { 2127 Error error; 2128 assert (bp_site != NULL); 2129 addr_t addr = bp_site->GetLoadAddress(); 2130 user_id_t site_id = bp_site->GetID(); 2131 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2132 if (log) 2133 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr); 2134 2135 if (bp_site->IsEnabled()) 2136 { 2137 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2138 2139 BreakpointSite::Type bp_type = bp_site->GetType(); 2140 switch (bp_type) 2141 { 2142 case BreakpointSite::eSoftware: 2143 error = DisableSoftwareBreakpoint (bp_site); 2144 break; 2145 2146 case BreakpointSite::eHardware: 2147 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2148 error.SetErrorToGenericError(); 2149 break; 2150 2151 case BreakpointSite::eExternal: 2152 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2153 error.SetErrorToGenericError(); 2154 break; 2155 } 2156 if (error.Success()) 2157 bp_site->SetEnabled(false); 2158 } 2159 else 2160 { 2161 if (log) 2162 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 2163 return error; 2164 } 2165 2166 if (error.Success()) 2167 error.SetErrorToGenericError(); 2168 return error; 2169 } 2170 2171 // Pre-requisite: wp != NULL. 2172 static GDBStoppointType 2173 GetGDBStoppointType (Watchpoint *wp) 2174 { 2175 assert(wp); 2176 bool watch_read = wp->WatchpointRead(); 2177 bool watch_write = wp->WatchpointWrite(); 2178 2179 // watch_read and watch_write cannot both be false. 2180 assert(watch_read || watch_write); 2181 if (watch_read && watch_write) 2182 return eWatchpointReadWrite; 2183 else if (watch_read) 2184 return eWatchpointRead; 2185 else // Must be watch_write, then. 2186 return eWatchpointWrite; 2187 } 2188 2189 Error 2190 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp) 2191 { 2192 Error error; 2193 if (wp) 2194 { 2195 user_id_t watchID = wp->GetID(); 2196 addr_t addr = wp->GetLoadAddress(); 2197 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2198 if (log) 2199 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID); 2200 if (wp->IsEnabled()) 2201 { 2202 if (log) 2203 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 2204 return error; 2205 } 2206 2207 GDBStoppointType type = GetGDBStoppointType(wp); 2208 // Pass down an appropriate z/Z packet... 2209 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 2210 { 2211 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 2212 { 2213 wp->SetEnabled(true); 2214 return error; 2215 } 2216 else 2217 error.SetErrorString("sending gdb watchpoint packet failed"); 2218 } 2219 else 2220 error.SetErrorString("watchpoints not supported"); 2221 } 2222 else 2223 { 2224 error.SetErrorString("Watchpoint argument was NULL."); 2225 } 2226 if (error.Success()) 2227 error.SetErrorToGenericError(); 2228 return error; 2229 } 2230 2231 Error 2232 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp) 2233 { 2234 Error error; 2235 if (wp) 2236 { 2237 user_id_t watchID = wp->GetID(); 2238 2239 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2240 2241 addr_t addr = wp->GetLoadAddress(); 2242 if (log) 2243 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr); 2244 2245 if (!wp->IsEnabled()) 2246 { 2247 if (log) 2248 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 2249 return error; 2250 } 2251 2252 if (wp->IsHardware()) 2253 { 2254 GDBStoppointType type = GetGDBStoppointType(wp); 2255 // Pass down an appropriate z/Z packet... 2256 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 2257 { 2258 wp->SetEnabled(false); 2259 return error; 2260 } 2261 else 2262 error.SetErrorString("sending gdb watchpoint packet failed"); 2263 } 2264 // TODO: clear software watchpoints if we implement them 2265 } 2266 else 2267 { 2268 error.SetErrorString("Watchpoint argument was NULL."); 2269 } 2270 if (error.Success()) 2271 error.SetErrorToGenericError(); 2272 return error; 2273 } 2274 2275 void 2276 ProcessGDBRemote::Clear() 2277 { 2278 m_flags = 0; 2279 m_thread_list.Clear(); 2280 } 2281 2282 Error 2283 ProcessGDBRemote::DoSignal (int signo) 2284 { 2285 Error error; 2286 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2287 if (log) 2288 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2289 2290 if (!m_gdb_comm.SendAsyncSignal (signo)) 2291 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2292 return error; 2293 } 2294 2295 Error 2296 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) 2297 { 2298 ProcessLaunchInfo launch_info; 2299 return StartDebugserverProcess(debugserver_url, launch_info); 2300 } 2301 2302 Error 2303 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 2304 { 2305 Error error; 2306 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2307 { 2308 // If we locate debugserver, keep that located version around 2309 static FileSpec g_debugserver_file_spec; 2310 2311 ProcessLaunchInfo debugserver_launch_info; 2312 char debugserver_path[PATH_MAX]; 2313 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile(); 2314 2315 // Always check to see if we have an environment override for the path 2316 // to the debugserver to use and use it if we do. 2317 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 2318 if (env_debugserver_path) 2319 debugserver_file_spec.SetFile (env_debugserver_path, false); 2320 else 2321 debugserver_file_spec = g_debugserver_file_spec; 2322 bool debugserver_exists = debugserver_file_spec.Exists(); 2323 if (!debugserver_exists) 2324 { 2325 // The debugserver binary is in the LLDB.framework/Resources 2326 // directory. 2327 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 2328 { 2329 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 2330 debugserver_exists = debugserver_file_spec.Exists(); 2331 if (debugserver_exists) 2332 { 2333 g_debugserver_file_spec = debugserver_file_spec; 2334 } 2335 else 2336 { 2337 g_debugserver_file_spec.Clear(); 2338 debugserver_file_spec.Clear(); 2339 } 2340 } 2341 } 2342 2343 if (debugserver_exists) 2344 { 2345 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 2346 2347 m_stdio_communication.Clear(); 2348 2349 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2350 2351 Args &debugserver_args = debugserver_launch_info.GetArguments(); 2352 char arg_cstr[PATH_MAX]; 2353 2354 // Start args with "debugserver /file/path -r --" 2355 debugserver_args.AppendArgument(debugserver_path); 2356 debugserver_args.AppendArgument(debugserver_url); 2357 // use native registers, not the GDB registers 2358 debugserver_args.AppendArgument("--native-regs"); 2359 // make debugserver run in its own session so signals generated by 2360 // special terminal key sequences (^C) don't affect debugserver 2361 debugserver_args.AppendArgument("--setsid"); 2362 2363 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 2364 if (env_debugserver_log_file) 2365 { 2366 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 2367 debugserver_args.AppendArgument(arg_cstr); 2368 } 2369 2370 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 2371 if (env_debugserver_log_flags) 2372 { 2373 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 2374 debugserver_args.AppendArgument(arg_cstr); 2375 } 2376 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 2377 // debugserver_args.AppendArgument("--log-flags=0x802e0e"); 2378 2379 // We currently send down all arguments, attach pids, or attach 2380 // process names in dedicated GDB server packets, so we don't need 2381 // to pass them as arguments. This is currently because of all the 2382 // things we need to setup prior to launching: the environment, 2383 // current working dir, file actions, etc. 2384 #if 0 2385 // Now append the program arguments 2386 if (inferior_argv) 2387 { 2388 // Terminate the debugserver args so we can now append the inferior args 2389 debugserver_args.AppendArgument("--"); 2390 2391 for (int i = 0; inferior_argv[i] != NULL; ++i) 2392 debugserver_args.AppendArgument (inferior_argv[i]); 2393 } 2394 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 2395 { 2396 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 2397 debugserver_args.AppendArgument (arg_cstr); 2398 } 2399 else if (attach_name && attach_name[0]) 2400 { 2401 if (wait_for_launch) 2402 debugserver_args.AppendArgument ("--waitfor"); 2403 else 2404 debugserver_args.AppendArgument ("--attach"); 2405 debugserver_args.AppendArgument (attach_name); 2406 } 2407 #endif 2408 2409 ProcessLaunchInfo::FileAction file_action; 2410 2411 // Close STDIN, STDOUT and STDERR. We might need to redirect them 2412 // to "/dev/null" if we run into any problems. 2413 file_action.Close (STDIN_FILENO); 2414 debugserver_launch_info.AppendFileAction (file_action); 2415 file_action.Close (STDOUT_FILENO); 2416 debugserver_launch_info.AppendFileAction (file_action); 2417 file_action.Close (STDERR_FILENO); 2418 debugserver_launch_info.AppendFileAction (file_action); 2419 2420 if (log) 2421 { 2422 StreamString strm; 2423 debugserver_args.Dump (&strm); 2424 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 2425 } 2426 2427 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 2428 debugserver_launch_info.SetUserID(process_info.GetUserID()); 2429 2430 error = Host::LaunchProcess(debugserver_launch_info); 2431 2432 if (error.Success ()) 2433 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 2434 else 2435 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2436 2437 if (error.Fail() || log) 2438 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path); 2439 } 2440 else 2441 { 2442 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME); 2443 } 2444 2445 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2446 StartAsyncThread (); 2447 } 2448 return error; 2449 } 2450 2451 bool 2452 ProcessGDBRemote::MonitorDebugserverProcess 2453 ( 2454 void *callback_baton, 2455 lldb::pid_t debugserver_pid, 2456 bool exited, // True if the process did exit 2457 int signo, // Zero for no signal 2458 int exit_status // Exit value of process if signal is zero 2459 ) 2460 { 2461 // The baton is a "ProcessGDBRemote *". Now this class might be gone 2462 // and might not exist anymore, so we need to carefully try to get the 2463 // target for this process first since we have a race condition when 2464 // we are done running between getting the notice that the inferior 2465 // process has died and the debugserver that was debugging this process. 2466 // In our test suite, we are also continually running process after 2467 // process, so we must be very careful to make sure: 2468 // 1 - process object hasn't been deleted already 2469 // 2 - that a new process object hasn't been recreated in its place 2470 2471 // "debugserver_pid" argument passed in is the process ID for 2472 // debugserver that we are tracking... 2473 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2474 2475 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2476 2477 // Get a shared pointer to the target that has a matching process pointer. 2478 // This target could be gone, or the target could already have a new process 2479 // object inside of it 2480 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 2481 2482 if (log) 2483 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2484 2485 if (target_sp) 2486 { 2487 // We found a process in a target that matches, but another thread 2488 // might be in the process of launching a new process that will 2489 // soon replace it, so get a shared pointer to the process so we 2490 // can keep it alive. 2491 ProcessSP process_sp (target_sp->GetProcessSP()); 2492 // Now we have a shared pointer to the process that can't go away on us 2493 // so we now make sure it was the same as the one passed in, and also make 2494 // sure that our previous "process *" didn't get deleted and have a new 2495 // "process *" created in its place with the same pointer. To verify this 2496 // we make sure the process has our debugserver process ID. If we pass all 2497 // of these tests, then we are sure that this process is the one we were 2498 // looking for. 2499 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 2500 { 2501 // Sleep for a half a second to make sure our inferior process has 2502 // time to set its exit status before we set it incorrectly when 2503 // both the debugserver and the inferior process shut down. 2504 usleep (500000); 2505 // If our process hasn't yet exited, debugserver might have died. 2506 // If the process did exit, the we are reaping it. 2507 const StateType state = process->GetState(); 2508 2509 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2510 state != eStateInvalid && 2511 state != eStateUnloaded && 2512 state != eStateExited && 2513 state != eStateDetached) 2514 { 2515 char error_str[1024]; 2516 if (signo) 2517 { 2518 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2519 if (signal_cstr) 2520 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2521 else 2522 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2523 } 2524 else 2525 { 2526 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2527 } 2528 2529 process->SetExitStatus (-1, error_str); 2530 } 2531 // Debugserver has exited we need to let our ProcessGDBRemote 2532 // know that it no longer has a debugserver instance 2533 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2534 } 2535 } 2536 return true; 2537 } 2538 2539 void 2540 ProcessGDBRemote::KillDebugserverProcess () 2541 { 2542 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2543 { 2544 ::kill (m_debugserver_pid, SIGINT); 2545 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2546 } 2547 } 2548 2549 void 2550 ProcessGDBRemote::Initialize() 2551 { 2552 static bool g_initialized = false; 2553 2554 if (g_initialized == false) 2555 { 2556 g_initialized = true; 2557 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2558 GetPluginDescriptionStatic(), 2559 CreateInstance); 2560 2561 Log::Callbacks log_callbacks = { 2562 ProcessGDBRemoteLog::DisableLog, 2563 ProcessGDBRemoteLog::EnableLog, 2564 ProcessGDBRemoteLog::ListLogCategories 2565 }; 2566 2567 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2568 } 2569 } 2570 2571 bool 2572 ProcessGDBRemote::StartAsyncThread () 2573 { 2574 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2575 2576 if (log) 2577 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2578 2579 // Create a thread that watches our internal state and controls which 2580 // events make it to clients (into the DCProcess event queue). 2581 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2582 return IS_VALID_LLDB_HOST_THREAD(m_async_thread); 2583 } 2584 2585 void 2586 ProcessGDBRemote::StopAsyncThread () 2587 { 2588 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2589 2590 if (log) 2591 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2592 2593 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2594 2595 // This will shut down the async thread. 2596 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2597 2598 // Stop the stdio thread 2599 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2600 { 2601 Host::ThreadJoin (m_async_thread, NULL, NULL); 2602 } 2603 } 2604 2605 2606 void * 2607 ProcessGDBRemote::AsyncThread (void *arg) 2608 { 2609 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2610 2611 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2612 if (log) 2613 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID()); 2614 2615 Listener listener ("ProcessGDBRemote::AsyncThread"); 2616 EventSP event_sp; 2617 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2618 eBroadcastBitAsyncThreadShouldExit; 2619 2620 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2621 { 2622 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2623 2624 bool done = false; 2625 while (!done) 2626 { 2627 if (log) 2628 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2629 if (listener.WaitForEvent (NULL, event_sp)) 2630 { 2631 const uint32_t event_type = event_sp->GetType(); 2632 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2633 { 2634 if (log) 2635 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2636 2637 switch (event_type) 2638 { 2639 case eBroadcastBitAsyncContinue: 2640 { 2641 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2642 2643 if (continue_packet) 2644 { 2645 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2646 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2647 if (log) 2648 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2649 2650 if (::strstr (continue_cstr, "vAttach") == NULL) 2651 process->SetPrivateState(eStateRunning); 2652 StringExtractorGDBRemote response; 2653 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2654 2655 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 2656 // The thread ID list might be contained within the "response", or the stop reply packet that 2657 // caused the stop. So clear it now before we give the stop reply packet to the process 2658 // using the process->SetLastStopPacket()... 2659 process->ClearThreadIDList (); 2660 2661 switch (stop_state) 2662 { 2663 case eStateStopped: 2664 case eStateCrashed: 2665 case eStateSuspended: 2666 process->SetLastStopPacket (response); 2667 process->SetPrivateState (stop_state); 2668 break; 2669 2670 case eStateExited: 2671 process->SetLastStopPacket (response); 2672 process->ClearThreadIDList(); 2673 response.SetFilePos(1); 2674 process->SetExitStatus(response.GetHexU8(), NULL); 2675 done = true; 2676 break; 2677 2678 case eStateInvalid: 2679 process->SetExitStatus(-1, "lost connection"); 2680 break; 2681 2682 default: 2683 process->SetPrivateState (stop_state); 2684 break; 2685 } 2686 } 2687 } 2688 break; 2689 2690 case eBroadcastBitAsyncThreadShouldExit: 2691 if (log) 2692 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2693 done = true; 2694 break; 2695 2696 default: 2697 if (log) 2698 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2699 done = true; 2700 break; 2701 } 2702 } 2703 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 2704 { 2705 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 2706 { 2707 process->SetExitStatus (-1, "lost connection"); 2708 done = true; 2709 } 2710 } 2711 } 2712 else 2713 { 2714 if (log) 2715 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2716 done = true; 2717 } 2718 } 2719 } 2720 2721 if (log) 2722 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID()); 2723 2724 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2725 return NULL; 2726 } 2727 2728 const char * 2729 ProcessGDBRemote::GetDispatchQueueNameForThread 2730 ( 2731 addr_t thread_dispatch_qaddr, 2732 std::string &dispatch_queue_name 2733 ) 2734 { 2735 dispatch_queue_name.clear(); 2736 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2737 { 2738 // Cache the dispatch_queue_offsets_addr value so we don't always have 2739 // to look it up 2740 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2741 { 2742 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); 2743 const Symbol *dispatch_queue_offsets_symbol = NULL; 2744 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false)); 2745 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec)); 2746 if (module_sp) 2747 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2748 2749 if (dispatch_queue_offsets_symbol == NULL) 2750 { 2751 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false)); 2752 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec); 2753 if (module_sp) 2754 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2755 } 2756 if (dispatch_queue_offsets_symbol) 2757 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target); 2758 2759 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2760 return NULL; 2761 } 2762 2763 uint8_t memory_buffer[8]; 2764 DataExtractor data (memory_buffer, 2765 sizeof(memory_buffer), 2766 m_target.GetArchitecture().GetByteOrder(), 2767 m_target.GetArchitecture().GetAddressByteSize()); 2768 2769 // Excerpt from src/queue_private.h 2770 struct dispatch_queue_offsets_s 2771 { 2772 uint16_t dqo_version; 2773 uint16_t dqo_label; 2774 uint16_t dqo_label_size; 2775 } dispatch_queue_offsets; 2776 2777 2778 Error error; 2779 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2780 { 2781 uint32_t data_offset = 0; 2782 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2783 { 2784 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2785 { 2786 data_offset = 0; 2787 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2788 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2789 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2790 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2791 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2792 dispatch_queue_name.erase (bytes_read); 2793 } 2794 } 2795 } 2796 } 2797 if (dispatch_queue_name.empty()) 2798 return NULL; 2799 return dispatch_queue_name.c_str(); 2800 } 2801 2802 //uint32_t 2803 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2804 //{ 2805 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 2806 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 2807 // if (m_local_debugserver) 2808 // { 2809 // return Host::ListProcessesMatchingName (name, matches, pids); 2810 // } 2811 // else 2812 // { 2813 // // FIXME: Implement talking to the remote debugserver. 2814 // return 0; 2815 // } 2816 // 2817 //} 2818 // 2819 bool 2820 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 2821 lldb_private::StoppointCallbackContext *context, 2822 lldb::user_id_t break_id, 2823 lldb::user_id_t break_loc_id) 2824 { 2825 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 2826 // run so I can stop it if that's what I want to do. 2827 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2828 if (log) 2829 log->Printf("Hit New Thread Notification breakpoint."); 2830 return false; 2831 } 2832 2833 2834 bool 2835 ProcessGDBRemote::StartNoticingNewThreads() 2836 { 2837 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2838 if (m_thread_create_bp_sp) 2839 { 2840 if (log && log->GetVerbose()) 2841 log->Printf("Enabled noticing new thread breakpoint."); 2842 m_thread_create_bp_sp->SetEnabled(true); 2843 } 2844 else 2845 { 2846 PlatformSP platform_sp (m_target.GetPlatform()); 2847 if (platform_sp) 2848 { 2849 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 2850 if (m_thread_create_bp_sp) 2851 { 2852 if (log && log->GetVerbose()) 2853 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 2854 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 2855 } 2856 else 2857 { 2858 if (log) 2859 log->Printf("Failed to create new thread notification breakpoint."); 2860 } 2861 } 2862 } 2863 return m_thread_create_bp_sp.get() != NULL; 2864 } 2865 2866 bool 2867 ProcessGDBRemote::StopNoticingNewThreads() 2868 { 2869 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 2870 if (log && log->GetVerbose()) 2871 log->Printf ("Disabling new thread notification breakpoint."); 2872 2873 if (m_thread_create_bp_sp) 2874 m_thread_create_bp_sp->SetEnabled(false); 2875 2876 return true; 2877 } 2878 2879 2880