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