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 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); 849 } 850 return error; 851 } 852 853 void 854 ProcessGDBRemote::DidLaunchOrAttach () 855 { 856 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 857 if (log) 858 log->Printf ("ProcessGDBRemote::DidLaunch()"); 859 if (GetID() != LLDB_INVALID_PROCESS_ID) 860 { 861 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS; 862 863 BuildDynamicRegisterInfo (false); 864 865 // See if the GDB server supports the qHostInfo information 866 867 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture(); 868 if (gdb_remote_arch.IsValid()) 869 { 870 ArchSpec &target_arch = GetTarget().GetArchitecture(); 871 872 if (target_arch.IsValid()) 873 { 874 // If the remote host is ARM and we have apple as the vendor, then 875 // ARM executables and shared libraries can have mixed ARM architectures. 876 // You can have an armv6 executable, and if the host is armv7, then the 877 // system will load the best possible architecture for all shared libraries 878 // it has, so we really need to take the remote host architecture as our 879 // defacto architecture in this case. 880 881 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm && 882 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 883 { 884 target_arch = gdb_remote_arch; 885 } 886 else 887 { 888 // Fill in what is missing in the triple 889 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple(); 890 llvm::Triple &target_triple = target_arch.GetTriple(); 891 if (target_triple.getVendorName().size() == 0) 892 { 893 target_triple.setVendor (remote_triple.getVendor()); 894 895 if (target_triple.getOSName().size() == 0) 896 { 897 target_triple.setOS (remote_triple.getOS()); 898 899 if (target_triple.getEnvironmentName().size() == 0) 900 target_triple.setEnvironment (remote_triple.getEnvironment()); 901 } 902 } 903 } 904 } 905 else 906 { 907 // The target doesn't have a valid architecture yet, set it from 908 // the architecture we got from the remote GDB server 909 target_arch = gdb_remote_arch; 910 } 911 } 912 } 913 } 914 915 void 916 ProcessGDBRemote::DidLaunch () 917 { 918 DidLaunchOrAttach (); 919 } 920 921 Error 922 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid) 923 { 924 ProcessAttachInfo attach_info; 925 return DoAttachToProcessWithID(attach_pid, attach_info); 926 } 927 928 Error 929 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) 930 { 931 Error error; 932 // Clear out and clean up from any current state 933 Clear(); 934 if (attach_pid != LLDB_INVALID_PROCESS_ID) 935 { 936 // Make sure we aren't already connected? 937 if (!m_gdb_comm.IsConnected()) 938 { 939 char host_port[128]; 940 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 941 char connect_url[128]; 942 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 943 944 error = StartDebugserverProcess (host_port, attach_info); 945 946 if (error.Fail()) 947 { 948 const char *error_string = error.AsCString(); 949 if (error_string == NULL) 950 error_string = "unable to launch " DEBUGSERVER_BASENAME; 951 952 SetExitStatus (-1, error_string); 953 } 954 else 955 { 956 error = ConnectToDebugserver (connect_url); 957 } 958 } 959 960 if (error.Success()) 961 { 962 char packet[64]; 963 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid); 964 SetID (attach_pid); 965 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len)); 966 } 967 } 968 return error; 969 } 970 971 size_t 972 ProcessGDBRemote::AttachInputReaderCallback 973 ( 974 void *baton, 975 InputReader *reader, 976 lldb::InputReaderAction notification, 977 const char *bytes, 978 size_t bytes_len 979 ) 980 { 981 if (notification == eInputReaderGotToken) 982 { 983 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton; 984 if (gdb_process->m_waiting_for_attach) 985 gdb_process->m_waiting_for_attach = false; 986 reader->SetIsDone(true); 987 return 1; 988 } 989 return 0; 990 } 991 992 Error 993 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info) 994 { 995 Error error; 996 // Clear out and clean up from any current state 997 Clear(); 998 999 if (process_name && process_name[0]) 1000 { 1001 // Make sure we aren't already connected? 1002 if (!m_gdb_comm.IsConnected()) 1003 { 1004 char host_port[128]; 1005 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ()); 1006 char connect_url[128]; 1007 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port); 1008 1009 error = StartDebugserverProcess (host_port, attach_info); 1010 if (error.Fail()) 1011 { 1012 const char *error_string = error.AsCString(); 1013 if (error_string == NULL) 1014 error_string = "unable to launch " DEBUGSERVER_BASENAME; 1015 1016 SetExitStatus (-1, error_string); 1017 } 1018 else 1019 { 1020 error = ConnectToDebugserver (connect_url); 1021 } 1022 } 1023 1024 if (error.Success()) 1025 { 1026 StreamString packet; 1027 1028 if (wait_for_launch) 1029 { 1030 if (!m_gdb_comm.GetVAttachOrWaitSupported()) 1031 { 1032 packet.PutCString ("vAttachWait"); 1033 } 1034 else 1035 { 1036 if (attach_info.GetIgnoreExisting()) 1037 packet.PutCString("vAttachWait"); 1038 else 1039 packet.PutCString ("vAttachOrWait"); 1040 } 1041 } 1042 else 1043 packet.PutCString("vAttachName"); 1044 packet.PutChar(';'); 1045 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1046 1047 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize())); 1048 1049 } 1050 } 1051 return error; 1052 } 1053 1054 1055 void 1056 ProcessGDBRemote::DidAttach () 1057 { 1058 DidLaunchOrAttach (); 1059 } 1060 1061 Error 1062 ProcessGDBRemote::WillResume () 1063 { 1064 m_continue_c_tids.clear(); 1065 m_continue_C_tids.clear(); 1066 m_continue_s_tids.clear(); 1067 m_continue_S_tids.clear(); 1068 return Error(); 1069 } 1070 1071 Error 1072 ProcessGDBRemote::DoResume () 1073 { 1074 Error error; 1075 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1076 if (log) 1077 log->Printf ("ProcessGDBRemote::Resume()"); 1078 1079 Listener listener ("gdb-remote.resume-packet-sent"); 1080 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 1081 { 1082 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 1083 1084 StreamString continue_packet; 1085 bool continue_packet_error = false; 1086 if (m_gdb_comm.HasAnyVContSupport ()) 1087 { 1088 continue_packet.PutCString ("vCont"); 1089 1090 if (!m_continue_c_tids.empty()) 1091 { 1092 if (m_gdb_comm.GetVContSupported ('c')) 1093 { 1094 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) 1095 continue_packet.Printf(";c:%4.4llx", *t_pos); 1096 } 1097 else 1098 continue_packet_error = true; 1099 } 1100 1101 if (!continue_packet_error && !m_continue_C_tids.empty()) 1102 { 1103 if (m_gdb_comm.GetVContSupported ('C')) 1104 { 1105 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) 1106 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first); 1107 } 1108 else 1109 continue_packet_error = true; 1110 } 1111 1112 if (!continue_packet_error && !m_continue_s_tids.empty()) 1113 { 1114 if (m_gdb_comm.GetVContSupported ('s')) 1115 { 1116 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) 1117 continue_packet.Printf(";s:%4.4llx", *t_pos); 1118 } 1119 else 1120 continue_packet_error = true; 1121 } 1122 1123 if (!continue_packet_error && !m_continue_S_tids.empty()) 1124 { 1125 if (m_gdb_comm.GetVContSupported ('S')) 1126 { 1127 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) 1128 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first); 1129 } 1130 else 1131 continue_packet_error = true; 1132 } 1133 1134 if (continue_packet_error) 1135 continue_packet.GetString().clear(); 1136 } 1137 else 1138 continue_packet_error = true; 1139 1140 if (continue_packet_error) 1141 { 1142 // Either no vCont support, or we tried to use part of the vCont 1143 // packet that wasn't supported by the remote GDB server. 1144 // We need to try and make a simple packet that can do our continue 1145 const size_t num_threads = GetThreadList().GetSize(); 1146 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1147 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1148 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1149 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1150 if (num_continue_c_tids > 0) 1151 { 1152 if (num_continue_c_tids == num_threads) 1153 { 1154 // All threads are resuming... 1155 m_gdb_comm.SetCurrentThreadForRun (-1); 1156 continue_packet.PutChar ('c'); 1157 continue_packet_error = false; 1158 } 1159 else if (num_continue_c_tids == 1 && 1160 num_continue_C_tids == 0 && 1161 num_continue_s_tids == 0 && 1162 num_continue_S_tids == 0 ) 1163 { 1164 // Only one thread is continuing 1165 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 1166 continue_packet.PutChar ('c'); 1167 continue_packet_error = false; 1168 } 1169 } 1170 1171 if (continue_packet_error && num_continue_C_tids > 0) 1172 { 1173 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1174 num_continue_C_tids > 0 && 1175 num_continue_s_tids == 0 && 1176 num_continue_S_tids == 0 ) 1177 { 1178 const int continue_signo = m_continue_C_tids.front().second; 1179 // Only one thread is continuing 1180 if (num_continue_C_tids > 1) 1181 { 1182 // More that one thread with a signal, yet we don't have 1183 // vCont support and we are being asked to resume each 1184 // thread with a signal, we need to make sure they are 1185 // all the same signal, or we can't issue the continue 1186 // accurately with the current support... 1187 if (num_continue_C_tids > 1) 1188 { 1189 continue_packet_error = false; 1190 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1191 { 1192 if (m_continue_C_tids[i].second != continue_signo) 1193 continue_packet_error = true; 1194 } 1195 } 1196 if (!continue_packet_error) 1197 m_gdb_comm.SetCurrentThreadForRun (-1); 1198 } 1199 else 1200 { 1201 // Set the continue thread ID 1202 continue_packet_error = false; 1203 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1204 } 1205 if (!continue_packet_error) 1206 { 1207 // Add threads continuing with the same signo... 1208 continue_packet.Printf("C%2.2x", continue_signo); 1209 } 1210 } 1211 } 1212 1213 if (continue_packet_error && num_continue_s_tids > 0) 1214 { 1215 if (num_continue_s_tids == num_threads) 1216 { 1217 // All threads are resuming... 1218 m_gdb_comm.SetCurrentThreadForRun (-1); 1219 continue_packet.PutChar ('s'); 1220 continue_packet_error = false; 1221 } 1222 else if (num_continue_c_tids == 0 && 1223 num_continue_C_tids == 0 && 1224 num_continue_s_tids == 1 && 1225 num_continue_S_tids == 0 ) 1226 { 1227 // Only one thread is stepping 1228 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1229 continue_packet.PutChar ('s'); 1230 continue_packet_error = false; 1231 } 1232 } 1233 1234 if (!continue_packet_error && num_continue_S_tids > 0) 1235 { 1236 if (num_continue_S_tids == num_threads) 1237 { 1238 const int step_signo = m_continue_S_tids.front().second; 1239 // Are all threads trying to step with the same signal? 1240 continue_packet_error = false; 1241 if (num_continue_S_tids > 1) 1242 { 1243 for (size_t i=1; i<num_threads; ++i) 1244 { 1245 if (m_continue_S_tids[i].second != step_signo) 1246 continue_packet_error = true; 1247 } 1248 } 1249 if (!continue_packet_error) 1250 { 1251 // Add threads stepping with the same signo... 1252 m_gdb_comm.SetCurrentThreadForRun (-1); 1253 continue_packet.Printf("S%2.2x", step_signo); 1254 } 1255 } 1256 else if (num_continue_c_tids == 0 && 1257 num_continue_C_tids == 0 && 1258 num_continue_s_tids == 0 && 1259 num_continue_S_tids == 1 ) 1260 { 1261 // Only one thread is stepping with signal 1262 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1263 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1264 continue_packet_error = false; 1265 } 1266 } 1267 } 1268 1269 if (continue_packet_error) 1270 { 1271 error.SetErrorString ("can't make continue packet for this resume"); 1272 } 1273 else 1274 { 1275 EventSP event_sp; 1276 TimeValue timeout; 1277 timeout = TimeValue::Now(); 1278 timeout.OffsetWithSeconds (5); 1279 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 1280 { 1281 error.SetErrorString ("Trying to resume but the async thread is dead."); 1282 if (log) 1283 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead."); 1284 return error; 1285 } 1286 1287 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1288 1289 if (listener.WaitForEvent (&timeout, event_sp) == false) 1290 { 1291 error.SetErrorString("Resume timed out."); 1292 if (log) 1293 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out."); 1294 } 1295 else if (event_sp->BroadcasterIs (&m_async_broadcaster)) 1296 { 1297 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back."); 1298 if (log) 1299 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back."); 1300 return error; 1301 } 1302 } 1303 } 1304 1305 return error; 1306 } 1307 1308 void 1309 ProcessGDBRemote::ClearThreadIDList () 1310 { 1311 Mutex::Locker locker(m_thread_list.GetMutex()); 1312 m_thread_ids.clear(); 1313 } 1314 1315 bool 1316 ProcessGDBRemote::UpdateThreadIDList () 1317 { 1318 Mutex::Locker locker(m_thread_list.GetMutex()); 1319 bool sequence_mutex_unavailable = false; 1320 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable); 1321 if (sequence_mutex_unavailable) 1322 { 1323 return false; // We just didn't get the list 1324 } 1325 return true; 1326 } 1327 1328 bool 1329 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1330 { 1331 // locker will keep a mutex locked until it goes out of scope 1332 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1333 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1334 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID()); 1335 1336 size_t num_thread_ids = m_thread_ids.size(); 1337 // The "m_thread_ids" thread ID list should always be updated after each stop 1338 // reply packet, but in case it isn't, update it here. 1339 if (num_thread_ids == 0) 1340 { 1341 if (!UpdateThreadIDList ()) 1342 return false; 1343 num_thread_ids = m_thread_ids.size(); 1344 } 1345 1346 if (num_thread_ids > 0) 1347 { 1348 for (size_t i=0; i<num_thread_ids; ++i) 1349 { 1350 tid_t tid = m_thread_ids[i]; 1351 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false)); 1352 if (!thread_sp) 1353 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1354 new_thread_list.AddThread(thread_sp); 1355 } 1356 } 1357 1358 return true; 1359 } 1360 1361 1362 StateType 1363 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 1364 { 1365 stop_packet.SetFilePos (0); 1366 const char stop_type = stop_packet.GetChar(); 1367 switch (stop_type) 1368 { 1369 case 'T': 1370 case 'S': 1371 { 1372 if (GetStopID() == 0) 1373 { 1374 // Our first stop, make sure we have a process ID, and also make 1375 // sure we know about our registers 1376 if (GetID() == LLDB_INVALID_PROCESS_ID) 1377 { 1378 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 1379 if (pid != LLDB_INVALID_PROCESS_ID) 1380 SetID (pid); 1381 } 1382 BuildDynamicRegisterInfo (true); 1383 } 1384 // Stop with signal and thread info 1385 const uint8_t signo = stop_packet.GetHexU8(); 1386 std::string name; 1387 std::string value; 1388 std::string thread_name; 1389 std::string reason; 1390 std::string description; 1391 uint32_t exc_type = 0; 1392 std::vector<addr_t> exc_data; 1393 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1394 ThreadSP thread_sp; 1395 1396 while (stop_packet.GetNameColonValue(name, value)) 1397 { 1398 if (name.compare("metype") == 0) 1399 { 1400 // exception type in big endian hex 1401 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 1402 } 1403 else if (name.compare("medata") == 0) 1404 { 1405 // exception data in big endian hex 1406 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1407 } 1408 else if (name.compare("thread") == 0) 1409 { 1410 // thread in big endian hex 1411 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1412 // m_thread_list does have its own mutex, but we need to 1413 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...) 1414 // and the m_thread_list.AddThread(...) so it doesn't change on us 1415 Mutex::Locker locker (m_thread_list.GetMutex ()); 1416 thread_sp = m_thread_list.FindThreadByID(tid, false); 1417 if (!thread_sp) 1418 { 1419 // Create the thread if we need to 1420 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1421 m_thread_list.AddThread(thread_sp); 1422 } 1423 } 1424 else if (name.compare("threads") == 0) 1425 { 1426 Mutex::Locker locker(m_thread_list.GetMutex()); 1427 m_thread_ids.clear(); 1428 // A comma separated list of all threads in the current 1429 // process that includes the thread for this stop reply 1430 // packet 1431 size_t comma_pos; 1432 lldb::tid_t tid; 1433 while ((comma_pos = value.find(',')) != std::string::npos) 1434 { 1435 value[comma_pos] = '\0'; 1436 // thread in big endian hex 1437 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1438 if (tid != LLDB_INVALID_THREAD_ID) 1439 m_thread_ids.push_back (tid); 1440 value.erase(0, comma_pos + 1); 1441 1442 } 1443 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1444 if (tid != LLDB_INVALID_THREAD_ID) 1445 m_thread_ids.push_back (tid); 1446 } 1447 else if (name.compare("hexname") == 0) 1448 { 1449 StringExtractor name_extractor; 1450 // Swap "value" over into "name_extractor" 1451 name_extractor.GetStringRef().swap(value); 1452 // Now convert the HEX bytes into a string value 1453 name_extractor.GetHexByteString (value); 1454 thread_name.swap (value); 1455 } 1456 else if (name.compare("name") == 0) 1457 { 1458 thread_name.swap (value); 1459 } 1460 else if (name.compare("qaddr") == 0) 1461 { 1462 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1463 } 1464 else if (name.compare("reason") == 0) 1465 { 1466 reason.swap(value); 1467 } 1468 else if (name.compare("description") == 0) 1469 { 1470 StringExtractor desc_extractor; 1471 // Swap "value" over into "name_extractor" 1472 desc_extractor.GetStringRef().swap(value); 1473 // Now convert the HEX bytes into a string value 1474 desc_extractor.GetHexByteString (thread_name); 1475 } 1476 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1])) 1477 { 1478 // We have a register number that contains an expedited 1479 // register value. Lets supply this register to our thread 1480 // so it won't have to go and read it. 1481 if (thread_sp) 1482 { 1483 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16); 1484 1485 if (reg != UINT32_MAX) 1486 { 1487 StringExtractor reg_value_extractor; 1488 // Swap "value" over into "reg_value_extractor" 1489 reg_value_extractor.GetStringRef().swap(value); 1490 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor)) 1491 { 1492 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'", 1493 name.c_str(), 1494 reg, 1495 reg, 1496 reg_value_extractor.GetStringRef().c_str(), 1497 stop_packet.GetStringRef().c_str()); 1498 } 1499 } 1500 } 1501 } 1502 } 1503 1504 if (thread_sp) 1505 { 1506 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1507 1508 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1509 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1510 if (exc_type != 0) 1511 { 1512 const size_t exc_data_size = exc_data.size(); 1513 1514 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1515 exc_type, 1516 exc_data_size, 1517 exc_data_size >= 1 ? exc_data[0] : 0, 1518 exc_data_size >= 2 ? exc_data[1] : 0, 1519 exc_data_size >= 3 ? exc_data[2] : 0)); 1520 } 1521 else 1522 { 1523 bool handled = false; 1524 if (!reason.empty()) 1525 { 1526 if (reason.compare("trace") == 0) 1527 { 1528 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1529 handled = true; 1530 } 1531 else if (reason.compare("breakpoint") == 0) 1532 { 1533 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1534 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1535 if (bp_site_sp) 1536 { 1537 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1538 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1539 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1540 handled = true; 1541 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1542 { 1543 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1544 } 1545 else 1546 { 1547 StopInfoSP invalid_stop_info_sp; 1548 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1549 } 1550 } 1551 1552 } 1553 else if (reason.compare("trap") == 0) 1554 { 1555 // Let the trap just use the standard signal stop reason below... 1556 } 1557 else if (reason.compare("watchpoint") == 0) 1558 { 1559 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1560 // TODO: locate the watchpoint somehow... 1561 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1562 handled = true; 1563 } 1564 else if (reason.compare("exception") == 0) 1565 { 1566 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1567 handled = true; 1568 } 1569 } 1570 1571 if (signo) 1572 { 1573 if (signo == SIGTRAP) 1574 { 1575 // Currently we are going to assume SIGTRAP means we are either 1576 // hitting a breakpoint or hardware single stepping. 1577 handled = true; 1578 addr_t pc = gdb_thread->GetRegisterContext()->GetPC(); 1579 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1580 1581 if (bp_site_sp) 1582 { 1583 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1584 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1585 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1586 if (bp_site_sp->ValidForThisThread (gdb_thread)) 1587 { 1588 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1589 } 1590 else 1591 { 1592 StopInfoSP invalid_stop_info_sp; 1593 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1594 } 1595 } 1596 else 1597 { 1598 // If we were stepping then assume the stop was the result of the trace. If we were 1599 // not stepping then report the SIGTRAP. 1600 // FIXME: We are still missing the case where we single step over a trap instruction. 1601 if (gdb_thread->GetTemporaryResumeState() == eStateStepping) 1602 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1603 else 1604 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo)); 1605 } 1606 } 1607 if (!handled) 1608 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1609 } 1610 else 1611 { 1612 StopInfoSP invalid_stop_info_sp; 1613 gdb_thread->SetStopInfo (invalid_stop_info_sp); 1614 } 1615 1616 if (!description.empty()) 1617 { 1618 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ()); 1619 if (stop_info_sp) 1620 { 1621 stop_info_sp->SetDescription (description.c_str()); 1622 } 1623 else 1624 { 1625 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1626 } 1627 } 1628 } 1629 } 1630 return eStateStopped; 1631 } 1632 break; 1633 1634 case 'W': 1635 // process exited 1636 return eStateExited; 1637 1638 default: 1639 break; 1640 } 1641 return eStateInvalid; 1642 } 1643 1644 void 1645 ProcessGDBRemote::RefreshStateAfterStop () 1646 { 1647 Mutex::Locker locker(m_thread_list.GetMutex()); 1648 m_thread_ids.clear(); 1649 // Set the thread stop info. It might have a "threads" key whose value is 1650 // a list of all thread IDs in the current process, so m_thread_ids might 1651 // get set. 1652 SetThreadStopInfo (m_last_stop_packet); 1653 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 1654 if (m_thread_ids.empty()) 1655 { 1656 // No, we need to fetch the thread list manually 1657 UpdateThreadIDList(); 1658 } 1659 1660 // Let all threads recover from stopping and do any clean up based 1661 // on the previous thread state (if any). 1662 m_thread_list.RefreshStateAfterStop(); 1663 1664 } 1665 1666 Error 1667 ProcessGDBRemote::DoHalt (bool &caused_stop) 1668 { 1669 Error error; 1670 1671 bool timed_out = false; 1672 Mutex::Locker locker; 1673 1674 if (m_public_state.GetValue() == eStateAttaching) 1675 { 1676 // We are being asked to halt during an attach. We need to just close 1677 // our file handle and debugserver will go away, and we can be done... 1678 m_gdb_comm.Disconnect(); 1679 } 1680 else 1681 { 1682 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 1683 { 1684 if (timed_out) 1685 error.SetErrorString("timed out sending interrupt packet"); 1686 else 1687 error.SetErrorString("unknown error sending interrupt packet"); 1688 } 1689 1690 caused_stop = m_gdb_comm.GetInterruptWasSent (); 1691 } 1692 return error; 1693 } 1694 1695 Error 1696 ProcessGDBRemote::InterruptIfRunning 1697 ( 1698 bool discard_thread_plans, 1699 bool catch_stop_event, 1700 EventSP &stop_event_sp 1701 ) 1702 { 1703 Error error; 1704 1705 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1706 1707 bool paused_private_state_thread = false; 1708 const bool is_running = m_gdb_comm.IsRunning(); 1709 if (log) 1710 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i", 1711 discard_thread_plans, 1712 catch_stop_event, 1713 is_running); 1714 1715 if (discard_thread_plans) 1716 { 1717 if (log) 1718 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans"); 1719 m_thread_list.DiscardThreadPlans(); 1720 } 1721 if (is_running) 1722 { 1723 if (catch_stop_event) 1724 { 1725 if (log) 1726 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread"); 1727 PausePrivateStateThread(); 1728 paused_private_state_thread = true; 1729 } 1730 1731 bool timed_out = false; 1732 Mutex::Locker locker; 1733 1734 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out)) 1735 { 1736 if (timed_out) 1737 error.SetErrorString("timed out sending interrupt packet"); 1738 else 1739 error.SetErrorString("unknown error sending interrupt packet"); 1740 if (paused_private_state_thread) 1741 ResumePrivateStateThread(); 1742 return error; 1743 } 1744 1745 if (catch_stop_event) 1746 { 1747 // LISTEN HERE 1748 TimeValue timeout_time; 1749 timeout_time = TimeValue::Now(); 1750 timeout_time.OffsetWithSeconds(5); 1751 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp); 1752 1753 timed_out = state == eStateInvalid; 1754 if (log) 1755 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out); 1756 1757 if (timed_out) 1758 error.SetErrorString("unable to verify target stopped"); 1759 } 1760 1761 if (paused_private_state_thread) 1762 { 1763 if (log) 1764 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread"); 1765 ResumePrivateStateThread(); 1766 } 1767 } 1768 return error; 1769 } 1770 1771 Error 1772 ProcessGDBRemote::WillDetach () 1773 { 1774 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1775 if (log) 1776 log->Printf ("ProcessGDBRemote::WillDetach()"); 1777 1778 bool discard_thread_plans = true; 1779 bool catch_stop_event = true; 1780 EventSP event_sp; 1781 1782 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is 1783 // needed. This shouldn't be a feature of a particular plugin. 1784 1785 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp); 1786 } 1787 1788 Error 1789 ProcessGDBRemote::DoDetach() 1790 { 1791 Error error; 1792 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1793 if (log) 1794 log->Printf ("ProcessGDBRemote::DoDetach()"); 1795 1796 DisableAllBreakpointSites (); 1797 1798 m_thread_list.DiscardThreadPlans(); 1799 1800 bool success = m_gdb_comm.Detach (); 1801 if (log) 1802 { 1803 if (success) 1804 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1805 else 1806 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed"); 1807 } 1808 // Sleep for one second to let the process get all detached... 1809 StopAsyncThread (); 1810 1811 SetPrivateState (eStateDetached); 1812 ResumePrivateStateThread(); 1813 1814 //KillDebugserverProcess (); 1815 return error; 1816 } 1817 1818 1819 Error 1820 ProcessGDBRemote::DoDestroy () 1821 { 1822 Error error; 1823 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1824 if (log) 1825 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1826 1827 // There is a bug in older iOS debugservers where they don't shut down the process 1828 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 1829 // this can cause problems with restarting. So we check to see if any of our threads are stopped 1830 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 1831 // destroy it again. 1832 // 1833 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 1834 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 1835 // the debugservers with this bug are equal. There really should be a better way to test this! 1836 // 1837 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 1838 // get called here to destroy again and we're still at a breakpoint or exception, then we should 1839 // just do the straight-forward kill. 1840 // 1841 // And of course, if we weren't able to stop the process by the time we get here, it isn't 1842 // necessary (or helpful) to do any of this. 1843 1844 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 1845 { 1846 PlatformSP platform_sp = GetTarget().GetPlatform(); 1847 1848 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 1849 if (platform_sp 1850 && platform_sp->GetName() 1851 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0) 1852 { 1853 if (m_destroy_tried_resuming) 1854 { 1855 if (log) 1856 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again."); 1857 } 1858 else 1859 { 1860 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 1861 // but we really need it to happen here and it doesn't matter if we do it twice. 1862 m_thread_list.DiscardThreadPlans(); 1863 DisableAllBreakpointSites(); 1864 1865 bool stop_looks_like_crash = false; 1866 ThreadList &threads = GetThreadList(); 1867 1868 { 1869 Mutex::Locker locker(threads.GetMutex()); 1870 1871 size_t num_threads = threads.GetSize(); 1872 for (size_t i = 0; i < num_threads; i++) 1873 { 1874 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1875 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1876 StopReason reason = eStopReasonInvalid; 1877 if (stop_info_sp) 1878 reason = stop_info_sp->GetStopReason(); 1879 if (reason == eStopReasonBreakpoint 1880 || reason == eStopReasonException) 1881 { 1882 if (log) 1883 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.", 1884 thread_sp->GetID(), 1885 stop_info_sp->GetDescription()); 1886 stop_looks_like_crash = true; 1887 break; 1888 } 1889 } 1890 } 1891 1892 if (stop_looks_like_crash) 1893 { 1894 if (log) 1895 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 1896 m_destroy_tried_resuming = true; 1897 1898 // If we are going to run again before killing, it would be good to suspend all the threads 1899 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 1900 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 1901 // have to run the risk of letting those threads proceed a bit. 1902 1903 { 1904 Mutex::Locker locker(threads.GetMutex()); 1905 1906 size_t num_threads = threads.GetSize(); 1907 for (size_t i = 0; i < num_threads; i++) 1908 { 1909 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1910 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason(); 1911 StopReason reason = eStopReasonInvalid; 1912 if (stop_info_sp) 1913 reason = stop_info_sp->GetStopReason(); 1914 if (reason != eStopReasonBreakpoint 1915 && reason != eStopReasonException) 1916 { 1917 if (log) 1918 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.", 1919 thread_sp->GetID()); 1920 thread_sp->SetResumeState(eStateSuspended); 1921 } 1922 } 1923 } 1924 Resume (); 1925 return Destroy(); 1926 } 1927 } 1928 } 1929 } 1930 1931 // Interrupt if our inferior is running... 1932 int exit_status = SIGABRT; 1933 std::string exit_string; 1934 1935 if (m_gdb_comm.IsConnected()) 1936 { 1937 if (m_public_state.GetValue() != eStateAttaching) 1938 { 1939 1940 StringExtractorGDBRemote response; 1941 bool send_async = true; 1942 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3); 1943 1944 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async)) 1945 { 1946 char packet_cmd = response.GetChar(0); 1947 1948 if (packet_cmd == 'W' || packet_cmd == 'X') 1949 { 1950 SetLastStopPacket (response); 1951 ClearThreadIDList (); 1952 exit_status = response.GetHexU8(); 1953 } 1954 else 1955 { 1956 if (log) 1957 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 1958 exit_string.assign("got unexpected response to k packet: "); 1959 exit_string.append(response.GetStringRef()); 1960 } 1961 } 1962 else 1963 { 1964 if (log) 1965 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1966 exit_string.assign("failed to send the k packet"); 1967 } 1968 1969 m_gdb_comm.SetPacketTimeout(old_packet_timeout); 1970 } 1971 else 1972 { 1973 if (log) 1974 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 1975 exit_string.assign ("killed or interrupted while attaching."); 1976 } 1977 } 1978 else 1979 { 1980 // If we missed setting the exit status on the way out, do it here. 1981 // NB set exit status can be called multiple times, the first one sets the status. 1982 exit_string.assign("destroying when not connected to debugserver"); 1983 } 1984 1985 SetExitStatus(exit_status, exit_string.c_str()); 1986 1987 StopAsyncThread (); 1988 KillDebugserverProcess (); 1989 return error; 1990 } 1991 1992 //------------------------------------------------------------------ 1993 // Process Queries 1994 //------------------------------------------------------------------ 1995 1996 bool 1997 ProcessGDBRemote::IsAlive () 1998 { 1999 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 2000 } 2001 2002 // For kernel debugging, we return the load address of the kernel binary as the 2003 // ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader() 2004 // name so the correct DynamicLoader plugin is chosen. 2005 addr_t 2006 ProcessGDBRemote::GetImageInfoAddress() 2007 { 2008 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS) 2009 return m_kernel_load_addr; 2010 else 2011 return m_gdb_comm.GetShlibInfoAddr(); 2012 } 2013 2014 //------------------------------------------------------------------ 2015 // Process Memory 2016 //------------------------------------------------------------------ 2017 size_t 2018 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2019 { 2020 if (size > m_max_memory_size) 2021 { 2022 // Keep memory read sizes down to a sane limit. This function will be 2023 // called multiple times in order to complete the task by 2024 // lldb_private::Process so it is ok to do this. 2025 size = m_max_memory_size; 2026 } 2027 2028 char packet[64]; 2029 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size); 2030 assert (packet_len + 1 < sizeof(packet)); 2031 StringExtractorGDBRemote response; 2032 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true)) 2033 { 2034 if (response.IsNormalResponse()) 2035 { 2036 error.Clear(); 2037 return response.GetHexBytes(buf, size, '\xdd'); 2038 } 2039 else if (response.IsErrorResponse()) 2040 error.SetErrorString("memory read failed"); 2041 else if (response.IsUnsupportedResponse()) 2042 error.SetErrorStringWithFormat("GDB server does not support reading memory"); 2043 else 2044 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str()); 2045 } 2046 else 2047 { 2048 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet); 2049 } 2050 return 0; 2051 } 2052 2053 size_t 2054 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2055 { 2056 if (size > m_max_memory_size) 2057 { 2058 // Keep memory read sizes down to a sane limit. This function will be 2059 // called multiple times in order to complete the task by 2060 // lldb_private::Process so it is ok to do this. 2061 size = m_max_memory_size; 2062 } 2063 2064 StreamString packet; 2065 packet.Printf("M%llx,%llx:", addr, (uint64_t)size); 2066 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 2067 StringExtractorGDBRemote response; 2068 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true)) 2069 { 2070 if (response.IsOKResponse()) 2071 { 2072 error.Clear(); 2073 return size; 2074 } 2075 else if (response.IsErrorResponse()) 2076 error.SetErrorString("memory write failed"); 2077 else if (response.IsUnsupportedResponse()) 2078 error.SetErrorStringWithFormat("GDB server does not support writing memory"); 2079 else 2080 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 2081 } 2082 else 2083 { 2084 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str()); 2085 } 2086 return 0; 2087 } 2088 2089 lldb::addr_t 2090 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 2091 { 2092 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2093 2094 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2095 switch (supported) 2096 { 2097 case eLazyBoolCalculate: 2098 case eLazyBoolYes: 2099 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 2100 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 2101 return allocated_addr; 2102 2103 case eLazyBoolNo: 2104 // Call mmap() to create memory in the inferior.. 2105 unsigned prot = 0; 2106 if (permissions & lldb::ePermissionsReadable) 2107 prot |= eMmapProtRead; 2108 if (permissions & lldb::ePermissionsWritable) 2109 prot |= eMmapProtWrite; 2110 if (permissions & lldb::ePermissionsExecutable) 2111 prot |= eMmapProtExec; 2112 2113 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2114 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2115 m_addr_to_mmap_size[allocated_addr] = size; 2116 else 2117 allocated_addr = LLDB_INVALID_ADDRESS; 2118 break; 2119 } 2120 2121 if (allocated_addr == LLDB_INVALID_ADDRESS) 2122 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions)); 2123 else 2124 error.Clear(); 2125 return allocated_addr; 2126 } 2127 2128 Error 2129 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 2130 MemoryRegionInfo ®ion_info) 2131 { 2132 2133 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 2134 return error; 2135 } 2136 2137 Error 2138 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 2139 { 2140 2141 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 2142 return error; 2143 } 2144 2145 Error 2146 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after) 2147 { 2148 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after)); 2149 return error; 2150 } 2151 2152 Error 2153 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 2154 { 2155 Error error; 2156 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2157 2158 switch (supported) 2159 { 2160 case eLazyBoolCalculate: 2161 // We should never be deallocating memory without allocating memory 2162 // first so we should never get eLazyBoolCalculate 2163 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 2164 break; 2165 2166 case eLazyBoolYes: 2167 if (!m_gdb_comm.DeallocateMemory (addr)) 2168 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2169 break; 2170 2171 case eLazyBoolNo: 2172 // Call munmap() to deallocate memory in the inferior.. 2173 { 2174 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2175 if (pos != m_addr_to_mmap_size.end() && 2176 InferiorCallMunmap(this, addr, pos->second)) 2177 m_addr_to_mmap_size.erase (pos); 2178 else 2179 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr); 2180 } 2181 break; 2182 } 2183 2184 return error; 2185 } 2186 2187 2188 //------------------------------------------------------------------ 2189 // Process STDIO 2190 //------------------------------------------------------------------ 2191 size_t 2192 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 2193 { 2194 if (m_stdio_communication.IsConnected()) 2195 { 2196 ConnectionStatus status; 2197 m_stdio_communication.Write(src, src_len, status, NULL); 2198 } 2199 return 0; 2200 } 2201 2202 Error 2203 ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site) 2204 { 2205 Error error; 2206 assert (bp_site != NULL); 2207 2208 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2209 user_id_t site_id = bp_site->GetID(); 2210 const addr_t addr = bp_site->GetLoadAddress(); 2211 if (log) 2212 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr); 2213 2214 if (bp_site->IsEnabled()) 2215 { 2216 if (log) 2217 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 2218 return error; 2219 } 2220 else 2221 { 2222 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2223 2224 if (bp_site->HardwarePreferred()) 2225 { 2226 // Try and set hardware breakpoint, and if that fails, fall through 2227 // and set a software breakpoint? 2228 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware)) 2229 { 2230 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 2231 { 2232 bp_site->SetEnabled(true); 2233 bp_site->SetType (BreakpointSite::eHardware); 2234 return error; 2235 } 2236 } 2237 } 2238 2239 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware)) 2240 { 2241 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 2242 { 2243 bp_site->SetEnabled(true); 2244 bp_site->SetType (BreakpointSite::eExternal); 2245 return error; 2246 } 2247 } 2248 2249 return EnableSoftwareBreakpoint (bp_site); 2250 } 2251 2252 if (log) 2253 { 2254 const char *err_string = error.AsCString(); 2255 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s", 2256 bp_site->GetLoadAddress(), 2257 err_string ? err_string : "NULL"); 2258 } 2259 // We shouldn't reach here on a successful breakpoint enable... 2260 if (error.Success()) 2261 error.SetErrorToGenericError(); 2262 return error; 2263 } 2264 2265 Error 2266 ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site) 2267 { 2268 Error error; 2269 assert (bp_site != NULL); 2270 addr_t addr = bp_site->GetLoadAddress(); 2271 user_id_t site_id = bp_site->GetID(); 2272 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2273 if (log) 2274 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr); 2275 2276 if (bp_site->IsEnabled()) 2277 { 2278 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2279 2280 BreakpointSite::Type bp_type = bp_site->GetType(); 2281 switch (bp_type) 2282 { 2283 case BreakpointSite::eSoftware: 2284 error = DisableSoftwareBreakpoint (bp_site); 2285 break; 2286 2287 case BreakpointSite::eHardware: 2288 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2289 error.SetErrorToGenericError(); 2290 break; 2291 2292 case BreakpointSite::eExternal: 2293 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2294 error.SetErrorToGenericError(); 2295 break; 2296 } 2297 if (error.Success()) 2298 bp_site->SetEnabled(false); 2299 } 2300 else 2301 { 2302 if (log) 2303 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 2304 return error; 2305 } 2306 2307 if (error.Success()) 2308 error.SetErrorToGenericError(); 2309 return error; 2310 } 2311 2312 // Pre-requisite: wp != NULL. 2313 static GDBStoppointType 2314 GetGDBStoppointType (Watchpoint *wp) 2315 { 2316 assert(wp); 2317 bool watch_read = wp->WatchpointRead(); 2318 bool watch_write = wp->WatchpointWrite(); 2319 2320 // watch_read and watch_write cannot both be false. 2321 assert(watch_read || watch_write); 2322 if (watch_read && watch_write) 2323 return eWatchpointReadWrite; 2324 else if (watch_read) 2325 return eWatchpointRead; 2326 else // Must be watch_write, then. 2327 return eWatchpointWrite; 2328 } 2329 2330 Error 2331 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp) 2332 { 2333 Error error; 2334 if (wp) 2335 { 2336 user_id_t watchID = wp->GetID(); 2337 addr_t addr = wp->GetLoadAddress(); 2338 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2339 if (log) 2340 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID); 2341 if (wp->IsEnabled()) 2342 { 2343 if (log) 2344 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr); 2345 return error; 2346 } 2347 2348 GDBStoppointType type = GetGDBStoppointType(wp); 2349 // Pass down an appropriate z/Z packet... 2350 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 2351 { 2352 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 2353 { 2354 wp->SetEnabled(true); 2355 return error; 2356 } 2357 else 2358 error.SetErrorString("sending gdb watchpoint packet failed"); 2359 } 2360 else 2361 error.SetErrorString("watchpoints not supported"); 2362 } 2363 else 2364 { 2365 error.SetErrorString("Watchpoint argument was NULL."); 2366 } 2367 if (error.Success()) 2368 error.SetErrorToGenericError(); 2369 return error; 2370 } 2371 2372 Error 2373 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp) 2374 { 2375 Error error; 2376 if (wp) 2377 { 2378 user_id_t watchID = wp->GetID(); 2379 2380 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2381 2382 addr_t addr = wp->GetLoadAddress(); 2383 if (log) 2384 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr); 2385 2386 if (!wp->IsEnabled()) 2387 { 2388 if (log) 2389 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 2390 // See also 'class WatchpointSentry' within StopInfo.cpp. 2391 // This disabling attempt might come from the user-supplied actions, we'll route it in order for 2392 // the watchpoint object to intelligently process this action. 2393 wp->SetEnabled(false); 2394 return error; 2395 } 2396 2397 if (wp->IsHardware()) 2398 { 2399 GDBStoppointType type = GetGDBStoppointType(wp); 2400 // Pass down an appropriate z/Z packet... 2401 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 2402 { 2403 wp->SetEnabled(false); 2404 return error; 2405 } 2406 else 2407 error.SetErrorString("sending gdb watchpoint packet failed"); 2408 } 2409 // TODO: clear software watchpoints if we implement them 2410 } 2411 else 2412 { 2413 error.SetErrorString("Watchpoint argument was NULL."); 2414 } 2415 if (error.Success()) 2416 error.SetErrorToGenericError(); 2417 return error; 2418 } 2419 2420 void 2421 ProcessGDBRemote::Clear() 2422 { 2423 m_flags = 0; 2424 m_thread_list.Clear(); 2425 } 2426 2427 Error 2428 ProcessGDBRemote::DoSignal (int signo) 2429 { 2430 Error error; 2431 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2432 if (log) 2433 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2434 2435 if (!m_gdb_comm.SendAsyncSignal (signo)) 2436 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2437 return error; 2438 } 2439 2440 Error 2441 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) 2442 { 2443 ProcessLaunchInfo launch_info; 2444 return StartDebugserverProcess(debugserver_url, launch_info); 2445 } 2446 2447 Error 2448 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 2449 { 2450 Error error; 2451 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2452 { 2453 // If we locate debugserver, keep that located version around 2454 static FileSpec g_debugserver_file_spec; 2455 2456 ProcessLaunchInfo debugserver_launch_info; 2457 char debugserver_path[PATH_MAX]; 2458 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile(); 2459 2460 // Always check to see if we have an environment override for the path 2461 // to the debugserver to use and use it if we do. 2462 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 2463 if (env_debugserver_path) 2464 debugserver_file_spec.SetFile (env_debugserver_path, false); 2465 else 2466 debugserver_file_spec = g_debugserver_file_spec; 2467 bool debugserver_exists = debugserver_file_spec.Exists(); 2468 if (!debugserver_exists) 2469 { 2470 // The debugserver binary is in the LLDB.framework/Resources 2471 // directory. 2472 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 2473 { 2474 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 2475 debugserver_exists = debugserver_file_spec.Exists(); 2476 if (debugserver_exists) 2477 { 2478 g_debugserver_file_spec = debugserver_file_spec; 2479 } 2480 else 2481 { 2482 g_debugserver_file_spec.Clear(); 2483 debugserver_file_spec.Clear(); 2484 } 2485 } 2486 } 2487 2488 if (debugserver_exists) 2489 { 2490 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 2491 2492 m_stdio_communication.Clear(); 2493 2494 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2495 2496 Args &debugserver_args = debugserver_launch_info.GetArguments(); 2497 char arg_cstr[PATH_MAX]; 2498 2499 // Start args with "debugserver /file/path -r --" 2500 debugserver_args.AppendArgument(debugserver_path); 2501 debugserver_args.AppendArgument(debugserver_url); 2502 // use native registers, not the GDB registers 2503 debugserver_args.AppendArgument("--native-regs"); 2504 // make debugserver run in its own session so signals generated by 2505 // special terminal key sequences (^C) don't affect debugserver 2506 debugserver_args.AppendArgument("--setsid"); 2507 2508 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 2509 if (env_debugserver_log_file) 2510 { 2511 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 2512 debugserver_args.AppendArgument(arg_cstr); 2513 } 2514 2515 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 2516 if (env_debugserver_log_flags) 2517 { 2518 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 2519 debugserver_args.AppendArgument(arg_cstr); 2520 } 2521 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 2522 // debugserver_args.AppendArgument("--log-flags=0x802e0e"); 2523 2524 // We currently send down all arguments, attach pids, or attach 2525 // process names in dedicated GDB server packets, so we don't need 2526 // to pass them as arguments. This is currently because of all the 2527 // things we need to setup prior to launching: the environment, 2528 // current working dir, file actions, etc. 2529 #if 0 2530 // Now append the program arguments 2531 if (inferior_argv) 2532 { 2533 // Terminate the debugserver args so we can now append the inferior args 2534 debugserver_args.AppendArgument("--"); 2535 2536 for (int i = 0; inferior_argv[i] != NULL; ++i) 2537 debugserver_args.AppendArgument (inferior_argv[i]); 2538 } 2539 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 2540 { 2541 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 2542 debugserver_args.AppendArgument (arg_cstr); 2543 } 2544 else if (attach_name && attach_name[0]) 2545 { 2546 if (wait_for_launch) 2547 debugserver_args.AppendArgument ("--waitfor"); 2548 else 2549 debugserver_args.AppendArgument ("--attach"); 2550 debugserver_args.AppendArgument (attach_name); 2551 } 2552 #endif 2553 2554 ProcessLaunchInfo::FileAction file_action; 2555 2556 // Close STDIN, STDOUT and STDERR. We might need to redirect them 2557 // to "/dev/null" if we run into any problems. 2558 file_action.Close (STDIN_FILENO); 2559 debugserver_launch_info.AppendFileAction (file_action); 2560 file_action.Close (STDOUT_FILENO); 2561 debugserver_launch_info.AppendFileAction (file_action); 2562 file_action.Close (STDERR_FILENO); 2563 debugserver_launch_info.AppendFileAction (file_action); 2564 2565 if (log) 2566 { 2567 StreamString strm; 2568 debugserver_args.Dump (&strm); 2569 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 2570 } 2571 2572 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 2573 debugserver_launch_info.SetUserID(process_info.GetUserID()); 2574 2575 error = Host::LaunchProcess(debugserver_launch_info); 2576 2577 if (error.Success ()) 2578 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 2579 else 2580 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2581 2582 if (error.Fail() || log) 2583 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path); 2584 } 2585 else 2586 { 2587 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME); 2588 } 2589 2590 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2591 StartAsyncThread (); 2592 } 2593 return error; 2594 } 2595 2596 bool 2597 ProcessGDBRemote::MonitorDebugserverProcess 2598 ( 2599 void *callback_baton, 2600 lldb::pid_t debugserver_pid, 2601 bool exited, // True if the process did exit 2602 int signo, // Zero for no signal 2603 int exit_status // Exit value of process if signal is zero 2604 ) 2605 { 2606 // The baton is a "ProcessGDBRemote *". Now this class might be gone 2607 // and might not exist anymore, so we need to carefully try to get the 2608 // target for this process first since we have a race condition when 2609 // we are done running between getting the notice that the inferior 2610 // process has died and the debugserver that was debugging this process. 2611 // In our test suite, we are also continually running process after 2612 // process, so we must be very careful to make sure: 2613 // 1 - process object hasn't been deleted already 2614 // 2 - that a new process object hasn't been recreated in its place 2615 2616 // "debugserver_pid" argument passed in is the process ID for 2617 // debugserver that we are tracking... 2618 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2619 2620 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2621 2622 // Get a shared pointer to the target that has a matching process pointer. 2623 // This target could be gone, or the target could already have a new process 2624 // object inside of it 2625 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 2626 2627 if (log) 2628 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2629 2630 if (target_sp) 2631 { 2632 // We found a process in a target that matches, but another thread 2633 // might be in the process of launching a new process that will 2634 // soon replace it, so get a shared pointer to the process so we 2635 // can keep it alive. 2636 ProcessSP process_sp (target_sp->GetProcessSP()); 2637 // Now we have a shared pointer to the process that can't go away on us 2638 // so we now make sure it was the same as the one passed in, and also make 2639 // sure that our previous "process *" didn't get deleted and have a new 2640 // "process *" created in its place with the same pointer. To verify this 2641 // we make sure the process has our debugserver process ID. If we pass all 2642 // of these tests, then we are sure that this process is the one we were 2643 // looking for. 2644 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 2645 { 2646 // Sleep for a half a second to make sure our inferior process has 2647 // time to set its exit status before we set it incorrectly when 2648 // both the debugserver and the inferior process shut down. 2649 usleep (500000); 2650 // If our process hasn't yet exited, debugserver might have died. 2651 // If the process did exit, the we are reaping it. 2652 const StateType state = process->GetState(); 2653 2654 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2655 state != eStateInvalid && 2656 state != eStateUnloaded && 2657 state != eStateExited && 2658 state != eStateDetached) 2659 { 2660 char error_str[1024]; 2661 if (signo) 2662 { 2663 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2664 if (signal_cstr) 2665 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2666 else 2667 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2668 } 2669 else 2670 { 2671 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2672 } 2673 2674 process->SetExitStatus (-1, error_str); 2675 } 2676 // Debugserver has exited we need to let our ProcessGDBRemote 2677 // know that it no longer has a debugserver instance 2678 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2679 } 2680 } 2681 return true; 2682 } 2683 2684 void 2685 ProcessGDBRemote::KillDebugserverProcess () 2686 { 2687 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2688 { 2689 ::kill (m_debugserver_pid, SIGINT); 2690 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2691 } 2692 } 2693 2694 void 2695 ProcessGDBRemote::Initialize() 2696 { 2697 static bool g_initialized = false; 2698 2699 if (g_initialized == false) 2700 { 2701 g_initialized = true; 2702 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2703 GetPluginDescriptionStatic(), 2704 CreateInstance); 2705 2706 Log::Callbacks log_callbacks = { 2707 ProcessGDBRemoteLog::DisableLog, 2708 ProcessGDBRemoteLog::EnableLog, 2709 ProcessGDBRemoteLog::ListLogCategories 2710 }; 2711 2712 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2713 } 2714 } 2715 2716 bool 2717 ProcessGDBRemote::StartAsyncThread () 2718 { 2719 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2720 2721 if (log) 2722 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2723 2724 Mutex::Locker start_locker(m_async_thread_state_mutex); 2725 if (m_async_thread_state == eAsyncThreadNotStarted) 2726 { 2727 // Create a thread that watches our internal state and controls which 2728 // events make it to clients (into the DCProcess event queue). 2729 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2730 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2731 { 2732 m_async_thread_state = eAsyncThreadRunning; 2733 return true; 2734 } 2735 else 2736 return false; 2737 } 2738 else 2739 { 2740 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and 2741 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it. 2742 if (log) 2743 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2744 if (m_async_thread_state == eAsyncThreadRunning) 2745 return true; 2746 else 2747 return false; 2748 } 2749 } 2750 2751 void 2752 ProcessGDBRemote::StopAsyncThread () 2753 { 2754 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2755 2756 if (log) 2757 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2758 2759 Mutex::Locker start_locker(m_async_thread_state_mutex); 2760 if (m_async_thread_state == eAsyncThreadRunning) 2761 { 2762 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2763 2764 // This will shut down the async thread. 2765 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2766 2767 // Stop the stdio thread 2768 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2769 { 2770 Host::ThreadJoin (m_async_thread, NULL, NULL); 2771 } 2772 m_async_thread_state = eAsyncThreadDone; 2773 } 2774 else 2775 { 2776 if (log) 2777 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2778 } 2779 } 2780 2781 2782 void * 2783 ProcessGDBRemote::AsyncThread (void *arg) 2784 { 2785 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2786 2787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2788 if (log) 2789 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID()); 2790 2791 Listener listener ("ProcessGDBRemote::AsyncThread"); 2792 EventSP event_sp; 2793 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2794 eBroadcastBitAsyncThreadShouldExit; 2795 2796 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2797 { 2798 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2799 2800 bool done = false; 2801 while (!done) 2802 { 2803 if (log) 2804 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2805 if (listener.WaitForEvent (NULL, event_sp)) 2806 { 2807 const uint32_t event_type = event_sp->GetType(); 2808 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2809 { 2810 if (log) 2811 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2812 2813 switch (event_type) 2814 { 2815 case eBroadcastBitAsyncContinue: 2816 { 2817 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2818 2819 if (continue_packet) 2820 { 2821 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2822 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2823 if (log) 2824 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2825 2826 if (::strstr (continue_cstr, "vAttach") == NULL) 2827 process->SetPrivateState(eStateRunning); 2828 StringExtractorGDBRemote response; 2829 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2830 2831 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 2832 // The thread ID list might be contained within the "response", or the stop reply packet that 2833 // caused the stop. So clear it now before we give the stop reply packet to the process 2834 // using the process->SetLastStopPacket()... 2835 process->ClearThreadIDList (); 2836 2837 switch (stop_state) 2838 { 2839 case eStateStopped: 2840 case eStateCrashed: 2841 case eStateSuspended: 2842 process->SetLastStopPacket (response); 2843 process->SetPrivateState (stop_state); 2844 break; 2845 2846 case eStateExited: 2847 process->SetLastStopPacket (response); 2848 process->ClearThreadIDList(); 2849 response.SetFilePos(1); 2850 process->SetExitStatus(response.GetHexU8(), NULL); 2851 done = true; 2852 break; 2853 2854 case eStateInvalid: 2855 process->SetExitStatus(-1, "lost connection"); 2856 break; 2857 2858 default: 2859 process->SetPrivateState (stop_state); 2860 break; 2861 } 2862 } 2863 } 2864 break; 2865 2866 case eBroadcastBitAsyncThreadShouldExit: 2867 if (log) 2868 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2869 done = true; 2870 break; 2871 2872 default: 2873 if (log) 2874 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2875 done = true; 2876 break; 2877 } 2878 } 2879 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 2880 { 2881 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 2882 { 2883 process->SetExitStatus (-1, "lost connection"); 2884 done = true; 2885 } 2886 } 2887 } 2888 else 2889 { 2890 if (log) 2891 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 2892 done = true; 2893 } 2894 } 2895 } 2896 2897 if (log) 2898 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID()); 2899 2900 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 2901 return NULL; 2902 } 2903 2904 const char * 2905 ProcessGDBRemote::GetDispatchQueueNameForThread 2906 ( 2907 addr_t thread_dispatch_qaddr, 2908 std::string &dispatch_queue_name 2909 ) 2910 { 2911 dispatch_queue_name.clear(); 2912 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS) 2913 { 2914 // Cache the dispatch_queue_offsets_addr value so we don't always have 2915 // to look it up 2916 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2917 { 2918 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets"); 2919 const Symbol *dispatch_queue_offsets_symbol = NULL; 2920 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false)); 2921 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec)); 2922 if (module_sp) 2923 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2924 2925 if (dispatch_queue_offsets_symbol == NULL) 2926 { 2927 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false)); 2928 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec); 2929 if (module_sp) 2930 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData); 2931 } 2932 if (dispatch_queue_offsets_symbol) 2933 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target); 2934 2935 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS) 2936 return NULL; 2937 } 2938 2939 uint8_t memory_buffer[8]; 2940 DataExtractor data (memory_buffer, 2941 sizeof(memory_buffer), 2942 m_target.GetArchitecture().GetByteOrder(), 2943 m_target.GetArchitecture().GetAddressByteSize()); 2944 2945 // Excerpt from src/queue_private.h 2946 struct dispatch_queue_offsets_s 2947 { 2948 uint16_t dqo_version; 2949 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string 2950 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process 2951 } dispatch_queue_offsets; 2952 2953 2954 Error error; 2955 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets)) 2956 { 2957 uint32_t data_offset = 0; 2958 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t))) 2959 { 2960 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2961 { 2962 data_offset = 0; 2963 lldb::addr_t queue_addr = data.GetAddress(&data_offset); 2964 if (dispatch_queue_offsets.dqo_version >= 4) 2965 { 2966 // libdispatch versions 4+, pointer to dispatch name is in the 2967 // queue structure. 2968 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label; 2969 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize()) 2970 { 2971 data_offset = 0; 2972 lldb::addr_t label_addr = data.GetAddress(&data_offset); 2973 ReadCStringFromMemory (label_addr, dispatch_queue_name, error); 2974 } 2975 } 2976 else 2977 { 2978 // libdispatch versions 1-3, dispatch name is a fixed width char array 2979 // in the queue structure. 2980 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label; 2981 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0'); 2982 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error); 2983 if (bytes_read < dispatch_queue_offsets.dqo_label_size) 2984 dispatch_queue_name.erase (bytes_read); 2985 } 2986 } 2987 } 2988 } 2989 } 2990 if (dispatch_queue_name.empty()) 2991 return NULL; 2992 return dispatch_queue_name.c_str(); 2993 } 2994 2995 //uint32_t 2996 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 2997 //{ 2998 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 2999 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 3000 // if (m_local_debugserver) 3001 // { 3002 // return Host::ListProcessesMatchingName (name, matches, pids); 3003 // } 3004 // else 3005 // { 3006 // // FIXME: Implement talking to the remote debugserver. 3007 // return 0; 3008 // } 3009 // 3010 //} 3011 // 3012 bool 3013 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 3014 lldb_private::StoppointCallbackContext *context, 3015 lldb::user_id_t break_id, 3016 lldb::user_id_t break_loc_id) 3017 { 3018 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 3019 // run so I can stop it if that's what I want to do. 3020 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3021 if (log) 3022 log->Printf("Hit New Thread Notification breakpoint."); 3023 return false; 3024 } 3025 3026 3027 bool 3028 ProcessGDBRemote::StartNoticingNewThreads() 3029 { 3030 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3031 if (m_thread_create_bp_sp) 3032 { 3033 if (log && log->GetVerbose()) 3034 log->Printf("Enabled noticing new thread breakpoint."); 3035 m_thread_create_bp_sp->SetEnabled(true); 3036 } 3037 else 3038 { 3039 PlatformSP platform_sp (m_target.GetPlatform()); 3040 if (platform_sp) 3041 { 3042 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 3043 if (m_thread_create_bp_sp) 3044 { 3045 if (log && log->GetVerbose()) 3046 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 3047 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3048 } 3049 else 3050 { 3051 if (log) 3052 log->Printf("Failed to create new thread notification breakpoint."); 3053 } 3054 } 3055 } 3056 return m_thread_create_bp_sp.get() != NULL; 3057 } 3058 3059 bool 3060 ProcessGDBRemote::StopNoticingNewThreads() 3061 { 3062 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3063 if (log && log->GetVerbose()) 3064 log->Printf ("Disabling new thread notification breakpoint."); 3065 3066 if (m_thread_create_bp_sp) 3067 m_thread_create_bp_sp->SetEnabled(false); 3068 3069 return true; 3070 } 3071 3072 lldb_private::DynamicLoader * 3073 ProcessGDBRemote::GetDynamicLoader () 3074 { 3075 if (m_dyld_ap.get() == NULL) 3076 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str())); 3077 return m_dyld_ap.get(); 3078 } 3079 3080 3081 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed 3082 { 3083 private: 3084 3085 public: 3086 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : 3087 CommandObjectParsed (interpreter, 3088 "process plugin packet history", 3089 "Dumps the packet history buffer. ", 3090 NULL) 3091 { 3092 } 3093 3094 ~CommandObjectProcessGDBRemotePacketHistory () 3095 { 3096 } 3097 3098 bool 3099 DoExecute (Args& command, CommandReturnObject &result) 3100 { 3101 const size_t argc = command.GetArgumentCount(); 3102 if (argc == 0) 3103 { 3104 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3105 if (process) 3106 { 3107 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 3108 result.SetStatus (eReturnStatusSuccessFinishResult); 3109 return true; 3110 } 3111 } 3112 else 3113 { 3114 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 3115 } 3116 result.SetStatus (eReturnStatusFailed); 3117 return false; 3118 } 3119 }; 3120 3121 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed 3122 { 3123 private: 3124 3125 public: 3126 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : 3127 CommandObjectParsed (interpreter, 3128 "process plugin packet send", 3129 "Send a custom packet through the GDB remote protocol and print the answer. " 3130 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.", 3131 NULL) 3132 { 3133 } 3134 3135 ~CommandObjectProcessGDBRemotePacketSend () 3136 { 3137 } 3138 3139 bool 3140 DoExecute (Args& command, CommandReturnObject &result) 3141 { 3142 const size_t argc = command.GetArgumentCount(); 3143 if (argc == 0) 3144 { 3145 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); 3146 result.SetStatus (eReturnStatusFailed); 3147 return false; 3148 } 3149 3150 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3151 if (process) 3152 { 3153 for (size_t i=0; i<argc; ++ i) 3154 { 3155 const char *packet_cstr = command.GetArgumentAtIndex(0); 3156 bool send_async = true; 3157 StringExtractorGDBRemote response; 3158 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 3159 result.SetStatus (eReturnStatusSuccessFinishResult); 3160 Stream &output_strm = result.GetOutputStream(); 3161 output_strm.Printf (" packet: %s\n", packet_cstr); 3162 const std::string &response_str = response.GetStringRef(); 3163 if (response_str.empty()) 3164 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 3165 else 3166 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 3167 } 3168 } 3169 return true; 3170 } 3171 }; 3172 3173 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword 3174 { 3175 private: 3176 3177 public: 3178 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : 3179 CommandObjectMultiword (interpreter, 3180 "process plugin packet", 3181 "Commands that deal with GDB remote packets.", 3182 NULL) 3183 { 3184 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter))); 3185 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter))); 3186 } 3187 3188 ~CommandObjectProcessGDBRemotePacket () 3189 { 3190 } 3191 }; 3192 3193 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword 3194 { 3195 public: 3196 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) : 3197 CommandObjectMultiword (interpreter, 3198 "process plugin", 3199 "A set of commands for operating on a ProcessGDBRemote process.", 3200 "process plugin <subcommand> [<subcommand-options>]") 3201 { 3202 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter))); 3203 } 3204 3205 ~CommandObjectMultiwordProcessGDBRemote () 3206 { 3207 } 3208 }; 3209 3210 CommandObject * 3211 ProcessGDBRemote::GetPluginCommandObject() 3212 { 3213 if (!m_command_sp) 3214 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter())); 3215 return m_command_sp.get(); 3216 } 3217