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