1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
16 #include <netinet/in.h>
17 #include <sys/mman.h> // for mmap
19 #include <sys/types.h>
26 // Other libraries and framework includes
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"
57 #include "lldb/Host/Host.h"
58 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
59 #include "Plugins/Process/Utility/StopInfoMachException.h"
60 #include "Utility/StringExtractorGDBRemote.h"
61 #include "GDBRemoteRegisterContext.h"
62 #include "ProcessGDBRemote.h"
63 #include "ProcessGDBRemoteLog.h"
64 #include "ThreadGDBRemote.h"
69 // Provide a function that can easily dump the packet history if we know a
70 // ProcessGDBRemote * value (which we can get from logs or from debugging).
71 // We need the function in the lldb namespace so it makes it into the final
72 // executable since the LLDB shared library only exports stuff in the lldb
73 // namespace. This allows you to attach with a debugger and call this
74 // function and get the packet history dumped to a file.
76 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
78 lldb_private::StreamFile strm;
79 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
81 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
85 #define DEBUGSERVER_BASENAME "debugserver"
87 using namespace lldb_private;
92 static PropertyDefinition
95 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
96 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
101 ePropertyPacketTimeout
104 class PluginProperties : public Properties
111 return ProcessGDBRemote::GetPluginNameStatic();
117 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
118 m_collection_sp->Initialize(g_properties);
129 const uint32_t idx = ePropertyPacketTimeout;
130 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
134 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
136 static const ProcessKDPPropertiesSP &
137 GetGlobalPluginProperties()
139 static ProcessKDPPropertiesSP g_settings_sp;
141 g_settings_sp.reset (new PluginProperties ());
142 return g_settings_sp;
145 } // anonymous namespace end
147 static bool rand_initialized = false;
149 // TODO Randomly assigning a port is unsafe. We should get an unused
150 // ephemeral port from the kernel and make sure we reserve it before passing
151 // it to debugserver.
153 #if defined (__APPLE__)
154 #define LOW_PORT (IPPORT_RESERVED)
155 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
157 #define LOW_PORT (1024u)
158 #define HIGH_PORT (49151u)
161 static inline uint16_t
164 if (!rand_initialized)
166 time_t seed = time(NULL);
168 rand_initialized = true;
171 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
175 lldb_private::ConstString
176 ProcessGDBRemote::GetPluginNameStatic()
178 static ConstString g_name("gdb-remote");
183 ProcessGDBRemote::GetPluginDescriptionStatic()
185 return "GDB Remote protocol based debugging plug-in.";
189 ProcessGDBRemote::Terminate()
191 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
196 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
198 lldb::ProcessSP process_sp;
199 if (crash_file_path == NULL)
200 process_sp.reset (new ProcessGDBRemote (target, listener));
205 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
207 if (plugin_specified_by_name)
210 // For now we are just making sure the file exists for a given module
211 Module *exe_module = target.GetExecutableModulePointer();
214 ObjectFile *exe_objfile = exe_module->GetObjectFile();
215 // We can't debug core files...
216 switch (exe_objfile->GetType())
218 case ObjectFile::eTypeInvalid:
219 case ObjectFile::eTypeCoreFile:
220 case ObjectFile::eTypeDebugInfo:
221 case ObjectFile::eTypeObjectFile:
222 case ObjectFile::eTypeSharedLibrary:
223 case ObjectFile::eTypeStubLibrary:
225 case ObjectFile::eTypeExecutable:
226 case ObjectFile::eTypeDynamicLinker:
227 case ObjectFile::eTypeUnknown:
230 return exe_module->GetFileSpec().Exists();
232 // However, if there is no executable module, we return true since we might be preparing to attach.
236 //----------------------------------------------------------------------
237 // ProcessGDBRemote constructor
238 //----------------------------------------------------------------------
239 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
240 Process (target, listener),
243 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
244 m_last_stop_packet (),
245 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
247 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
248 m_async_thread (LLDB_INVALID_HOST_THREAD),
249 m_async_thread_state(eAsyncThreadNotStarted),
250 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
252 m_continue_c_tids (),
253 m_continue_C_tids (),
254 m_continue_s_tids (),
255 m_continue_S_tids (),
256 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
257 m_max_memory_size (512),
258 m_addr_to_mmap_size (),
259 m_thread_create_bp_sp (),
260 m_waiting_for_attach (false),
261 m_destroy_tried_resuming (false),
264 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
265 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
266 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
267 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
268 if (timeout_seconds > 0)
269 m_gdb_comm.SetPacketTimeout(timeout_seconds);
272 //----------------------------------------------------------------------
274 //----------------------------------------------------------------------
275 ProcessGDBRemote::~ProcessGDBRemote()
277 // m_mach_process.UnregisterNotificationCallbacks (this);
279 // We need to call finalize on the process before destroying ourselves
280 // to make sure all of the broadcaster cleanup goes as planned. If we
281 // destruct this class, then Process::~Process() might have problems
282 // trying to fully destroy the broadcaster.
285 // The general Finalize is going to try to destroy the process and that SHOULD
286 // shut down the async thread. However, if we don't kill it it will get stranded and
287 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
289 KillDebugserverProcess();
292 //----------------------------------------------------------------------
294 //----------------------------------------------------------------------
296 ProcessGDBRemote::GetPluginName()
298 return GetPluginNameStatic();
302 ProcessGDBRemote::GetPluginVersion()
308 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
310 if (!force && m_register_info.GetNumRegisters() > 0)
314 m_register_info.Clear();
315 uint32_t reg_offset = 0;
316 uint32_t reg_num = 0;
317 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
318 response_type == StringExtractorGDBRemote::eResponse;
321 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
322 assert (packet_len < (int)sizeof(packet));
323 StringExtractorGDBRemote response;
324 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
326 response_type = response.GetResponseType();
327 if (response_type == StringExtractorGDBRemote::eResponse)
331 ConstString reg_name;
332 ConstString alt_name;
333 ConstString set_name;
334 std::vector<uint32_t> value_regs;
335 std::vector<uint32_t> invalidate_regs;
336 RegisterInfo reg_info = { NULL, // Name
339 reg_offset, // offset
340 eEncodingUint, // encoding
341 eFormatHex, // formate
343 LLDB_INVALID_REGNUM, // GCC reg num
344 LLDB_INVALID_REGNUM, // DWARF reg num
345 LLDB_INVALID_REGNUM, // generic reg num
346 reg_num, // GDB reg num
347 reg_num // native register number
353 while (response.GetNameColonValue(name, value))
355 if (name.compare("name") == 0)
357 reg_name.SetCString(value.c_str());
359 else if (name.compare("alt-name") == 0)
361 alt_name.SetCString(value.c_str());
363 else if (name.compare("bitsize") == 0)
365 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
367 else if (name.compare("offset") == 0)
369 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
370 if (reg_offset != offset)
375 else if (name.compare("encoding") == 0)
377 const Encoding encoding = Args::StringToEncoding (value.c_str());
378 if (encoding != eEncodingInvalid)
379 reg_info.encoding = encoding;
381 else if (name.compare("format") == 0)
383 Format format = eFormatInvalid;
384 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
385 reg_info.format = format;
386 else if (value.compare("binary") == 0)
387 reg_info.format = eFormatBinary;
388 else if (value.compare("decimal") == 0)
389 reg_info.format = eFormatDecimal;
390 else if (value.compare("hex") == 0)
391 reg_info.format = eFormatHex;
392 else if (value.compare("float") == 0)
393 reg_info.format = eFormatFloat;
394 else if (value.compare("vector-sint8") == 0)
395 reg_info.format = eFormatVectorOfSInt8;
396 else if (value.compare("vector-uint8") == 0)
397 reg_info.format = eFormatVectorOfUInt8;
398 else if (value.compare("vector-sint16") == 0)
399 reg_info.format = eFormatVectorOfSInt16;
400 else if (value.compare("vector-uint16") == 0)
401 reg_info.format = eFormatVectorOfUInt16;
402 else if (value.compare("vector-sint32") == 0)
403 reg_info.format = eFormatVectorOfSInt32;
404 else if (value.compare("vector-uint32") == 0)
405 reg_info.format = eFormatVectorOfUInt32;
406 else if (value.compare("vector-float32") == 0)
407 reg_info.format = eFormatVectorOfFloat32;
408 else if (value.compare("vector-uint128") == 0)
409 reg_info.format = eFormatVectorOfUInt128;
411 else if (name.compare("set") == 0)
413 set_name.SetCString(value.c_str());
415 else if (name.compare("gcc") == 0)
417 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
419 else if (name.compare("dwarf") == 0)
421 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
423 else if (name.compare("generic") == 0)
425 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
427 else if (name.compare("container-regs") == 0)
429 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
430 value_pair.second = value;
433 value_pair = value_pair.second.split(',');
434 if (!value_pair.first.empty())
436 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
437 if (reg != LLDB_INVALID_REGNUM)
438 value_regs.push_back (reg);
440 } while (!value_pair.second.empty());
442 else if (name.compare("invalidate-regs") == 0)
444 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
445 value_pair.second = value;
448 value_pair = value_pair.second.split(',');
449 if (!value_pair.first.empty())
451 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
452 if (reg != LLDB_INVALID_REGNUM)
453 invalidate_regs.push_back (reg);
455 } while (!value_pair.second.empty());
459 reg_info.byte_offset = reg_offset;
460 assert (reg_info.byte_size != 0);
461 reg_offset += reg_info.byte_size;
462 if (!value_regs.empty())
464 value_regs.push_back(LLDB_INVALID_REGNUM);
465 reg_info.value_regs = value_regs.data();
467 if (!invalidate_regs.empty())
469 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
470 reg_info.invalidate_regs = invalidate_regs.data();
473 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
482 // We didn't get anything if the accumulated reg_num is zero. See if we are
483 // debugging ARM and fill with a hard coded register set until we can get an
484 // updated debugserver down on the devices.
485 // On the other hand, if the accumulated reg_num is positive, see if we can
486 // add composite registers to the existing primordial ones.
487 bool from_scratch = (reg_num == 0);
489 const ArchSpec &target_arch = GetTarget().GetArchitecture();
490 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
491 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
493 // Use the process' architecture instead of the host arch, if available
494 ArchSpec remote_arch;
495 if (remote_process_arch.IsValid ())
496 remote_arch = remote_process_arch;
498 remote_arch = remote_host_arch;
500 if (!target_arch.IsValid())
502 if (remote_arch.IsValid()
503 && remote_arch.GetMachine() == llvm::Triple::arm
504 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
505 m_register_info.HardcodeARMRegisters(from_scratch);
507 else if (target_arch.GetMachine() == llvm::Triple::arm)
509 m_register_info.HardcodeARMRegisters(from_scratch);
512 // At this point, we can finalize our register info.
513 m_register_info.Finalize ();
517 ProcessGDBRemote::WillLaunch (Module* module)
519 return WillLaunchOrAttach ();
523 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
525 return WillLaunchOrAttach ();
529 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
531 return WillLaunchOrAttach ();
535 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
537 Error error (WillLaunchOrAttach ());
542 error = ConnectToDebugserver (remote_url);
548 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
549 if (pid == LLDB_INVALID_PROCESS_ID)
551 // We don't have a valid process ID, so note that we are connected
552 // and could now request to launch or attach, or get remote process
554 SetPrivateState (eStateConnected);
558 // We have a valid process
561 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
563 const StateType state = SetThreadStopInfo (m_last_stop_packet);
564 if (state == eStateStopped)
566 SetPrivateState (state);
569 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
572 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
576 && !GetTarget().GetArchitecture().IsValid()
577 && m_gdb_comm.GetHostArchitecture().IsValid())
579 // Prefer the *process'* architecture over that of the *host*, if available.
580 if (m_gdb_comm.GetProcessArchitecture().IsValid())
581 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
583 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
590 ProcessGDBRemote::WillLaunchOrAttach ()
593 m_stdio_communication.Clear ();
597 //----------------------------------------------------------------------
599 //----------------------------------------------------------------------
601 ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
605 uint32_t launch_flags = launch_info.GetFlags().Get();
606 const char *stdin_path = NULL;
607 const char *stdout_path = NULL;
608 const char *stderr_path = NULL;
609 const char *working_dir = launch_info.GetWorkingDirectory();
611 const ProcessLaunchInfo::FileAction *file_action;
612 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
615 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
616 stdin_path = file_action->GetPath();
618 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
621 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
622 stdout_path = file_action->GetPath();
624 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
627 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
628 stderr_path = file_action->GetPath();
631 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
632 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
633 // ::LogSetLogFile ("/dev/stdout");
634 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
636 ObjectFile * object_file = exe_module->GetObjectFile();
640 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
641 char connect_url[128];
642 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
644 // Make sure we aren't already connected?
645 if (!m_gdb_comm.IsConnected())
647 error = StartDebugserverProcess (host_port, launch_info);
651 log->Printf("failed to start debugserver process: %s", error.AsCString());
655 error = ConnectToDebugserver (connect_url);
660 lldb_utility::PseudoTerminal pty;
661 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
663 // If the debugserver is local and we aren't disabling STDIO, lets use
664 // a pseudo terminal to instead of relying on the 'O' packets for stdio
665 // since 'O' packets can really slow down debugging if the inferior
666 // does a lot of output.
667 PlatformSP platform_sp (m_target.GetPlatform());
668 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
670 const char *slave_name = NULL;
671 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
673 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
674 slave_name = pty.GetSlaveName (NULL, 0);
676 if (stdin_path == NULL)
677 stdin_path = slave_name;
679 if (stdout_path == NULL)
680 stdout_path = slave_name;
682 if (stderr_path == NULL)
683 stderr_path = slave_name;
686 // Set STDIN to /dev/null if we want STDIO disabled or if either
687 // STDOUT or STDERR have been set to something and STDIN hasn't
688 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
689 stdin_path = "/dev/null";
691 // Set STDOUT to /dev/null if we want STDIO disabled or if either
692 // STDIN or STDERR have been set to something and STDOUT hasn't
693 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
694 stdout_path = "/dev/null";
696 // Set STDERR to /dev/null if we want STDIO disabled or if either
697 // STDIN or STDOUT have been set to something and STDERR hasn't
698 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
699 stderr_path = "/dev/null";
702 m_gdb_comm.SetSTDIN (stdin_path);
704 m_gdb_comm.SetSTDOUT (stdout_path);
706 m_gdb_comm.SetSTDERR (stderr_path);
708 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
710 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
712 if (working_dir && working_dir[0])
714 m_gdb_comm.SetWorkingDir (working_dir);
717 // Send the environment and the program + arguments after we connect
718 const Args &environment = launch_info.GetEnvironmentEntries();
719 if (environment.GetArgumentCount())
721 size_t num_environment_entries = environment.GetArgumentCount();
722 for (size_t i=0; i<num_environment_entries; ++i)
724 const char *env_entry = environment.GetArgumentAtIndex(i);
725 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
730 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
731 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
732 if (arg_packet_err == 0)
734 std::string error_str;
735 if (m_gdb_comm.GetLaunchSuccess (error_str))
737 SetID (m_gdb_comm.GetCurrentProcessID ());
741 error.SetErrorString (error_str.c_str());
746 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
749 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
751 if (GetID() == LLDB_INVALID_PROCESS_ID)
754 log->Printf("failed to connect to debugserver: %s", error.AsCString());
755 KillDebugserverProcess ();
759 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
761 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
765 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
766 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
773 log->Printf("failed to connect to debugserver: %s", error.AsCString());
778 // Set our user ID to an invalid process ID.
779 SetID(LLDB_INVALID_PROCESS_ID);
780 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
781 exe_module->GetFileSpec().GetFilename().AsCString(),
782 exe_module->GetArchitecture().GetArchitectureName());
790 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
793 // Sleep and wait a bit for debugserver to start to listen...
794 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
797 const uint32_t max_retry_count = 50;
798 uint32_t retry_count = 0;
799 while (!m_gdb_comm.IsConnected())
801 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
803 m_gdb_comm.SetConnection (conn_ap.release());
806 else if (error.WasInterrupted())
808 // If we were interrupted, don't keep retrying.
814 if (retry_count >= max_retry_count)
821 if (!m_gdb_comm.IsConnected())
824 error.SetErrorString("not connected to remote gdb server");
828 // We always seem to be able to open a connection to a local port
829 // so we need to make sure we can then send data to it. If we can't
830 // then we aren't actually connected to anything, so try and do the
831 // handshake with the remote GDB server and make sure that goes
833 if (!m_gdb_comm.HandshakeWithServer (NULL))
835 m_gdb_comm.Disconnect();
837 error.SetErrorString("not connected to remote gdb server");
840 m_gdb_comm.ResetDiscoverableSettings();
841 m_gdb_comm.QueryNoAckModeSupported ();
842 m_gdb_comm.GetThreadSuffixSupported ();
843 m_gdb_comm.GetListThreadsInStopReplySupported ();
844 m_gdb_comm.GetHostInfo ();
845 m_gdb_comm.GetVContSupported ('c');
846 m_gdb_comm.GetVAttachOrWaitSupported();
848 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
849 for (size_t idx = 0; idx < num_cmds; idx++)
851 StringExtractorGDBRemote response;
852 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
858 ProcessGDBRemote::DidLaunchOrAttach ()
860 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
862 log->Printf ("ProcessGDBRemote::DidLaunch()");
863 if (GetID() != LLDB_INVALID_PROCESS_ID)
865 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
867 BuildDynamicRegisterInfo (false);
869 // See if the GDB server supports the qHostInfo information
871 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
873 // See if the GDB server supports the qProcessInfo packet, if so
874 // prefer that over the Host information as it will be more specific
877 if (m_gdb_comm.GetProcessArchitecture().IsValid())
878 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
880 if (gdb_remote_arch.IsValid())
882 ArchSpec &target_arch = GetTarget().GetArchitecture();
884 if (target_arch.IsValid())
886 // If the remote host is ARM and we have apple as the vendor, then
887 // ARM executables and shared libraries can have mixed ARM architectures.
888 // You can have an armv6 executable, and if the host is armv7, then the
889 // system will load the best possible architecture for all shared libraries
890 // it has, so we really need to take the remote host architecture as our
891 // defacto architecture in this case.
893 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
894 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
896 target_arch = gdb_remote_arch;
900 // Fill in what is missing in the triple
901 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
902 llvm::Triple &target_triple = target_arch.GetTriple();
903 if (target_triple.getVendorName().size() == 0)
905 target_triple.setVendor (remote_triple.getVendor());
907 if (target_triple.getOSName().size() == 0)
909 target_triple.setOS (remote_triple.getOS());
911 if (target_triple.getEnvironmentName().size() == 0)
912 target_triple.setEnvironment (remote_triple.getEnvironment());
919 // The target doesn't have a valid architecture yet, set it from
920 // the architecture we got from the remote GDB server
921 target_arch = gdb_remote_arch;
928 ProcessGDBRemote::DidLaunch ()
930 DidLaunchOrAttach ();
934 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
936 ProcessAttachInfo attach_info;
937 return DoAttachToProcessWithID(attach_pid, attach_info);
941 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
944 // Clear out and clean up from any current state
946 if (attach_pid != LLDB_INVALID_PROCESS_ID)
948 // Make sure we aren't already connected?
949 if (!m_gdb_comm.IsConnected())
952 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
953 char connect_url[128];
954 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
956 error = StartDebugserverProcess (host_port, attach_info);
960 const char *error_string = error.AsCString();
961 if (error_string == NULL)
962 error_string = "unable to launch " DEBUGSERVER_BASENAME;
964 SetExitStatus (-1, error_string);
968 error = ConnectToDebugserver (connect_url);
975 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
977 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
984 ProcessGDBRemote::AttachInputReaderCallback
988 lldb::InputReaderAction notification,
993 if (notification == eInputReaderGotToken)
995 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
996 if (gdb_process->m_waiting_for_attach)
997 gdb_process->m_waiting_for_attach = false;
998 reader->SetIsDone(true);
1005 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
1008 // Clear out and clean up from any current state
1011 if (process_name && process_name[0])
1013 // Make sure we aren't already connected?
1014 if (!m_gdb_comm.IsConnected())
1016 char host_port[128];
1017 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1018 char connect_url[128];
1019 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1021 error = StartDebugserverProcess (host_port, attach_info);
1024 const char *error_string = error.AsCString();
1025 if (error_string == NULL)
1026 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1028 SetExitStatus (-1, error_string);
1032 error = ConnectToDebugserver (connect_url);
1036 if (error.Success())
1038 StreamString packet;
1040 if (wait_for_launch)
1042 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1044 packet.PutCString ("vAttachWait");
1048 if (attach_info.GetIgnoreExisting())
1049 packet.PutCString("vAttachWait");
1051 packet.PutCString ("vAttachOrWait");
1055 packet.PutCString("vAttachName");
1056 packet.PutChar(';');
1057 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1059 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1068 ProcessGDBRemote::DidAttach ()
1070 DidLaunchOrAttach ();
1075 ProcessGDBRemote::WillResume ()
1077 m_continue_c_tids.clear();
1078 m_continue_C_tids.clear();
1079 m_continue_s_tids.clear();
1080 m_continue_S_tids.clear();
1085 ProcessGDBRemote::DoResume ()
1088 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1090 log->Printf ("ProcessGDBRemote::Resume()");
1092 Listener listener ("gdb-remote.resume-packet-sent");
1093 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1095 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1097 const size_t num_threads = GetThreadList().GetSize();
1099 StreamString continue_packet;
1100 bool continue_packet_error = false;
1101 if (m_gdb_comm.HasAnyVContSupport ())
1103 if (m_continue_c_tids.size() == num_threads)
1105 // All threads are continuing, just send a "c" packet
1106 continue_packet.PutCString ("c");
1110 continue_packet.PutCString ("vCont");
1112 if (!m_continue_c_tids.empty())
1114 if (m_gdb_comm.GetVContSupported ('c'))
1116 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)
1117 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1120 continue_packet_error = true;
1123 if (!continue_packet_error && !m_continue_C_tids.empty())
1125 if (m_gdb_comm.GetVContSupported ('C'))
1127 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)
1128 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1131 continue_packet_error = true;
1134 if (!continue_packet_error && !m_continue_s_tids.empty())
1136 if (m_gdb_comm.GetVContSupported ('s'))
1138 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)
1139 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1142 continue_packet_error = true;
1145 if (!continue_packet_error && !m_continue_S_tids.empty())
1147 if (m_gdb_comm.GetVContSupported ('S'))
1149 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)
1150 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1153 continue_packet_error = true;
1156 if (continue_packet_error)
1157 continue_packet.GetString().clear();
1161 continue_packet_error = true;
1163 if (continue_packet_error)
1165 // Either no vCont support, or we tried to use part of the vCont
1166 // packet that wasn't supported by the remote GDB server.
1167 // We need to try and make a simple packet that can do our continue
1168 const size_t num_continue_c_tids = m_continue_c_tids.size();
1169 const size_t num_continue_C_tids = m_continue_C_tids.size();
1170 const size_t num_continue_s_tids = m_continue_s_tids.size();
1171 const size_t num_continue_S_tids = m_continue_S_tids.size();
1172 if (num_continue_c_tids > 0)
1174 if (num_continue_c_tids == num_threads)
1176 // All threads are resuming...
1177 m_gdb_comm.SetCurrentThreadForRun (-1);
1178 continue_packet.PutChar ('c');
1179 continue_packet_error = false;
1181 else if (num_continue_c_tids == 1 &&
1182 num_continue_C_tids == 0 &&
1183 num_continue_s_tids == 0 &&
1184 num_continue_S_tids == 0 )
1186 // Only one thread is continuing
1187 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1188 continue_packet.PutChar ('c');
1189 continue_packet_error = false;
1193 if (continue_packet_error && num_continue_C_tids > 0)
1195 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1196 num_continue_C_tids > 0 &&
1197 num_continue_s_tids == 0 &&
1198 num_continue_S_tids == 0 )
1200 const int continue_signo = m_continue_C_tids.front().second;
1201 // Only one thread is continuing
1202 if (num_continue_C_tids > 1)
1204 // More that one thread with a signal, yet we don't have
1205 // vCont support and we are being asked to resume each
1206 // thread with a signal, we need to make sure they are
1207 // all the same signal, or we can't issue the continue
1208 // accurately with the current support...
1209 if (num_continue_C_tids > 1)
1211 continue_packet_error = false;
1212 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1214 if (m_continue_C_tids[i].second != continue_signo)
1215 continue_packet_error = true;
1218 if (!continue_packet_error)
1219 m_gdb_comm.SetCurrentThreadForRun (-1);
1223 // Set the continue thread ID
1224 continue_packet_error = false;
1225 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1227 if (!continue_packet_error)
1229 // Add threads continuing with the same signo...
1230 continue_packet.Printf("C%2.2x", continue_signo);
1235 if (continue_packet_error && num_continue_s_tids > 0)
1237 if (num_continue_s_tids == num_threads)
1239 // All threads are resuming...
1240 m_gdb_comm.SetCurrentThreadForRun (-1);
1241 continue_packet.PutChar ('s');
1242 continue_packet_error = false;
1244 else if (num_continue_c_tids == 0 &&
1245 num_continue_C_tids == 0 &&
1246 num_continue_s_tids == 1 &&
1247 num_continue_S_tids == 0 )
1249 // Only one thread is stepping
1250 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1251 continue_packet.PutChar ('s');
1252 continue_packet_error = false;
1256 if (!continue_packet_error && num_continue_S_tids > 0)
1258 if (num_continue_S_tids == num_threads)
1260 const int step_signo = m_continue_S_tids.front().second;
1261 // Are all threads trying to step with the same signal?
1262 continue_packet_error = false;
1263 if (num_continue_S_tids > 1)
1265 for (size_t i=1; i<num_threads; ++i)
1267 if (m_continue_S_tids[i].second != step_signo)
1268 continue_packet_error = true;
1271 if (!continue_packet_error)
1273 // Add threads stepping with the same signo...
1274 m_gdb_comm.SetCurrentThreadForRun (-1);
1275 continue_packet.Printf("S%2.2x", step_signo);
1278 else if (num_continue_c_tids == 0 &&
1279 num_continue_C_tids == 0 &&
1280 num_continue_s_tids == 0 &&
1281 num_continue_S_tids == 1 )
1283 // Only one thread is stepping with signal
1284 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1285 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1286 continue_packet_error = false;
1291 if (continue_packet_error)
1293 error.SetErrorString ("can't make continue packet for this resume");
1299 timeout = TimeValue::Now();
1300 timeout.OffsetWithSeconds (5);
1301 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1303 error.SetErrorString ("Trying to resume but the async thread is dead.");
1305 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1309 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1311 if (listener.WaitForEvent (&timeout, event_sp) == false)
1313 error.SetErrorString("Resume timed out.");
1315 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1317 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1319 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1321 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1331 ProcessGDBRemote::ClearThreadIDList ()
1333 Mutex::Locker locker(m_thread_list_real.GetMutex());
1334 m_thread_ids.clear();
1338 ProcessGDBRemote::UpdateThreadIDList ()
1340 Mutex::Locker locker(m_thread_list_real.GetMutex());
1341 bool sequence_mutex_unavailable = false;
1342 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1343 if (sequence_mutex_unavailable)
1345 return false; // We just didn't get the list
1351 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1353 // locker will keep a mutex locked until it goes out of scope
1354 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1355 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1356 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1358 size_t num_thread_ids = m_thread_ids.size();
1359 // The "m_thread_ids" thread ID list should always be updated after each stop
1360 // reply packet, but in case it isn't, update it here.
1361 if (num_thread_ids == 0)
1363 if (!UpdateThreadIDList ())
1365 num_thread_ids = m_thread_ids.size();
1368 ThreadList old_thread_list_copy(old_thread_list);
1369 if (num_thread_ids > 0)
1371 for (size_t i=0; i<num_thread_ids; ++i)
1373 tid_t tid = m_thread_ids[i];
1374 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1377 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1378 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1380 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1383 thread_sp->GetID());
1387 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1389 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1392 thread_sp->GetID());
1394 new_thread_list.AddThread(thread_sp);
1398 // Whatever that is left in old_thread_list_copy are not
1399 // present in new_thread_list. Remove non-existent threads from internal id table.
1400 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1401 for (size_t i=0; i<old_num_thread_ids; i++)
1403 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1406 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1407 m_thread_id_to_index_id_map.erase(old_thread_id);
1416 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1418 stop_packet.SetFilePos (0);
1419 const char stop_type = stop_packet.GetChar();
1425 // This is a bit of a hack, but is is required. If we did exec, we
1426 // need to clear our thread lists and also know to rebuild our dynamic
1427 // register info before we lookup and threads and populate the expedited
1428 // register values so we need to know this right away so we can cleanup
1429 // and update our registers.
1430 const uint32_t stop_id = GetStopID();
1433 // Our first stop, make sure we have a process ID, and also make
1434 // sure we know about our registers
1435 if (GetID() == LLDB_INVALID_PROCESS_ID)
1437 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1438 if (pid != LLDB_INVALID_PROCESS_ID)
1441 BuildDynamicRegisterInfo (true);
1443 // Stop with signal and thread info
1444 const uint8_t signo = stop_packet.GetHexU8();
1447 std::string thread_name;
1449 std::string description;
1450 uint32_t exc_type = 0;
1451 std::vector<addr_t> exc_data;
1452 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1454 ThreadGDBRemote *gdb_thread = NULL;
1456 while (stop_packet.GetNameColonValue(name, value))
1458 if (name.compare("metype") == 0)
1460 // exception type in big endian hex
1461 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1463 else if (name.compare("medata") == 0)
1465 // exception data in big endian hex
1466 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1468 else if (name.compare("thread") == 0)
1470 // thread in big endian hex
1471 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1472 // m_thread_list_real does have its own mutex, but we need to
1473 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1474 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1475 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1476 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1480 // Create the thread if we need to
1481 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1482 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1483 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1484 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1487 thread_sp->GetID());
1489 m_thread_list_real.AddThread(thread_sp);
1491 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1494 else if (name.compare("threads") == 0)
1496 Mutex::Locker locker(m_thread_list_real.GetMutex());
1497 m_thread_ids.clear();
1498 // A comma separated list of all threads in the current
1499 // process that includes the thread for this stop reply
1503 while ((comma_pos = value.find(',')) != std::string::npos)
1505 value[comma_pos] = '\0';
1506 // thread in big endian hex
1507 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1508 if (tid != LLDB_INVALID_THREAD_ID)
1509 m_thread_ids.push_back (tid);
1510 value.erase(0, comma_pos + 1);
1513 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1514 if (tid != LLDB_INVALID_THREAD_ID)
1515 m_thread_ids.push_back (tid);
1517 else if (name.compare("hexname") == 0)
1519 StringExtractor name_extractor;
1520 // Swap "value" over into "name_extractor"
1521 name_extractor.GetStringRef().swap(value);
1522 // Now convert the HEX bytes into a string value
1523 name_extractor.GetHexByteString (value);
1524 thread_name.swap (value);
1526 else if (name.compare("name") == 0)
1528 thread_name.swap (value);
1530 else if (name.compare("qaddr") == 0)
1532 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1534 else if (name.compare("reason") == 0)
1538 else if (name.compare("description") == 0)
1540 StringExtractor desc_extractor;
1541 // Swap "value" over into "name_extractor"
1542 desc_extractor.GetStringRef().swap(value);
1543 // Now convert the HEX bytes into a string value
1544 desc_extractor.GetHexByteString (thread_name);
1546 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1548 // We have a register number that contains an expedited
1549 // register value. Lets supply this register to our thread
1550 // so it won't have to go and read it.
1553 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1555 if (reg != UINT32_MAX)
1557 StringExtractor reg_value_extractor;
1558 // Swap "value" over into "reg_value_extractor"
1559 reg_value_extractor.GetStringRef().swap(value);
1560 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1562 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1566 reg_value_extractor.GetStringRef().c_str(),
1567 stop_packet.GetStringRef().c_str());
1576 // Clear the stop info just in case we don't set it to anything
1577 thread_sp->SetStopInfo (StopInfoSP());
1579 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1580 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1583 const size_t exc_data_size = exc_data.size();
1585 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1588 exc_data_size >= 1 ? exc_data[0] : 0,
1589 exc_data_size >= 2 ? exc_data[1] : 0,
1590 exc_data_size >= 3 ? exc_data[2] : 0));
1594 bool handled = false;
1595 bool did_exec = false;
1596 if (!reason.empty())
1598 if (reason.compare("trace") == 0)
1600 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1603 else if (reason.compare("breakpoint") == 0)
1605 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1606 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1609 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1610 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1611 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1613 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1615 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1619 StopInfoSP invalid_stop_info_sp;
1620 thread_sp->SetStopInfo (invalid_stop_info_sp);
1625 else if (reason.compare("trap") == 0)
1627 // Let the trap just use the standard signal stop reason below...
1629 else if (reason.compare("watchpoint") == 0)
1631 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1632 // TODO: locate the watchpoint somehow...
1633 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1636 else if (reason.compare("exception") == 0)
1638 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1641 else if (reason.compare("exec") == 0)
1644 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1649 if (signo && did_exec == false)
1651 if (signo == SIGTRAP)
1653 // Currently we are going to assume SIGTRAP means we are either
1654 // hitting a breakpoint or hardware single stepping.
1656 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1657 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1661 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1662 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1663 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1664 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1666 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1670 StopInfoSP invalid_stop_info_sp;
1671 thread_sp->SetStopInfo (invalid_stop_info_sp);
1676 // If we were stepping then assume the stop was the result of the trace. If we were
1677 // not stepping then report the SIGTRAP.
1678 // FIXME: We are still missing the case where we single step over a trap instruction.
1679 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1680 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1682 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1686 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1689 if (!description.empty())
1691 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1694 stop_info_sp->SetDescription (description.c_str());
1698 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1703 return eStateStopped;
1709 return eStateExited;
1714 return eStateInvalid;
1718 ProcessGDBRemote::RefreshStateAfterStop ()
1720 Mutex::Locker locker(m_thread_list_real.GetMutex());
1721 m_thread_ids.clear();
1722 // Set the thread stop info. It might have a "threads" key whose value is
1723 // a list of all thread IDs in the current process, so m_thread_ids might
1725 SetThreadStopInfo (m_last_stop_packet);
1726 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1727 if (m_thread_ids.empty())
1729 // No, we need to fetch the thread list manually
1730 UpdateThreadIDList();
1733 // Let all threads recover from stopping and do any clean up based
1734 // on the previous thread state (if any).
1735 m_thread_list_real.RefreshStateAfterStop();
1740 ProcessGDBRemote::DoHalt (bool &caused_stop)
1744 bool timed_out = false;
1745 Mutex::Locker locker;
1747 if (m_public_state.GetValue() == eStateAttaching)
1749 // We are being asked to halt during an attach. We need to just close
1750 // our file handle and debugserver will go away, and we can be done...
1751 m_gdb_comm.Disconnect();
1755 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1758 error.SetErrorString("timed out sending interrupt packet");
1760 error.SetErrorString("unknown error sending interrupt packet");
1763 caused_stop = m_gdb_comm.GetInterruptWasSent ();
1769 ProcessGDBRemote::DoDetach(bool keep_stopped)
1772 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1774 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1776 DisableAllBreakpointSites ();
1778 m_thread_list.DiscardThreadPlans();
1780 error = m_gdb_comm.Detach (keep_stopped);
1783 if (error.Success())
1784 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1786 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
1789 if (!error.Success())
1792 // Sleep for one second to let the process get all detached...
1795 SetPrivateState (eStateDetached);
1796 ResumePrivateStateThread();
1798 //KillDebugserverProcess ();
1804 ProcessGDBRemote::DoDestroy ()
1807 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1809 log->Printf ("ProcessGDBRemote::DoDestroy()");
1811 #if 0 // XXX Currently no iOS target support on FreeBSD
1812 // There is a bug in older iOS debugservers where they don't shut down the process
1813 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1814 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1815 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1816 // destroy it again.
1818 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1819 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1820 // the debugservers with this bug are equal. There really should be a better way to test this!
1822 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1823 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1824 // just do the straight-forward kill.
1826 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1827 // necessary (or helpful) to do any of this.
1829 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1831 PlatformSP platform_sp = GetTarget().GetPlatform();
1833 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1835 && platform_sp->GetName()
1836 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
1838 if (m_destroy_tried_resuming)
1841 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1845 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1846 // but we really need it to happen here and it doesn't matter if we do it twice.
1847 m_thread_list.DiscardThreadPlans();
1848 DisableAllBreakpointSites();
1850 bool stop_looks_like_crash = false;
1851 ThreadList &threads = GetThreadList();
1854 Mutex::Locker locker(threads.GetMutex());
1856 size_t num_threads = threads.GetSize();
1857 for (size_t i = 0; i < num_threads; i++)
1859 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1860 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1861 StopReason reason = eStopReasonInvalid;
1863 reason = stop_info_sp->GetStopReason();
1864 if (reason == eStopReasonBreakpoint
1865 || reason == eStopReasonException)
1868 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1869 thread_sp->GetProtocolID(),
1870 stop_info_sp->GetDescription());
1871 stop_looks_like_crash = true;
1877 if (stop_looks_like_crash)
1880 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1881 m_destroy_tried_resuming = true;
1883 // If we are going to run again before killing, it would be good to suspend all the threads
1884 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1885 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1886 // have to run the risk of letting those threads proceed a bit.
1889 Mutex::Locker locker(threads.GetMutex());
1891 size_t num_threads = threads.GetSize();
1892 for (size_t i = 0; i < num_threads; i++)
1894 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1895 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1896 StopReason reason = eStopReasonInvalid;
1898 reason = stop_info_sp->GetStopReason();
1899 if (reason != eStopReasonBreakpoint
1900 && reason != eStopReasonException)
1903 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1904 thread_sp->GetProtocolID());
1905 thread_sp->SetResumeState(eStateSuspended);
1917 // Interrupt if our inferior is running...
1918 int exit_status = SIGABRT;
1919 std::string exit_string;
1921 if (m_gdb_comm.IsConnected())
1923 if (m_public_state.GetValue() != eStateAttaching)
1926 StringExtractorGDBRemote response;
1927 bool send_async = true;
1928 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1930 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
1932 char packet_cmd = response.GetChar(0);
1934 if (packet_cmd == 'W' || packet_cmd == 'X')
1936 SetLastStopPacket (response);
1937 ClearThreadIDList ();
1938 exit_status = response.GetHexU8();
1943 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1944 exit_string.assign("got unexpected response to k packet: ");
1945 exit_string.append(response.GetStringRef());
1951 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1952 exit_string.assign("failed to send the k packet");
1955 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
1960 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1961 exit_string.assign ("killed or interrupted while attaching.");
1966 // If we missed setting the exit status on the way out, do it here.
1967 // NB set exit status can be called multiple times, the first one sets the status.
1968 exit_string.assign("destroying when not connected to debugserver");
1971 SetExitStatus(exit_status, exit_string.c_str());
1974 KillDebugserverProcess ();
1979 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
1981 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
1982 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
1985 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1987 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
1989 m_thread_list_real.Clear();
1990 m_thread_list.Clear();
1991 BuildDynamicRegisterInfo (true);
1992 m_gdb_comm.ResetDiscoverableSettings();
1994 m_last_stop_packet = response;
1998 //------------------------------------------------------------------
2000 //------------------------------------------------------------------
2003 ProcessGDBRemote::IsAlive ()
2005 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2009 ProcessGDBRemote::GetImageInfoAddress()
2011 return m_gdb_comm.GetShlibInfoAddr();
2014 //------------------------------------------------------------------
2016 //------------------------------------------------------------------
2018 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2020 if (size > m_max_memory_size)
2022 // Keep memory read sizes down to a sane limit. This function will be
2023 // called multiple times in order to complete the task by
2024 // lldb_private::Process so it is ok to do this.
2025 size = m_max_memory_size;
2029 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2030 assert (packet_len + 1 < (int)sizeof(packet));
2031 StringExtractorGDBRemote response;
2032 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
2034 if (response.IsNormalResponse())
2037 return response.GetHexBytes(buf, size, '\xdd');
2039 else if (response.IsErrorResponse())
2040 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2041 else if (response.IsUnsupportedResponse())
2042 error.SetErrorStringWithFormat("GDB server does not support reading memory");
2044 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2048 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2054 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2056 if (size > m_max_memory_size)
2058 // Keep memory read sizes down to a sane limit. This function will be
2059 // called multiple times in order to complete the task by
2060 // lldb_private::Process so it is ok to do this.
2061 size = m_max_memory_size;
2064 StreamString packet;
2065 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2066 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2067 StringExtractorGDBRemote response;
2068 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
2070 if (response.IsOKResponse())
2075 else if (response.IsErrorResponse())
2076 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2077 else if (response.IsUnsupportedResponse())
2078 error.SetErrorStringWithFormat("GDB server does not support writing memory");
2080 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2084 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2090 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2092 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2094 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2097 case eLazyBoolCalculate:
2099 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2100 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2101 return allocated_addr;
2104 // Call mmap() to create memory in the inferior..
2106 if (permissions & lldb::ePermissionsReadable)
2107 prot |= eMmapProtRead;
2108 if (permissions & lldb::ePermissionsWritable)
2109 prot |= eMmapProtWrite;
2110 if (permissions & lldb::ePermissionsExecutable)
2111 prot |= eMmapProtExec;
2113 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2114 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2115 m_addr_to_mmap_size[allocated_addr] = size;
2117 allocated_addr = LLDB_INVALID_ADDRESS;
2121 if (allocated_addr == LLDB_INVALID_ADDRESS)
2122 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2125 return allocated_addr;
2129 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2130 MemoryRegionInfo ®ion_info)
2133 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2138 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2141 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2146 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2148 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2153 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2156 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2160 case eLazyBoolCalculate:
2161 // We should never be deallocating memory without allocating memory
2162 // first so we should never get eLazyBoolCalculate
2163 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2167 if (!m_gdb_comm.DeallocateMemory (addr))
2168 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2172 // Call munmap() to deallocate memory in the inferior..
2174 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2175 if (pos != m_addr_to_mmap_size.end() &&
2176 InferiorCallMunmap(this, addr, pos->second))
2177 m_addr_to_mmap_size.erase (pos);
2179 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2188 //------------------------------------------------------------------
2190 //------------------------------------------------------------------
2192 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2194 if (m_stdio_communication.IsConnected())
2196 ConnectionStatus status;
2197 m_stdio_communication.Write(src, src_len, status, NULL);
2203 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2206 assert (bp_site != NULL);
2208 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2209 user_id_t site_id = bp_site->GetID();
2210 const addr_t addr = bp_site->GetLoadAddress();
2212 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2214 if (bp_site->IsEnabled())
2217 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2222 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2224 if (bp_site->HardwarePreferred())
2226 // Try and set hardware breakpoint, and if that fails, fall through
2227 // and set a software breakpoint?
2228 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
2230 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2232 bp_site->SetEnabled(true);
2233 bp_site->SetType (BreakpointSite::eHardware);
2239 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
2241 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2243 bp_site->SetEnabled(true);
2244 bp_site->SetType (BreakpointSite::eExternal);
2249 return EnableSoftwareBreakpoint (bp_site);
2254 const char *err_string = error.AsCString();
2255 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
2256 bp_site->GetLoadAddress(),
2257 err_string ? err_string : "NULL");
2259 // We shouldn't reach here on a successful breakpoint enable...
2260 if (error.Success())
2261 error.SetErrorToGenericError();
2266 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2269 assert (bp_site != NULL);
2270 addr_t addr = bp_site->GetLoadAddress();
2271 user_id_t site_id = bp_site->GetID();
2272 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2274 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2276 if (bp_site->IsEnabled())
2278 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2280 BreakpointSite::Type bp_type = bp_site->GetType();
2283 case BreakpointSite::eSoftware:
2284 error = DisableSoftwareBreakpoint (bp_site);
2287 case BreakpointSite::eHardware:
2288 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2289 error.SetErrorToGenericError();
2292 case BreakpointSite::eExternal:
2293 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2294 error.SetErrorToGenericError();
2297 if (error.Success())
2298 bp_site->SetEnabled(false);
2303 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2307 if (error.Success())
2308 error.SetErrorToGenericError();
2312 // Pre-requisite: wp != NULL.
2313 static GDBStoppointType
2314 GetGDBStoppointType (Watchpoint *wp)
2317 bool watch_read = wp->WatchpointRead();
2318 bool watch_write = wp->WatchpointWrite();
2320 // watch_read and watch_write cannot both be false.
2321 assert(watch_read || watch_write);
2322 if (watch_read && watch_write)
2323 return eWatchpointReadWrite;
2324 else if (watch_read)
2325 return eWatchpointRead;
2326 else // Must be watch_write, then.
2327 return eWatchpointWrite;
2331 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2336 user_id_t watchID = wp->GetID();
2337 addr_t addr = wp->GetLoadAddress();
2338 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2340 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2341 if (wp->IsEnabled())
2344 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2348 GDBStoppointType type = GetGDBStoppointType(wp);
2349 // Pass down an appropriate z/Z packet...
2350 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2352 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2354 wp->SetEnabled(true, notify);
2358 error.SetErrorString("sending gdb watchpoint packet failed");
2361 error.SetErrorString("watchpoints not supported");
2365 error.SetErrorString("Watchpoint argument was NULL.");
2367 if (error.Success())
2368 error.SetErrorToGenericError();
2373 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2378 user_id_t watchID = wp->GetID();
2380 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2382 addr_t addr = wp->GetLoadAddress();
2385 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2387 if (!wp->IsEnabled())
2390 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2391 // See also 'class WatchpointSentry' within StopInfo.cpp.
2392 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2393 // the watchpoint object to intelligently process this action.
2394 wp->SetEnabled(false, notify);
2398 if (wp->IsHardware())
2400 GDBStoppointType type = GetGDBStoppointType(wp);
2401 // Pass down an appropriate z/Z packet...
2402 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2404 wp->SetEnabled(false, notify);
2408 error.SetErrorString("sending gdb watchpoint packet failed");
2410 // TODO: clear software watchpoints if we implement them
2414 error.SetErrorString("Watchpoint argument was NULL.");
2416 if (error.Success())
2417 error.SetErrorToGenericError();
2422 ProcessGDBRemote::Clear()
2425 m_thread_list_real.Clear();
2426 m_thread_list.Clear();
2430 ProcessGDBRemote::DoSignal (int signo)
2433 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2435 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2437 if (!m_gdb_comm.SendAsyncSignal (signo))
2438 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2443 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2445 ProcessLaunchInfo launch_info;
2446 return StartDebugserverProcess(debugserver_url, launch_info);
2450 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
2453 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2455 // If we locate debugserver, keep that located version around
2456 static FileSpec g_debugserver_file_spec;
2458 ProcessLaunchInfo debugserver_launch_info;
2459 char debugserver_path[PATH_MAX];
2460 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
2462 // Always check to see if we have an environment override for the path
2463 // to the debugserver to use and use it if we do.
2464 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2465 if (env_debugserver_path)
2466 debugserver_file_spec.SetFile (env_debugserver_path, false);
2468 debugserver_file_spec = g_debugserver_file_spec;
2469 bool debugserver_exists = debugserver_file_spec.Exists();
2470 if (!debugserver_exists)
2472 // The debugserver binary is in the LLDB.framework/Resources
2474 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
2476 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
2477 debugserver_exists = debugserver_file_spec.Exists();
2478 if (debugserver_exists)
2480 g_debugserver_file_spec = debugserver_file_spec;
2484 g_debugserver_file_spec.Clear();
2485 debugserver_file_spec.Clear();
2490 if (debugserver_exists)
2492 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2494 m_stdio_communication.Clear();
2496 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2498 Args &debugserver_args = debugserver_launch_info.GetArguments();
2499 char arg_cstr[PATH_MAX];
2501 // Start args with "debugserver /file/path -r --"
2502 debugserver_args.AppendArgument(debugserver_path);
2503 debugserver_args.AppendArgument(debugserver_url);
2504 // use native registers, not the GDB registers
2505 debugserver_args.AppendArgument("--native-regs");
2506 // make debugserver run in its own session so signals generated by
2507 // special terminal key sequences (^C) don't affect debugserver
2508 debugserver_args.AppendArgument("--setsid");
2510 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2511 if (env_debugserver_log_file)
2513 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2514 debugserver_args.AppendArgument(arg_cstr);
2517 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2518 if (env_debugserver_log_flags)
2520 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2521 debugserver_args.AppendArgument(arg_cstr);
2523 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2524 // debugserver_args.AppendArgument("--log-flags=0x802e0e");
2526 // We currently send down all arguments, attach pids, or attach
2527 // process names in dedicated GDB server packets, so we don't need
2528 // to pass them as arguments. This is currently because of all the
2529 // things we need to setup prior to launching: the environment,
2530 // current working dir, file actions, etc.
2532 // Now append the program arguments
2535 // Terminate the debugserver args so we can now append the inferior args
2536 debugserver_args.AppendArgument("--");
2538 for (int i = 0; inferior_argv[i] != NULL; ++i)
2539 debugserver_args.AppendArgument (inferior_argv[i]);
2541 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2543 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2544 debugserver_args.AppendArgument (arg_cstr);
2546 else if (attach_name && attach_name[0])
2548 if (wait_for_launch)
2549 debugserver_args.AppendArgument ("--waitfor");
2551 debugserver_args.AppendArgument ("--attach");
2552 debugserver_args.AppendArgument (attach_name);
2556 ProcessLaunchInfo::FileAction file_action;
2558 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2559 // to "/dev/null" if we run into any problems.
2560 file_action.Close (STDIN_FILENO);
2561 debugserver_launch_info.AppendFileAction (file_action);
2562 file_action.Close (STDOUT_FILENO);
2563 debugserver_launch_info.AppendFileAction (file_action);
2564 file_action.Close (STDERR_FILENO);
2565 debugserver_launch_info.AppendFileAction (file_action);
2570 debugserver_args.Dump (&strm);
2571 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2574 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2575 debugserver_launch_info.SetUserID(process_info.GetUserID());
2577 error = Host::LaunchProcess(debugserver_launch_info);
2579 if (error.Success ())
2580 m_debugserver_pid = debugserver_launch_info.GetProcessID();
2582 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2584 if (error.Fail() || log)
2585 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
2589 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
2592 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2593 StartAsyncThread ();
2599 ProcessGDBRemote::MonitorDebugserverProcess
2601 void *callback_baton,
2602 lldb::pid_t debugserver_pid,
2603 bool exited, // True if the process did exit
2604 int signo, // Zero for no signal
2605 int exit_status // Exit value of process if signal is zero
2608 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2609 // and might not exist anymore, so we need to carefully try to get the
2610 // target for this process first since we have a race condition when
2611 // we are done running between getting the notice that the inferior
2612 // process has died and the debugserver that was debugging this process.
2613 // In our test suite, we are also continually running process after
2614 // process, so we must be very careful to make sure:
2615 // 1 - process object hasn't been deleted already
2616 // 2 - that a new process object hasn't been recreated in its place
2618 // "debugserver_pid" argument passed in is the process ID for
2619 // debugserver that we are tracking...
2620 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2622 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2624 // Get a shared pointer to the target that has a matching process pointer.
2625 // This target could be gone, or the target could already have a new process
2626 // object inside of it
2627 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2630 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2634 // We found a process in a target that matches, but another thread
2635 // might be in the process of launching a new process that will
2636 // soon replace it, so get a shared pointer to the process so we
2637 // can keep it alive.
2638 ProcessSP process_sp (target_sp->GetProcessSP());
2639 // Now we have a shared pointer to the process that can't go away on us
2640 // so we now make sure it was the same as the one passed in, and also make
2641 // sure that our previous "process *" didn't get deleted and have a new
2642 // "process *" created in its place with the same pointer. To verify this
2643 // we make sure the process has our debugserver process ID. If we pass all
2644 // of these tests, then we are sure that this process is the one we were
2646 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2648 // Sleep for a half a second to make sure our inferior process has
2649 // time to set its exit status before we set it incorrectly when
2650 // both the debugserver and the inferior process shut down.
2652 // If our process hasn't yet exited, debugserver might have died.
2653 // If the process did exit, the we are reaping it.
2654 const StateType state = process->GetState();
2656 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2657 state != eStateInvalid &&
2658 state != eStateUnloaded &&
2659 state != eStateExited &&
2660 state != eStateDetached)
2662 char error_str[1024];
2665 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2667 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2669 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2673 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2676 process->SetExitStatus (-1, error_str);
2678 // Debugserver has exited we need to let our ProcessGDBRemote
2679 // know that it no longer has a debugserver instance
2680 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2687 ProcessGDBRemote::KillDebugserverProcess ()
2689 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2691 ::kill (m_debugserver_pid, SIGINT);
2692 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2697 ProcessGDBRemote::Initialize()
2699 static bool g_initialized = false;
2701 if (g_initialized == false)
2703 g_initialized = true;
2704 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2705 GetPluginDescriptionStatic(),
2707 DebuggerInitialize);
2709 Log::Callbacks log_callbacks = {
2710 ProcessGDBRemoteLog::DisableLog,
2711 ProcessGDBRemoteLog::EnableLog,
2712 ProcessGDBRemoteLog::ListLogCategories
2715 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2720 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2722 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2724 const bool is_global_setting = true;
2725 PluginManager::CreateSettingForProcessPlugin (debugger,
2726 GetGlobalPluginProperties()->GetValueProperties(),
2727 ConstString ("Properties for the gdb-remote process plug-in."),
2733 ProcessGDBRemote::StartAsyncThread ()
2735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2738 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2740 Mutex::Locker start_locker(m_async_thread_state_mutex);
2741 if (m_async_thread_state == eAsyncThreadNotStarted)
2743 // Create a thread that watches our internal state and controls which
2744 // events make it to clients (into the DCProcess event queue).
2745 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2746 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2748 m_async_thread_state = eAsyncThreadRunning;
2756 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2757 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2759 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2760 if (m_async_thread_state == eAsyncThreadRunning)
2768 ProcessGDBRemote::StopAsyncThread ()
2770 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2773 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2775 Mutex::Locker start_locker(m_async_thread_state_mutex);
2776 if (m_async_thread_state == eAsyncThreadRunning)
2778 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2780 // This will shut down the async thread.
2781 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2783 // Stop the stdio thread
2784 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2786 Host::ThreadJoin (m_async_thread, NULL, NULL);
2788 m_async_thread_state = eAsyncThreadDone;
2793 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2799 ProcessGDBRemote::AsyncThread (void *arg)
2801 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2803 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2805 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
2807 Listener listener ("ProcessGDBRemote::AsyncThread");
2809 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2810 eBroadcastBitAsyncThreadShouldExit;
2812 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2814 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2820 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2821 if (listener.WaitForEvent (NULL, event_sp))
2823 const uint32_t event_type = event_sp->GetType();
2824 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
2827 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2831 case eBroadcastBitAsyncContinue:
2833 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2835 if (continue_packet)
2837 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2838 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2840 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2842 if (::strstr (continue_cstr, "vAttach") == NULL)
2843 process->SetPrivateState(eStateRunning);
2844 StringExtractorGDBRemote response;
2845 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2847 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2848 // The thread ID list might be contained within the "response", or the stop reply packet that
2849 // caused the stop. So clear it now before we give the stop reply packet to the process
2850 // using the process->SetLastStopPacket()...
2851 process->ClearThreadIDList ();
2857 case eStateSuspended:
2858 process->SetLastStopPacket (response);
2859 process->SetPrivateState (stop_state);
2863 process->SetLastStopPacket (response);
2864 process->ClearThreadIDList();
2865 response.SetFilePos(1);
2866 process->SetExitStatus(response.GetHexU8(), NULL);
2871 process->SetExitStatus(-1, "lost connection");
2875 process->SetPrivateState (stop_state);
2882 case eBroadcastBitAsyncThreadShouldExit:
2884 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2890 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2895 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2897 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2899 process->SetExitStatus (-1, "lost connection");
2907 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2914 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
2916 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2921 ProcessGDBRemote::GetDispatchQueueNameForThread
2923 addr_t thread_dispatch_qaddr,
2924 std::string &dispatch_queue_name
2927 dispatch_queue_name.clear();
2928 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2930 // Cache the dispatch_queue_offsets_addr value so we don't always have
2932 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2934 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2935 const Symbol *dispatch_queue_offsets_symbol = NULL;
2936 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2937 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
2939 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2941 if (dispatch_queue_offsets_symbol == NULL)
2943 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2944 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
2946 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2948 if (dispatch_queue_offsets_symbol)
2949 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
2951 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2955 uint8_t memory_buffer[8];
2956 DataExtractor data (memory_buffer,
2957 sizeof(memory_buffer),
2958 m_target.GetArchitecture().GetByteOrder(),
2959 m_target.GetArchitecture().GetAddressByteSize());
2961 // Excerpt from src/queue_private.h
2962 struct dispatch_queue_offsets_s
2964 uint16_t dqo_version;
2965 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2966 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process
2967 } dispatch_queue_offsets;
2971 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2973 lldb::offset_t data_offset = 0;
2974 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2976 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2979 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2980 if (dispatch_queue_offsets.dqo_version >= 4)
2982 // libdispatch versions 4+, pointer to dispatch name is in the
2984 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2985 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2988 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2989 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2994 // libdispatch versions 1-3, dispatch name is a fixed width char array
2995 // in the queue structure.
2996 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2997 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2998 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2999 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
3000 dispatch_queue_name.erase (bytes_read);
3006 if (dispatch_queue_name.empty())
3008 return dispatch_queue_name.c_str();
3012 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3014 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3015 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3016 // if (m_local_debugserver)
3018 // return Host::ListProcessesMatchingName (name, matches, pids);
3022 // // FIXME: Implement talking to the remote debugserver.
3029 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3030 lldb_private::StoppointCallbackContext *context,
3031 lldb::user_id_t break_id,
3032 lldb::user_id_t break_loc_id)
3034 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3035 // run so I can stop it if that's what I want to do.
3036 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3038 log->Printf("Hit New Thread Notification breakpoint.");
3044 ProcessGDBRemote::StartNoticingNewThreads()
3046 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3047 if (m_thread_create_bp_sp)
3049 if (log && log->GetVerbose())
3050 log->Printf("Enabled noticing new thread breakpoint.");
3051 m_thread_create_bp_sp->SetEnabled(true);
3055 PlatformSP platform_sp (m_target.GetPlatform());
3058 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3059 if (m_thread_create_bp_sp)
3061 if (log && log->GetVerbose())
3062 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3063 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3068 log->Printf("Failed to create new thread notification breakpoint.");
3072 return m_thread_create_bp_sp.get() != NULL;
3076 ProcessGDBRemote::StopNoticingNewThreads()
3078 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3079 if (log && log->GetVerbose())
3080 log->Printf ("Disabling new thread notification breakpoint.");
3082 if (m_thread_create_bp_sp)
3083 m_thread_create_bp_sp->SetEnabled(false);
3088 lldb_private::DynamicLoader *
3089 ProcessGDBRemote::GetDynamicLoader ()
3091 if (m_dyld_ap.get() == NULL)
3092 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3093 return m_dyld_ap.get();
3097 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3102 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3103 CommandObjectParsed (interpreter,
3104 "process plugin packet history",
3105 "Dumps the packet history buffer. ",
3110 ~CommandObjectProcessGDBRemotePacketHistory ()
3115 DoExecute (Args& command, CommandReturnObject &result)
3117 const size_t argc = command.GetArgumentCount();
3120 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3123 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3124 result.SetStatus (eReturnStatusSuccessFinishResult);
3130 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3132 result.SetStatus (eReturnStatusFailed);
3137 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3142 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3143 CommandObjectParsed (interpreter,
3144 "process plugin packet send",
3145 "Send a custom packet through the GDB remote protocol and print the answer. "
3146 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3151 ~CommandObjectProcessGDBRemotePacketSend ()
3156 DoExecute (Args& command, CommandReturnObject &result)
3158 const size_t argc = command.GetArgumentCount();
3161 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3162 result.SetStatus (eReturnStatusFailed);
3166 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3169 for (size_t i=0; i<argc; ++ i)
3171 const char *packet_cstr = command.GetArgumentAtIndex(0);
3172 bool send_async = true;
3173 StringExtractorGDBRemote response;
3174 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3175 result.SetStatus (eReturnStatusSuccessFinishResult);
3176 Stream &output_strm = result.GetOutputStream();
3177 output_strm.Printf (" packet: %s\n", packet_cstr);
3178 std::string &response_str = response.GetStringRef();
3180 if (strstr(packet_cstr, "qGetProfileData") != NULL)
3182 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3185 if (response_str.empty())
3186 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3188 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3195 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3200 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3201 CommandObjectRaw (interpreter,
3202 "process plugin packet monitor",
3203 "Send a qRcmd packet through the GDB remote protocol and print the response."
3204 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3209 ~CommandObjectProcessGDBRemotePacketMonitor ()
3214 DoExecute (const char *command, CommandReturnObject &result)
3216 if (command == NULL || command[0] == '\0')
3218 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3219 result.SetStatus (eReturnStatusFailed);
3223 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3226 StreamString packet;
3227 packet.PutCString("qRcmd,");
3228 packet.PutBytesAsRawHex8(command, strlen(command));
3229 const char *packet_cstr = packet.GetString().c_str();
3231 bool send_async = true;
3232 StringExtractorGDBRemote response;
3233 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3234 result.SetStatus (eReturnStatusSuccessFinishResult);
3235 Stream &output_strm = result.GetOutputStream();
3236 output_strm.Printf (" packet: %s\n", packet_cstr);
3237 const std::string &response_str = response.GetStringRef();
3239 if (response_str.empty())
3240 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3242 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3248 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3253 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3254 CommandObjectMultiword (interpreter,
3255 "process plugin packet",
3256 "Commands that deal with GDB remote packets.",
3259 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3260 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3261 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3264 ~CommandObjectProcessGDBRemotePacket ()
3269 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3272 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3273 CommandObjectMultiword (interpreter,
3275 "A set of commands for operating on a ProcessGDBRemote process.",
3276 "process plugin <subcommand> [<subcommand-options>]")
3278 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3281 ~CommandObjectMultiwordProcessGDBRemote ()
3287 ProcessGDBRemote::GetPluginCommandObject()
3290 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3291 return m_command_sp.get();