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