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