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