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"
11 #include "lldb/Host/Config.h"
16 #ifndef LLDB_DISABLE_POSIX
18 #include <netinet/in.h>
19 #include <sys/mman.h> // for mmap
22 #include <sys/types.h>
29 // Other libraries and framework includes
31 #include "lldb/Breakpoint/Watchpoint.h"
32 #include "lldb/Interpreter/Args.h"
33 #include "lldb/Core/ArchSpec.h"
34 #include "lldb/Core/Debugger.h"
35 #include "lldb/Core/ConnectionFileDescriptor.h"
36 #include "lldb/Host/FileSpec.h"
37 #include "lldb/Core/Module.h"
38 #include "lldb/Core/ModuleSpec.h"
39 #include "lldb/Core/PluginManager.h"
40 #include "lldb/Core/State.h"
41 #include "lldb/Core/StreamFile.h"
42 #include "lldb/Core/StreamString.h"
43 #include "lldb/Core/Timer.h"
44 #include "lldb/Core/Value.h"
45 #include "lldb/Host/Symbols.h"
46 #include "lldb/Host/TimeValue.h"
47 #include "lldb/Interpreter/CommandInterpreter.h"
48 #include "lldb/Interpreter/CommandObject.h"
49 #include "lldb/Interpreter/CommandObjectMultiword.h"
50 #include "lldb/Interpreter/CommandReturnObject.h"
51 #ifndef LLDB_DISABLE_PYTHON
52 #include "lldb/Interpreter/PythonDataObjects.h"
54 #include "lldb/Symbol/ObjectFile.h"
55 #include "lldb/Target/DynamicLoader.h"
56 #include "lldb/Target/Target.h"
57 #include "lldb/Target/TargetList.h"
58 #include "lldb/Target/ThreadPlanCallFunction.h"
59 #include "lldb/Utility/PseudoTerminal.h"
62 #include "lldb/Host/Host.h"
63 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
64 #include "Plugins/Process/Utility/StopInfoMachException.h"
65 #include "Utility/StringExtractorGDBRemote.h"
66 #include "GDBRemoteRegisterContext.h"
67 #include "ProcessGDBRemote.h"
68 #include "ProcessGDBRemoteLog.h"
69 #include "ThreadGDBRemote.h"
74 // Provide a function that can easily dump the packet history if we know a
75 // ProcessGDBRemote * value (which we can get from logs or from debugging).
76 // We need the function in the lldb namespace so it makes it into the final
77 // executable since the LLDB shared library only exports stuff in the lldb
78 // namespace. This allows you to attach with a debugger and call this
79 // function and get the packet history dumped to a file.
81 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
83 lldb_private::StreamFile strm;
84 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
86 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
90 #define DEBUGSERVER_BASENAME "debugserver"
92 using namespace lldb_private;
97 static PropertyDefinition
100 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
101 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
102 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
107 ePropertyPacketTimeout,
108 ePropertyTargetDefinitionFile
111 class PluginProperties : public Properties
118 return ProcessGDBRemote::GetPluginNameStatic();
124 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
125 m_collection_sp->Initialize(g_properties);
136 const uint32_t idx = ePropertyPacketTimeout;
137 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
141 SetPacketTimeout(uint64_t timeout)
143 const uint32_t idx = ePropertyPacketTimeout;
144 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
148 GetTargetDefinitionFile () const
150 const uint32_t idx = ePropertyTargetDefinitionFile;
151 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
155 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
157 static const ProcessKDPPropertiesSP &
158 GetGlobalPluginProperties()
160 static ProcessKDPPropertiesSP g_settings_sp;
162 g_settings_sp.reset (new PluginProperties ());
163 return g_settings_sp;
166 } // anonymous namespace end
168 static bool rand_initialized = false;
170 // TODO Randomly assigning a port is unsafe. We should get an unused
171 // ephemeral port from the kernel and make sure we reserve it before passing
172 // it to debugserver.
174 #if defined (__APPLE__)
175 #define LOW_PORT (IPPORT_RESERVED)
176 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
178 #define LOW_PORT (1024u)
179 #define HIGH_PORT (49151u)
182 static inline uint16_t
185 if (!rand_initialized)
187 time_t seed = time(NULL);
189 rand_initialized = true;
192 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
196 lldb_private::ConstString
197 ProcessGDBRemote::GetPluginNameStatic()
199 static ConstString g_name("gdb-remote");
204 ProcessGDBRemote::GetPluginDescriptionStatic()
206 return "GDB Remote protocol based debugging plug-in.";
210 ProcessGDBRemote::Terminate()
212 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
217 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
219 lldb::ProcessSP process_sp;
220 if (crash_file_path == NULL)
221 process_sp.reset (new ProcessGDBRemote (target, listener));
226 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
228 if (plugin_specified_by_name)
231 // For now we are just making sure the file exists for a given module
232 Module *exe_module = target.GetExecutableModulePointer();
235 ObjectFile *exe_objfile = exe_module->GetObjectFile();
236 // We can't debug core files...
237 switch (exe_objfile->GetType())
239 case ObjectFile::eTypeInvalid:
240 case ObjectFile::eTypeCoreFile:
241 case ObjectFile::eTypeDebugInfo:
242 case ObjectFile::eTypeObjectFile:
243 case ObjectFile::eTypeSharedLibrary:
244 case ObjectFile::eTypeStubLibrary:
246 case ObjectFile::eTypeExecutable:
247 case ObjectFile::eTypeDynamicLinker:
248 case ObjectFile::eTypeUnknown:
251 return exe_module->GetFileSpec().Exists();
253 // However, if there is no executable module, we return true since we might be preparing to attach.
257 //----------------------------------------------------------------------
258 // ProcessGDBRemote constructor
259 //----------------------------------------------------------------------
260 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
261 Process (target, listener),
264 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
265 m_last_stop_packet (),
266 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
268 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
269 m_async_thread (LLDB_INVALID_HOST_THREAD),
270 m_async_thread_state(eAsyncThreadNotStarted),
271 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
273 m_continue_c_tids (),
274 m_continue_C_tids (),
275 m_continue_s_tids (),
276 m_continue_S_tids (),
277 m_max_memory_size (512),
278 m_addr_to_mmap_size (),
279 m_thread_create_bp_sp (),
280 m_waiting_for_attach (false),
281 m_destroy_tried_resuming (false),
283 m_breakpoint_pc_offset (0)
285 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
286 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
287 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
288 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
289 if (timeout_seconds > 0)
290 m_gdb_comm.SetPacketTimeout(timeout_seconds);
293 //----------------------------------------------------------------------
295 //----------------------------------------------------------------------
296 ProcessGDBRemote::~ProcessGDBRemote()
298 // m_mach_process.UnregisterNotificationCallbacks (this);
300 // We need to call finalize on the process before destroying ourselves
301 // to make sure all of the broadcaster cleanup goes as planned. If we
302 // destruct this class, then Process::~Process() might have problems
303 // trying to fully destroy the broadcaster.
306 // The general Finalize is going to try to destroy the process and that SHOULD
307 // shut down the async thread. However, if we don't kill it it will get stranded and
308 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
310 KillDebugserverProcess();
313 //----------------------------------------------------------------------
315 //----------------------------------------------------------------------
317 ProcessGDBRemote::GetPluginName()
319 return GetPluginNameStatic();
323 ProcessGDBRemote::GetPluginVersion()
329 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
331 #ifndef LLDB_DISABLE_PYTHON
332 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
334 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
335 if (module_object_sp)
337 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
339 "gdb-server-target-definition",
342 PythonDictionary target_dict(target_definition_sp);
346 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
349 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
351 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
353 GetTarget().SetArchitecture(host_arch);
357 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
359 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
371 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
373 if (!force && m_register_info.GetNumRegisters() > 0)
377 m_register_info.Clear();
378 uint32_t reg_offset = 0;
379 uint32_t reg_num = 0;
380 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
381 response_type == StringExtractorGDBRemote::eResponse;
384 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
385 assert (packet_len < (int)sizeof(packet));
386 StringExtractorGDBRemote response;
387 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
389 response_type = response.GetResponseType();
390 if (response_type == StringExtractorGDBRemote::eResponse)
394 ConstString reg_name;
395 ConstString alt_name;
396 ConstString set_name;
397 std::vector<uint32_t> value_regs;
398 std::vector<uint32_t> invalidate_regs;
399 RegisterInfo reg_info = { NULL, // Name
402 reg_offset, // offset
403 eEncodingUint, // encoding
404 eFormatHex, // formate
406 LLDB_INVALID_REGNUM, // GCC reg num
407 LLDB_INVALID_REGNUM, // DWARF reg num
408 LLDB_INVALID_REGNUM, // generic reg num
409 reg_num, // GDB reg num
410 reg_num // native register number
416 while (response.GetNameColonValue(name, value))
418 if (name.compare("name") == 0)
420 reg_name.SetCString(value.c_str());
422 else if (name.compare("alt-name") == 0)
424 alt_name.SetCString(value.c_str());
426 else if (name.compare("bitsize") == 0)
428 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
430 else if (name.compare("offset") == 0)
432 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
433 if (reg_offset != offset)
438 else if (name.compare("encoding") == 0)
440 const Encoding encoding = Args::StringToEncoding (value.c_str());
441 if (encoding != eEncodingInvalid)
442 reg_info.encoding = encoding;
444 else if (name.compare("format") == 0)
446 Format format = eFormatInvalid;
447 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
448 reg_info.format = format;
449 else if (value.compare("binary") == 0)
450 reg_info.format = eFormatBinary;
451 else if (value.compare("decimal") == 0)
452 reg_info.format = eFormatDecimal;
453 else if (value.compare("hex") == 0)
454 reg_info.format = eFormatHex;
455 else if (value.compare("float") == 0)
456 reg_info.format = eFormatFloat;
457 else if (value.compare("vector-sint8") == 0)
458 reg_info.format = eFormatVectorOfSInt8;
459 else if (value.compare("vector-uint8") == 0)
460 reg_info.format = eFormatVectorOfUInt8;
461 else if (value.compare("vector-sint16") == 0)
462 reg_info.format = eFormatVectorOfSInt16;
463 else if (value.compare("vector-uint16") == 0)
464 reg_info.format = eFormatVectorOfUInt16;
465 else if (value.compare("vector-sint32") == 0)
466 reg_info.format = eFormatVectorOfSInt32;
467 else if (value.compare("vector-uint32") == 0)
468 reg_info.format = eFormatVectorOfUInt32;
469 else if (value.compare("vector-float32") == 0)
470 reg_info.format = eFormatVectorOfFloat32;
471 else if (value.compare("vector-uint128") == 0)
472 reg_info.format = eFormatVectorOfUInt128;
474 else if (name.compare("set") == 0)
476 set_name.SetCString(value.c_str());
478 else if (name.compare("gcc") == 0)
480 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
482 else if (name.compare("dwarf") == 0)
484 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
486 else if (name.compare("generic") == 0)
488 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
490 else if (name.compare("container-regs") == 0)
492 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
493 value_pair.second = value;
496 value_pair = value_pair.second.split(',');
497 if (!value_pair.first.empty())
499 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
500 if (reg != LLDB_INVALID_REGNUM)
501 value_regs.push_back (reg);
503 } while (!value_pair.second.empty());
505 else if (name.compare("invalidate-regs") == 0)
507 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
508 value_pair.second = value;
511 value_pair = value_pair.second.split(',');
512 if (!value_pair.first.empty())
514 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
515 if (reg != LLDB_INVALID_REGNUM)
516 invalidate_regs.push_back (reg);
518 } while (!value_pair.second.empty());
522 reg_info.byte_offset = reg_offset;
523 assert (reg_info.byte_size != 0);
524 reg_offset += reg_info.byte_size;
525 if (!value_regs.empty())
527 value_regs.push_back(LLDB_INVALID_REGNUM);
528 reg_info.value_regs = value_regs.data();
530 if (!invalidate_regs.empty())
532 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
533 reg_info.invalidate_regs = invalidate_regs.data();
536 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
540 break; // ensure exit before reg_num is incremented
549 // Check if qHostInfo specified a specific packet timeout for this connection.
550 // If so then lets update our setting so the user knows what the timeout is
552 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
553 if (host_packet_timeout)
555 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
561 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
563 if (target_definition_fspec)
565 // See if we can get register definitions from a python file
566 if (ParsePythonTargetDefinition (target_definition_fspec))
571 // We didn't get anything if the accumulated reg_num is zero. See if we are
572 // debugging ARM and fill with a hard coded register set until we can get an
573 // updated debugserver down on the devices.
574 // On the other hand, if the accumulated reg_num is positive, see if we can
575 // add composite registers to the existing primordial ones.
576 bool from_scratch = (reg_num == 0);
578 const ArchSpec &target_arch = GetTarget().GetArchitecture();
579 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
580 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
582 // Use the process' architecture instead of the host arch, if available
583 ArchSpec remote_arch;
584 if (remote_process_arch.IsValid ())
585 remote_arch = remote_process_arch;
587 remote_arch = remote_host_arch;
589 if (!target_arch.IsValid())
591 if (remote_arch.IsValid()
592 && remote_arch.GetMachine() == llvm::Triple::arm
593 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
594 m_register_info.HardcodeARMRegisters(from_scratch);
596 else if (target_arch.GetMachine() == llvm::Triple::arm)
598 m_register_info.HardcodeARMRegisters(from_scratch);
601 // At this point, we can finalize our register info.
602 m_register_info.Finalize ();
606 ProcessGDBRemote::WillLaunch (Module* module)
608 return WillLaunchOrAttach ();
612 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
614 return WillLaunchOrAttach ();
618 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
620 return WillLaunchOrAttach ();
624 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
626 Error error (WillLaunchOrAttach ());
631 error = ConnectToDebugserver (remote_url);
637 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
638 if (pid == LLDB_INVALID_PROCESS_ID)
640 // We don't have a valid process ID, so note that we are connected
641 // and could now request to launch or attach, or get remote process
643 SetPrivateState (eStateConnected);
647 // We have a valid process
650 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
652 if (!m_target.GetArchitecture().IsValid())
654 if (m_gdb_comm.GetProcessArchitecture().IsValid())
656 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
660 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
664 const StateType state = SetThreadStopInfo (m_last_stop_packet);
665 if (state == eStateStopped)
667 SetPrivateState (state);
670 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
673 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
677 && !GetTarget().GetArchitecture().IsValid()
678 && m_gdb_comm.GetHostArchitecture().IsValid())
680 // Prefer the *process'* architecture over that of the *host*, if available.
681 if (m_gdb_comm.GetProcessArchitecture().IsValid())
682 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
684 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
691 ProcessGDBRemote::WillLaunchOrAttach ()
694 m_stdio_communication.Clear ();
698 //----------------------------------------------------------------------
700 //----------------------------------------------------------------------
702 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
706 uint32_t launch_flags = launch_info.GetFlags().Get();
707 const char *stdin_path = NULL;
708 const char *stdout_path = NULL;
709 const char *stderr_path = NULL;
710 const char *working_dir = launch_info.GetWorkingDirectory();
712 const ProcessLaunchInfo::FileAction *file_action;
713 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
716 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
717 stdin_path = file_action->GetPath();
719 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
722 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
723 stdout_path = file_action->GetPath();
725 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
728 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
729 stderr_path = file_action->GetPath();
732 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
733 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
734 // ::LogSetLogFile ("/dev/stdout");
735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
737 ObjectFile * object_file = exe_module->GetObjectFile();
740 // Make sure we aren't already connected?
741 if (!m_gdb_comm.IsConnected())
743 error = LaunchAndConnectToDebugserver (launch_info);
748 lldb_utility::PseudoTerminal pty;
749 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
751 // If the debugserver is local and we aren't disabling STDIO, lets use
752 // a pseudo terminal to instead of relying on the 'O' packets for stdio
753 // since 'O' packets can really slow down debugging if the inferior
754 // does a lot of output.
755 PlatformSP platform_sp (m_target.GetPlatform());
756 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
758 const char *slave_name = NULL;
759 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
761 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
762 slave_name = pty.GetSlaveName (NULL, 0);
764 if (stdin_path == NULL)
765 stdin_path = slave_name;
767 if (stdout_path == NULL)
768 stdout_path = slave_name;
770 if (stderr_path == NULL)
771 stderr_path = slave_name;
774 // Set STDIN to /dev/null if we want STDIO disabled or if either
775 // STDOUT or STDERR have been set to something and STDIN hasn't
776 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
777 stdin_path = "/dev/null";
779 // Set STDOUT to /dev/null if we want STDIO disabled or if either
780 // STDIN or STDERR have been set to something and STDOUT hasn't
781 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
782 stdout_path = "/dev/null";
784 // Set STDERR to /dev/null if we want STDIO disabled or if either
785 // STDIN or STDOUT have been set to something and STDERR hasn't
786 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
787 stderr_path = "/dev/null";
790 m_gdb_comm.SetSTDIN (stdin_path);
792 m_gdb_comm.SetSTDOUT (stdout_path);
794 m_gdb_comm.SetSTDERR (stderr_path);
796 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
798 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
800 if (working_dir && working_dir[0])
802 m_gdb_comm.SetWorkingDir (working_dir);
805 // Send the environment and the program + arguments after we connect
806 const Args &environment = launch_info.GetEnvironmentEntries();
807 if (environment.GetArgumentCount())
809 size_t num_environment_entries = environment.GetArgumentCount();
810 for (size_t i=0; i<num_environment_entries; ++i)
812 const char *env_entry = environment.GetArgumentAtIndex(i);
813 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
818 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
819 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
820 if (arg_packet_err == 0)
822 std::string error_str;
823 if (m_gdb_comm.GetLaunchSuccess (error_str))
825 SetID (m_gdb_comm.GetCurrentProcessID ());
829 error.SetErrorString (error_str.c_str());
834 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
837 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
839 if (GetID() == LLDB_INVALID_PROCESS_ID)
842 log->Printf("failed to connect to debugserver: %s", error.AsCString());
843 KillDebugserverProcess ();
847 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
849 if (!m_target.GetArchitecture().IsValid())
851 if (m_gdb_comm.GetProcessArchitecture().IsValid())
853 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
857 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
861 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
865 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
866 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
873 log->Printf("failed to connect to debugserver: %s", error.AsCString());
878 // Set our user ID to an invalid process ID.
879 SetID(LLDB_INVALID_PROCESS_ID);
880 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
881 exe_module->GetFileSpec().GetFilename().AsCString(),
882 exe_module->GetArchitecture().GetArchitectureName());
890 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
893 // Only connect if we have a valid connect URL
895 if (connect_url && connect_url[0])
897 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
900 const uint32_t max_retry_count = 50;
901 uint32_t retry_count = 0;
902 while (!m_gdb_comm.IsConnected())
904 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
906 m_gdb_comm.SetConnection (conn_ap.release());
909 else if (error.WasInterrupted())
911 // If we were interrupted, don't keep retrying.
917 if (retry_count >= max_retry_count)
925 if (!m_gdb_comm.IsConnected())
928 error.SetErrorString("not connected to remote gdb server");
932 // We always seem to be able to open a connection to a local port
933 // so we need to make sure we can then send data to it. If we can't
934 // then we aren't actually connected to anything, so try and do the
935 // handshake with the remote GDB server and make sure that goes
937 if (!m_gdb_comm.HandshakeWithServer (&error))
939 m_gdb_comm.Disconnect();
941 error.SetErrorString("not connected to remote gdb server");
944 m_gdb_comm.GetThreadSuffixSupported ();
945 m_gdb_comm.GetListThreadsInStopReplySupported ();
946 m_gdb_comm.GetHostInfo ();
947 m_gdb_comm.GetVContSupported ('c');
948 m_gdb_comm.GetVAttachOrWaitSupported();
950 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
951 for (size_t idx = 0; idx < num_cmds; idx++)
953 StringExtractorGDBRemote response;
954 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
960 ProcessGDBRemote::DidLaunchOrAttach ()
962 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
964 log->Printf ("ProcessGDBRemote::DidLaunch()");
965 if (GetID() != LLDB_INVALID_PROCESS_ID)
967 BuildDynamicRegisterInfo (false);
969 // See if the GDB server supports the qHostInfo information
971 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
973 // See if the GDB server supports the qProcessInfo packet, if so
974 // prefer that over the Host information as it will be more specific
977 if (m_gdb_comm.GetProcessArchitecture().IsValid())
978 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
980 if (gdb_remote_arch.IsValid())
982 ArchSpec &target_arch = GetTarget().GetArchitecture();
984 if (target_arch.IsValid())
986 // If the remote host is ARM and we have apple as the vendor, then
987 // ARM executables and shared libraries can have mixed ARM architectures.
988 // You can have an armv6 executable, and if the host is armv7, then the
989 // system will load the best possible architecture for all shared libraries
990 // it has, so we really need to take the remote host architecture as our
991 // defacto architecture in this case.
993 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
994 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
996 target_arch = gdb_remote_arch;
1000 // Fill in what is missing in the triple
1001 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
1002 llvm::Triple &target_triple = target_arch.GetTriple();
1003 if (target_triple.getVendorName().size() == 0)
1005 target_triple.setVendor (remote_triple.getVendor());
1007 if (target_triple.getOSName().size() == 0)
1009 target_triple.setOS (remote_triple.getOS());
1011 if (target_triple.getEnvironmentName().size() == 0)
1012 target_triple.setEnvironment (remote_triple.getEnvironment());
1019 // The target doesn't have a valid architecture yet, set it from
1020 // the architecture we got from the remote GDB server
1021 target_arch = gdb_remote_arch;
1028 ProcessGDBRemote::DidLaunch ()
1030 DidLaunchOrAttach ();
1034 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
1036 ProcessAttachInfo attach_info;
1037 return DoAttachToProcessWithID(attach_pid, attach_info);
1041 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1044 // Clear out and clean up from any current state
1046 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1048 // Make sure we aren't already connected?
1049 if (!m_gdb_comm.IsConnected())
1051 error = LaunchAndConnectToDebugserver (attach_info);
1055 const char *error_string = error.AsCString();
1056 if (error_string == NULL)
1057 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1059 SetExitStatus (-1, error_string);
1063 if (error.Success())
1066 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1068 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1075 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1078 // Clear out and clean up from any current state
1081 if (process_name && process_name[0])
1083 // Make sure we aren't already connected?
1084 if (!m_gdb_comm.IsConnected())
1086 error = LaunchAndConnectToDebugserver (attach_info);
1090 const char *error_string = error.AsCString();
1091 if (error_string == NULL)
1092 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1094 SetExitStatus (-1, error_string);
1098 if (error.Success())
1100 StreamString packet;
1102 if (attach_info.GetWaitForLaunch())
1104 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1106 packet.PutCString ("vAttachWait");
1110 if (attach_info.GetIgnoreExisting())
1111 packet.PutCString("vAttachWait");
1113 packet.PutCString ("vAttachOrWait");
1117 packet.PutCString("vAttachName");
1118 packet.PutChar(';');
1119 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1121 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1130 ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1132 m_gdb_comm.Disconnect();
1133 return Process::SetExitStatus (exit_status, cstr);
1137 ProcessGDBRemote::DidAttach ()
1139 DidLaunchOrAttach ();
1144 ProcessGDBRemote::WillResume ()
1146 m_continue_c_tids.clear();
1147 m_continue_C_tids.clear();
1148 m_continue_s_tids.clear();
1149 m_continue_S_tids.clear();
1154 ProcessGDBRemote::DoResume ()
1157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1159 log->Printf ("ProcessGDBRemote::Resume()");
1161 Listener listener ("gdb-remote.resume-packet-sent");
1162 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1164 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1166 const size_t num_threads = GetThreadList().GetSize();
1168 StreamString continue_packet;
1169 bool continue_packet_error = false;
1170 if (m_gdb_comm.HasAnyVContSupport ())
1172 if (m_continue_c_tids.size() == num_threads ||
1173 (m_continue_c_tids.empty() &&
1174 m_continue_C_tids.empty() &&
1175 m_continue_s_tids.empty() &&
1176 m_continue_S_tids.empty()))
1178 // All threads are continuing, just send a "c" packet
1179 continue_packet.PutCString ("c");
1183 continue_packet.PutCString ("vCont");
1185 if (!m_continue_c_tids.empty())
1187 if (m_gdb_comm.GetVContSupported ('c'))
1189 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)
1190 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1193 continue_packet_error = true;
1196 if (!continue_packet_error && !m_continue_C_tids.empty())
1198 if (m_gdb_comm.GetVContSupported ('C'))
1200 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)
1201 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1204 continue_packet_error = true;
1207 if (!continue_packet_error && !m_continue_s_tids.empty())
1209 if (m_gdb_comm.GetVContSupported ('s'))
1211 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)
1212 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1215 continue_packet_error = true;
1218 if (!continue_packet_error && !m_continue_S_tids.empty())
1220 if (m_gdb_comm.GetVContSupported ('S'))
1222 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)
1223 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1226 continue_packet_error = true;
1229 if (continue_packet_error)
1230 continue_packet.GetString().clear();
1234 continue_packet_error = true;
1236 if (continue_packet_error)
1238 // Either no vCont support, or we tried to use part of the vCont
1239 // packet that wasn't supported by the remote GDB server.
1240 // We need to try and make a simple packet that can do our continue
1241 const size_t num_continue_c_tids = m_continue_c_tids.size();
1242 const size_t num_continue_C_tids = m_continue_C_tids.size();
1243 const size_t num_continue_s_tids = m_continue_s_tids.size();
1244 const size_t num_continue_S_tids = m_continue_S_tids.size();
1245 if (num_continue_c_tids > 0)
1247 if (num_continue_c_tids == num_threads)
1249 // All threads are resuming...
1250 m_gdb_comm.SetCurrentThreadForRun (-1);
1251 continue_packet.PutChar ('c');
1252 continue_packet_error = false;
1254 else if (num_continue_c_tids == 1 &&
1255 num_continue_C_tids == 0 &&
1256 num_continue_s_tids == 0 &&
1257 num_continue_S_tids == 0 )
1259 // Only one thread is continuing
1260 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1261 continue_packet.PutChar ('c');
1262 continue_packet_error = false;
1266 if (continue_packet_error && num_continue_C_tids > 0)
1268 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1269 num_continue_C_tids > 0 &&
1270 num_continue_s_tids == 0 &&
1271 num_continue_S_tids == 0 )
1273 const int continue_signo = m_continue_C_tids.front().second;
1274 // Only one thread is continuing
1275 if (num_continue_C_tids > 1)
1277 // More that one thread with a signal, yet we don't have
1278 // vCont support and we are being asked to resume each
1279 // thread with a signal, we need to make sure they are
1280 // all the same signal, or we can't issue the continue
1281 // accurately with the current support...
1282 if (num_continue_C_tids > 1)
1284 continue_packet_error = false;
1285 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1287 if (m_continue_C_tids[i].second != continue_signo)
1288 continue_packet_error = true;
1291 if (!continue_packet_error)
1292 m_gdb_comm.SetCurrentThreadForRun (-1);
1296 // Set the continue thread ID
1297 continue_packet_error = false;
1298 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1300 if (!continue_packet_error)
1302 // Add threads continuing with the same signo...
1303 continue_packet.Printf("C%2.2x", continue_signo);
1308 if (continue_packet_error && num_continue_s_tids > 0)
1310 if (num_continue_s_tids == num_threads)
1312 // All threads are resuming...
1313 m_gdb_comm.SetCurrentThreadForRun (-1);
1314 continue_packet.PutChar ('s');
1315 continue_packet_error = false;
1317 else if (num_continue_c_tids == 0 &&
1318 num_continue_C_tids == 0 &&
1319 num_continue_s_tids == 1 &&
1320 num_continue_S_tids == 0 )
1322 // Only one thread is stepping
1323 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1324 continue_packet.PutChar ('s');
1325 continue_packet_error = false;
1329 if (!continue_packet_error && num_continue_S_tids > 0)
1331 if (num_continue_S_tids == num_threads)
1333 const int step_signo = m_continue_S_tids.front().second;
1334 // Are all threads trying to step with the same signal?
1335 continue_packet_error = false;
1336 if (num_continue_S_tids > 1)
1338 for (size_t i=1; i<num_threads; ++i)
1340 if (m_continue_S_tids[i].second != step_signo)
1341 continue_packet_error = true;
1344 if (!continue_packet_error)
1346 // Add threads stepping with the same signo...
1347 m_gdb_comm.SetCurrentThreadForRun (-1);
1348 continue_packet.Printf("S%2.2x", step_signo);
1351 else if (num_continue_c_tids == 0 &&
1352 num_continue_C_tids == 0 &&
1353 num_continue_s_tids == 0 &&
1354 num_continue_S_tids == 1 )
1356 // Only one thread is stepping with signal
1357 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1358 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1359 continue_packet_error = false;
1364 if (continue_packet_error)
1366 error.SetErrorString ("can't make continue packet for this resume");
1372 timeout = TimeValue::Now();
1373 timeout.OffsetWithSeconds (5);
1374 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1376 error.SetErrorString ("Trying to resume but the async thread is dead.");
1378 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1382 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1384 if (listener.WaitForEvent (&timeout, event_sp) == false)
1386 error.SetErrorString("Resume timed out.");
1388 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1390 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1392 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1394 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1404 ProcessGDBRemote::ClearThreadIDList ()
1406 Mutex::Locker locker(m_thread_list_real.GetMutex());
1407 m_thread_ids.clear();
1411 ProcessGDBRemote::UpdateThreadIDList ()
1413 Mutex::Locker locker(m_thread_list_real.GetMutex());
1414 bool sequence_mutex_unavailable = false;
1415 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1416 if (sequence_mutex_unavailable)
1418 return false; // We just didn't get the list
1424 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1426 // locker will keep a mutex locked until it goes out of scope
1427 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1428 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1429 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1431 size_t num_thread_ids = m_thread_ids.size();
1432 // The "m_thread_ids" thread ID list should always be updated after each stop
1433 // reply packet, but in case it isn't, update it here.
1434 if (num_thread_ids == 0)
1436 if (!UpdateThreadIDList ())
1438 num_thread_ids = m_thread_ids.size();
1441 ThreadList old_thread_list_copy(old_thread_list);
1442 if (num_thread_ids > 0)
1444 for (size_t i=0; i<num_thread_ids; ++i)
1446 tid_t tid = m_thread_ids[i];
1447 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1450 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1451 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1453 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1456 thread_sp->GetID());
1460 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1462 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1465 thread_sp->GetID());
1467 new_thread_list.AddThread(thread_sp);
1471 // Whatever that is left in old_thread_list_copy are not
1472 // present in new_thread_list. Remove non-existent threads from internal id table.
1473 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1474 for (size_t i=0; i<old_num_thread_ids; i++)
1476 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1479 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1480 m_thread_id_to_index_id_map.erase(old_thread_id);
1489 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1491 stop_packet.SetFilePos (0);
1492 const char stop_type = stop_packet.GetChar();
1498 // This is a bit of a hack, but is is required. If we did exec, we
1499 // need to clear our thread lists and also know to rebuild our dynamic
1500 // register info before we lookup and threads and populate the expedited
1501 // register values so we need to know this right away so we can cleanup
1502 // and update our registers.
1503 const uint32_t stop_id = GetStopID();
1506 // Our first stop, make sure we have a process ID, and also make
1507 // sure we know about our registers
1508 if (GetID() == LLDB_INVALID_PROCESS_ID)
1510 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1511 if (pid != LLDB_INVALID_PROCESS_ID)
1514 BuildDynamicRegisterInfo (true);
1516 // Stop with signal and thread info
1517 const uint8_t signo = stop_packet.GetHexU8();
1520 std::string thread_name;
1522 std::string description;
1523 uint32_t exc_type = 0;
1524 std::vector<addr_t> exc_data;
1525 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1527 ThreadGDBRemote *gdb_thread = NULL;
1529 while (stop_packet.GetNameColonValue(name, value))
1531 if (name.compare("metype") == 0)
1533 // exception type in big endian hex
1534 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1536 else if (name.compare("medata") == 0)
1538 // exception data in big endian hex
1539 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1541 else if (name.compare("thread") == 0)
1543 // thread in big endian hex
1544 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1545 // m_thread_list_real does have its own mutex, but we need to
1546 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1547 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1548 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1549 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1553 // Create the thread if we need to
1554 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1555 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1556 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1557 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1560 thread_sp->GetID());
1562 m_thread_list_real.AddThread(thread_sp);
1564 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1567 else if (name.compare("threads") == 0)
1569 Mutex::Locker locker(m_thread_list_real.GetMutex());
1570 m_thread_ids.clear();
1571 // A comma separated list of all threads in the current
1572 // process that includes the thread for this stop reply
1576 while ((comma_pos = value.find(',')) != std::string::npos)
1578 value[comma_pos] = '\0';
1579 // thread in big endian hex
1580 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1581 if (tid != LLDB_INVALID_THREAD_ID)
1582 m_thread_ids.push_back (tid);
1583 value.erase(0, comma_pos + 1);
1586 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1587 if (tid != LLDB_INVALID_THREAD_ID)
1588 m_thread_ids.push_back (tid);
1590 else if (name.compare("hexname") == 0)
1592 StringExtractor name_extractor;
1593 // Swap "value" over into "name_extractor"
1594 name_extractor.GetStringRef().swap(value);
1595 // Now convert the HEX bytes into a string value
1596 name_extractor.GetHexByteString (value);
1597 thread_name.swap (value);
1599 else if (name.compare("name") == 0)
1601 thread_name.swap (value);
1603 else if (name.compare("qaddr") == 0)
1605 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1607 else if (name.compare("reason") == 0)
1611 else if (name.compare("description") == 0)
1613 StringExtractor desc_extractor;
1614 // Swap "value" over into "name_extractor"
1615 desc_extractor.GetStringRef().swap(value);
1616 // Now convert the HEX bytes into a string value
1617 desc_extractor.GetHexByteString (thread_name);
1619 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1621 // We have a register number that contains an expedited
1622 // register value. Lets supply this register to our thread
1623 // so it won't have to go and read it.
1626 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1628 if (reg != UINT32_MAX)
1630 StringExtractor reg_value_extractor;
1631 // Swap "value" over into "reg_value_extractor"
1632 reg_value_extractor.GetStringRef().swap(value);
1633 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1635 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1639 reg_value_extractor.GetStringRef().c_str(),
1640 stop_packet.GetStringRef().c_str());
1647 // If the response is old style 'S' packet which does not provide us with thread information
1648 // then update the thread list and choose the first one.
1651 UpdateThreadIDList ();
1653 if (!m_thread_ids.empty ())
1655 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1656 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1658 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1664 // Clear the stop info just in case we don't set it to anything
1665 thread_sp->SetStopInfo (StopInfoSP());
1667 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1668 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1671 const size_t exc_data_size = exc_data.size();
1673 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1676 exc_data_size >= 1 ? exc_data[0] : 0,
1677 exc_data_size >= 2 ? exc_data[1] : 0,
1678 exc_data_size >= 3 ? exc_data[2] : 0));
1682 bool handled = false;
1683 bool did_exec = false;
1684 if (!reason.empty())
1686 if (reason.compare("trace") == 0)
1688 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1691 else if (reason.compare("breakpoint") == 0)
1693 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1694 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1697 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1698 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1699 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1701 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1703 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1707 StopInfoSP invalid_stop_info_sp;
1708 thread_sp->SetStopInfo (invalid_stop_info_sp);
1713 else if (reason.compare("trap") == 0)
1715 // Let the trap just use the standard signal stop reason below...
1717 else if (reason.compare("watchpoint") == 0)
1719 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1720 // TODO: locate the watchpoint somehow...
1721 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1724 else if (reason.compare("exception") == 0)
1726 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1729 else if (reason.compare("exec") == 0)
1732 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1737 if (!handled && signo && did_exec == false)
1739 if (signo == SIGTRAP)
1741 // Currently we are going to assume SIGTRAP means we are either
1742 // hitting a breakpoint or hardware single stepping.
1744 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1745 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1749 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1750 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1751 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1752 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1754 if(m_breakpoint_pc_offset != 0)
1755 thread_sp->GetRegisterContext()->SetPC(pc);
1756 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1760 StopInfoSP invalid_stop_info_sp;
1761 thread_sp->SetStopInfo (invalid_stop_info_sp);
1766 // If we were stepping then assume the stop was the result of the trace. If we were
1767 // not stepping then report the SIGTRAP.
1768 // FIXME: We are still missing the case where we single step over a trap instruction.
1769 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1770 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1772 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1776 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1779 if (!description.empty())
1781 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1784 stop_info_sp->SetDescription (description.c_str());
1788 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1793 return eStateStopped;
1799 return eStateExited;
1804 return eStateInvalid;
1808 ProcessGDBRemote::RefreshStateAfterStop ()
1810 Mutex::Locker locker(m_thread_list_real.GetMutex());
1811 m_thread_ids.clear();
1812 // Set the thread stop info. It might have a "threads" key whose value is
1813 // a list of all thread IDs in the current process, so m_thread_ids might
1815 SetThreadStopInfo (m_last_stop_packet);
1816 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1817 if (m_thread_ids.empty())
1819 // No, we need to fetch the thread list manually
1820 UpdateThreadIDList();
1823 // Let all threads recover from stopping and do any clean up based
1824 // on the previous thread state (if any).
1825 m_thread_list_real.RefreshStateAfterStop();
1830 ProcessGDBRemote::DoHalt (bool &caused_stop)
1834 bool timed_out = false;
1835 Mutex::Locker locker;
1837 if (m_public_state.GetValue() == eStateAttaching)
1839 // We are being asked to halt during an attach. We need to just close
1840 // our file handle and debugserver will go away, and we can be done...
1841 m_gdb_comm.Disconnect();
1845 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1848 error.SetErrorString("timed out sending interrupt packet");
1850 error.SetErrorString("unknown error sending interrupt packet");
1853 caused_stop = m_gdb_comm.GetInterruptWasSent ();
1859 ProcessGDBRemote::DoDetach(bool keep_stopped)
1862 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1864 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1866 DisableAllBreakpointSites ();
1868 m_thread_list.DiscardThreadPlans();
1870 error = m_gdb_comm.Detach (keep_stopped);
1873 if (error.Success())
1874 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1876 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
1879 if (!error.Success())
1882 // Sleep for one second to let the process get all detached...
1885 SetPrivateState (eStateDetached);
1886 ResumePrivateStateThread();
1888 //KillDebugserverProcess ();
1894 ProcessGDBRemote::DoDestroy ()
1897 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1899 log->Printf ("ProcessGDBRemote::DoDestroy()");
1901 #if 0 // XXX Currently no iOS target support on FreeBSD
1902 // There is a bug in older iOS debugservers where they don't shut down the process
1903 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1904 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1905 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1906 // destroy it again.
1908 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1909 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1910 // the debugservers with this bug are equal. There really should be a better way to test this!
1912 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1913 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1914 // just do the straight-forward kill.
1916 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1917 // necessary (or helpful) to do any of this.
1919 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1921 PlatformSP platform_sp = GetTarget().GetPlatform();
1923 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1925 && platform_sp->GetName()
1926 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
1928 if (m_destroy_tried_resuming)
1931 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1935 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1936 // but we really need it to happen here and it doesn't matter if we do it twice.
1937 m_thread_list.DiscardThreadPlans();
1938 DisableAllBreakpointSites();
1940 bool stop_looks_like_crash = false;
1941 ThreadList &threads = GetThreadList();
1944 Mutex::Locker locker(threads.GetMutex());
1946 size_t num_threads = threads.GetSize();
1947 for (size_t i = 0; i < num_threads; i++)
1949 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1950 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1951 StopReason reason = eStopReasonInvalid;
1953 reason = stop_info_sp->GetStopReason();
1954 if (reason == eStopReasonBreakpoint
1955 || reason == eStopReasonException)
1958 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1959 thread_sp->GetProtocolID(),
1960 stop_info_sp->GetDescription());
1961 stop_looks_like_crash = true;
1967 if (stop_looks_like_crash)
1970 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1971 m_destroy_tried_resuming = true;
1973 // If we are going to run again before killing, it would be good to suspend all the threads
1974 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1975 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1976 // have to run the risk of letting those threads proceed a bit.
1979 Mutex::Locker locker(threads.GetMutex());
1981 size_t num_threads = threads.GetSize();
1982 for (size_t i = 0; i < num_threads; i++)
1984 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1985 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1986 StopReason reason = eStopReasonInvalid;
1988 reason = stop_info_sp->GetStopReason();
1989 if (reason != eStopReasonBreakpoint
1990 && reason != eStopReasonException)
1993 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1994 thread_sp->GetProtocolID());
1995 thread_sp->SetResumeState(eStateSuspended);
2007 // Interrupt if our inferior is running...
2008 int exit_status = SIGABRT;
2009 std::string exit_string;
2011 if (m_gdb_comm.IsConnected())
2013 if (m_public_state.GetValue() != eStateAttaching)
2016 StringExtractorGDBRemote response;
2017 bool send_async = true;
2018 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2020 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2022 char packet_cmd = response.GetChar(0);
2024 if (packet_cmd == 'W' || packet_cmd == 'X')
2026 #if defined(__APPLE__)
2027 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2028 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2029 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2030 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2031 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2032 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2033 // Anyway, so call waitpid here to finally reap it.
2034 PlatformSP platform_sp(GetTarget().GetPlatform());
2035 if (platform_sp && platform_sp->IsHost())
2039 reap_pid = waitpid (GetID(), &status, WNOHANG);
2041 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2044 SetLastStopPacket (response);
2045 ClearThreadIDList ();
2046 exit_status = response.GetHexU8();
2051 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2052 exit_string.assign("got unexpected response to k packet: ");
2053 exit_string.append(response.GetStringRef());
2059 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2060 exit_string.assign("failed to send the k packet");
2063 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
2068 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2069 exit_string.assign ("killed or interrupted while attaching.");
2074 // If we missed setting the exit status on the way out, do it here.
2075 // NB set exit status can be called multiple times, the first one sets the status.
2076 exit_string.assign("destroying when not connected to debugserver");
2079 SetExitStatus(exit_status, exit_string.c_str());
2082 KillDebugserverProcess ();
2087 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2089 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2090 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2093 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2095 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2097 m_thread_list_real.Clear();
2098 m_thread_list.Clear();
2099 BuildDynamicRegisterInfo (true);
2100 m_gdb_comm.ResetDiscoverableSettings();
2102 m_last_stop_packet = response;
2106 //------------------------------------------------------------------
2108 //------------------------------------------------------------------
2111 ProcessGDBRemote::IsAlive ()
2113 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2117 ProcessGDBRemote::GetImageInfoAddress()
2119 return m_gdb_comm.GetShlibInfoAddr();
2122 //------------------------------------------------------------------
2124 //------------------------------------------------------------------
2126 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2128 if (size > m_max_memory_size)
2130 // Keep memory read sizes down to a sane limit. This function will be
2131 // called multiple times in order to complete the task by
2132 // lldb_private::Process so it is ok to do this.
2133 size = m_max_memory_size;
2137 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2138 assert (packet_len + 1 < (int)sizeof(packet));
2139 StringExtractorGDBRemote response;
2140 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2142 if (response.IsNormalResponse())
2145 return response.GetHexBytes(buf, size, '\xdd');
2147 else if (response.IsErrorResponse())
2148 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2149 else if (response.IsUnsupportedResponse())
2150 error.SetErrorStringWithFormat("GDB server does not support reading memory");
2152 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2156 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2162 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2164 if (size > m_max_memory_size)
2166 // Keep memory read sizes down to a sane limit. This function will be
2167 // called multiple times in order to complete the task by
2168 // lldb_private::Process so it is ok to do this.
2169 size = m_max_memory_size;
2172 StreamString packet;
2173 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2174 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2175 StringExtractorGDBRemote response;
2176 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2178 if (response.IsOKResponse())
2183 else if (response.IsErrorResponse())
2184 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2185 else if (response.IsUnsupportedResponse())
2186 error.SetErrorStringWithFormat("GDB server does not support writing memory");
2188 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2192 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2198 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2200 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2202 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2205 case eLazyBoolCalculate:
2207 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2208 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2209 return allocated_addr;
2212 // Call mmap() to create memory in the inferior..
2214 if (permissions & lldb::ePermissionsReadable)
2215 prot |= eMmapProtRead;
2216 if (permissions & lldb::ePermissionsWritable)
2217 prot |= eMmapProtWrite;
2218 if (permissions & lldb::ePermissionsExecutable)
2219 prot |= eMmapProtExec;
2221 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2222 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2223 m_addr_to_mmap_size[allocated_addr] = size;
2225 allocated_addr = LLDB_INVALID_ADDRESS;
2229 if (allocated_addr == LLDB_INVALID_ADDRESS)
2230 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2233 return allocated_addr;
2237 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2238 MemoryRegionInfo ®ion_info)
2241 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2246 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2249 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2254 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2256 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2261 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2264 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2268 case eLazyBoolCalculate:
2269 // We should never be deallocating memory without allocating memory
2270 // first so we should never get eLazyBoolCalculate
2271 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2275 if (!m_gdb_comm.DeallocateMemory (addr))
2276 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2280 // Call munmap() to deallocate memory in the inferior..
2282 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2283 if (pos != m_addr_to_mmap_size.end() &&
2284 InferiorCallMunmap(this, addr, pos->second))
2285 m_addr_to_mmap_size.erase (pos);
2287 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2296 //------------------------------------------------------------------
2298 //------------------------------------------------------------------
2300 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2302 if (m_stdio_communication.IsConnected())
2304 ConnectionStatus status;
2305 m_stdio_communication.Write(src, src_len, status, NULL);
2311 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2314 assert(bp_site != NULL);
2317 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2318 user_id_t site_id = bp_site->GetID();
2320 // Get the breakpoint address
2321 const addr_t addr = bp_site->GetLoadAddress();
2323 // Log that a breakpoint was requested
2325 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2327 // Breakpoint already exists and is enabled
2328 if (bp_site->IsEnabled())
2331 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2335 // Get the software breakpoint trap opcode size
2336 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2338 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2339 // is supported by the remote stub. These are set to true by default, and later set to false
2340 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2341 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2342 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2343 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2344 // skip over software breakpoints.
2345 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2347 // Try to send off a software breakpoint packet ($Z0)
2348 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2350 // The breakpoint was placed successfully
2351 bp_site->SetEnabled(true);
2352 bp_site->SetType(BreakpointSite::eExternal);
2356 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2357 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2358 // or if we have learned that this breakpoint type is unsupported. To do this, we
2359 // must test the support boolean for this breakpoint type to see if it now indicates that
2360 // this breakpoint type is unsupported. If they are still supported then we should return
2361 // with the error code. If they are now unsupported, then we would like to fall through
2362 // and try another form of breakpoint.
2363 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2366 // We reach here when software breakpoints have been found to be unsupported. For future
2367 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2368 // known not to be supported.
2370 log->Printf("Software breakpoints are unsupported");
2372 // So we will fall through and try a hardware breakpoint
2375 // The process of setting a hardware breakpoint is much the same as above. We check the
2376 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2377 // will try to set this breakpoint with a hardware breakpoint.
2378 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2380 // Try to send off a hardware breakpoint packet ($Z1)
2381 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2383 // The breakpoint was placed successfully
2384 bp_site->SetEnabled(true);
2385 bp_site->SetType(BreakpointSite::eHardware);
2389 // Check if the error was something other then an unsupported breakpoint type
2390 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2392 // Unable to set this hardware breakpoint
2393 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2397 // We will reach here when the stub gives an unsported response to a hardware breakpoint
2399 log->Printf("Hardware breakpoints are unsupported");
2401 // Finally we will falling through to a #trap style breakpoint
2404 // Don't fall through when hardware breakpoints were specifically requested
2405 if (bp_site->HardwareRequired())
2407 error.SetErrorString("hardware breakpoints are not supported");
2411 // As a last resort we want to place a manual breakpoint. An instruction
2412 // is placed into the process memory using memory write packets.
2413 return EnableSoftwareBreakpoint(bp_site);
2417 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2420 assert (bp_site != NULL);
2421 addr_t addr = bp_site->GetLoadAddress();
2422 user_id_t site_id = bp_site->GetID();
2423 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2425 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2427 if (bp_site->IsEnabled())
2429 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2431 BreakpointSite::Type bp_type = bp_site->GetType();
2434 case BreakpointSite::eSoftware:
2435 error = DisableSoftwareBreakpoint (bp_site);
2438 case BreakpointSite::eHardware:
2439 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
2440 error.SetErrorToGenericError();
2443 case BreakpointSite::eExternal:
2444 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2445 error.SetErrorToGenericError();
2448 if (error.Success())
2449 bp_site->SetEnabled(false);
2454 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2458 if (error.Success())
2459 error.SetErrorToGenericError();
2463 // Pre-requisite: wp != NULL.
2464 static GDBStoppointType
2465 GetGDBStoppointType (Watchpoint *wp)
2468 bool watch_read = wp->WatchpointRead();
2469 bool watch_write = wp->WatchpointWrite();
2471 // watch_read and watch_write cannot both be false.
2472 assert(watch_read || watch_write);
2473 if (watch_read && watch_write)
2474 return eWatchpointReadWrite;
2475 else if (watch_read)
2476 return eWatchpointRead;
2477 else // Must be watch_write, then.
2478 return eWatchpointWrite;
2482 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2487 user_id_t watchID = wp->GetID();
2488 addr_t addr = wp->GetLoadAddress();
2489 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2491 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2492 if (wp->IsEnabled())
2495 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2499 GDBStoppointType type = GetGDBStoppointType(wp);
2500 // Pass down an appropriate z/Z packet...
2501 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2503 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2505 wp->SetEnabled(true, notify);
2509 error.SetErrorString("sending gdb watchpoint packet failed");
2512 error.SetErrorString("watchpoints not supported");
2516 error.SetErrorString("Watchpoint argument was NULL.");
2518 if (error.Success())
2519 error.SetErrorToGenericError();
2524 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2529 user_id_t watchID = wp->GetID();
2531 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2533 addr_t addr = wp->GetLoadAddress();
2536 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2538 if (!wp->IsEnabled())
2541 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2542 // See also 'class WatchpointSentry' within StopInfo.cpp.
2543 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2544 // the watchpoint object to intelligently process this action.
2545 wp->SetEnabled(false, notify);
2549 if (wp->IsHardware())
2551 GDBStoppointType type = GetGDBStoppointType(wp);
2552 // Pass down an appropriate z/Z packet...
2553 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2555 wp->SetEnabled(false, notify);
2559 error.SetErrorString("sending gdb watchpoint packet failed");
2561 // TODO: clear software watchpoints if we implement them
2565 error.SetErrorString("Watchpoint argument was NULL.");
2567 if (error.Success())
2568 error.SetErrorToGenericError();
2573 ProcessGDBRemote::Clear()
2576 m_thread_list_real.Clear();
2577 m_thread_list.Clear();
2581 ProcessGDBRemote::DoSignal (int signo)
2584 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2586 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2588 if (!m_gdb_comm.SendAsyncSignal (signo))
2589 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2594 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
2597 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2599 // If we locate debugserver, keep that located version around
2600 static FileSpec g_debugserver_file_spec;
2602 ProcessLaunchInfo debugserver_launch_info;
2603 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2604 debugserver_launch_info.SetUserID(process_info.GetUserID());
2606 #if defined (__APPLE__) && defined (__arm__)
2607 // On iOS, still do a local connection using a random port
2608 const char *hostname = "localhost";
2609 uint16_t port = get_random_port ();
2611 // Set hostname being NULL to do the reverse connect where debugserver
2612 // will bind to port zero and it will communicate back to us the port
2613 // that we will connect to
2614 const char *hostname = NULL;
2618 error = m_gdb_comm.StartDebugserverProcess (hostname,
2620 debugserver_launch_info,
2623 if (error.Success ())
2624 m_debugserver_pid = debugserver_launch_info.GetProcessID();
2626 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2628 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2629 StartAsyncThread ();
2633 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2636 log->Printf("failed to start debugserver process: %s", error.AsCString());
2640 if (m_gdb_comm.IsConnected())
2642 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2643 ConnectToDebugserver (NULL);
2647 StreamString connect_url;
2648 connect_url.Printf("connect://%s:%u", hostname, port);
2649 error = ConnectToDebugserver (connect_url.GetString().c_str());
2657 ProcessGDBRemote::MonitorDebugserverProcess
2659 void *callback_baton,
2660 lldb::pid_t debugserver_pid,
2661 bool exited, // True if the process did exit
2662 int signo, // Zero for no signal
2663 int exit_status // Exit value of process if signal is zero
2666 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2667 // and might not exist anymore, so we need to carefully try to get the
2668 // target for this process first since we have a race condition when
2669 // we are done running between getting the notice that the inferior
2670 // process has died and the debugserver that was debugging this process.
2671 // In our test suite, we are also continually running process after
2672 // process, so we must be very careful to make sure:
2673 // 1 - process object hasn't been deleted already
2674 // 2 - that a new process object hasn't been recreated in its place
2676 // "debugserver_pid" argument passed in is the process ID for
2677 // debugserver that we are tracking...
2678 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2680 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2682 // Get a shared pointer to the target that has a matching process pointer.
2683 // This target could be gone, or the target could already have a new process
2684 // object inside of it
2685 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2688 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2692 // We found a process in a target that matches, but another thread
2693 // might be in the process of launching a new process that will
2694 // soon replace it, so get a shared pointer to the process so we
2695 // can keep it alive.
2696 ProcessSP process_sp (target_sp->GetProcessSP());
2697 // Now we have a shared pointer to the process that can't go away on us
2698 // so we now make sure it was the same as the one passed in, and also make
2699 // sure that our previous "process *" didn't get deleted and have a new
2700 // "process *" created in its place with the same pointer. To verify this
2701 // we make sure the process has our debugserver process ID. If we pass all
2702 // of these tests, then we are sure that this process is the one we were
2704 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2706 // Sleep for a half a second to make sure our inferior process has
2707 // time to set its exit status before we set it incorrectly when
2708 // both the debugserver and the inferior process shut down.
2710 // If our process hasn't yet exited, debugserver might have died.
2711 // If the process did exit, the we are reaping it.
2712 const StateType state = process->GetState();
2714 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2715 state != eStateInvalid &&
2716 state != eStateUnloaded &&
2717 state != eStateExited &&
2718 state != eStateDetached)
2720 char error_str[1024];
2723 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2725 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2727 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2731 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2734 process->SetExitStatus (-1, error_str);
2736 // Debugserver has exited we need to let our ProcessGDBRemote
2737 // know that it no longer has a debugserver instance
2738 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2745 ProcessGDBRemote::KillDebugserverProcess ()
2747 m_gdb_comm.Disconnect();
2748 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2750 Host::Kill (m_debugserver_pid, SIGINT);
2751 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2756 ProcessGDBRemote::Initialize()
2758 static bool g_initialized = false;
2760 if (g_initialized == false)
2762 g_initialized = true;
2763 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2764 GetPluginDescriptionStatic(),
2766 DebuggerInitialize);
2768 Log::Callbacks log_callbacks = {
2769 ProcessGDBRemoteLog::DisableLog,
2770 ProcessGDBRemoteLog::EnableLog,
2771 ProcessGDBRemoteLog::ListLogCategories
2774 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2779 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2781 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2783 const bool is_global_setting = true;
2784 PluginManager::CreateSettingForProcessPlugin (debugger,
2785 GetGlobalPluginProperties()->GetValueProperties(),
2786 ConstString ("Properties for the gdb-remote process plug-in."),
2792 ProcessGDBRemote::StartAsyncThread ()
2794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2797 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2799 Mutex::Locker start_locker(m_async_thread_state_mutex);
2800 if (m_async_thread_state == eAsyncThreadNotStarted)
2802 // Create a thread that watches our internal state and controls which
2803 // events make it to clients (into the DCProcess event queue).
2804 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2805 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2807 m_async_thread_state = eAsyncThreadRunning;
2815 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2816 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2818 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2819 if (m_async_thread_state == eAsyncThreadRunning)
2827 ProcessGDBRemote::StopAsyncThread ()
2829 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2832 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2834 Mutex::Locker start_locker(m_async_thread_state_mutex);
2835 if (m_async_thread_state == eAsyncThreadRunning)
2837 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2839 // This will shut down the async thread.
2840 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2842 // Stop the stdio thread
2843 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2845 Host::ThreadJoin (m_async_thread, NULL, NULL);
2847 m_async_thread_state = eAsyncThreadDone;
2852 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2858 ProcessGDBRemote::AsyncThread (void *arg)
2860 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2862 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2864 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
2866 Listener listener ("ProcessGDBRemote::AsyncThread");
2868 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2869 eBroadcastBitAsyncThreadShouldExit;
2871 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2873 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2880 if (listener.WaitForEvent (NULL, event_sp))
2882 const uint32_t event_type = event_sp->GetType();
2883 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
2886 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2890 case eBroadcastBitAsyncContinue:
2892 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2894 if (continue_packet)
2896 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2897 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2899 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2901 if (::strstr (continue_cstr, "vAttach") == NULL)
2902 process->SetPrivateState(eStateRunning);
2903 StringExtractorGDBRemote response;
2904 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2906 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2907 // The thread ID list might be contained within the "response", or the stop reply packet that
2908 // caused the stop. So clear it now before we give the stop reply packet to the process
2909 // using the process->SetLastStopPacket()...
2910 process->ClearThreadIDList ();
2916 case eStateSuspended:
2917 process->SetLastStopPacket (response);
2918 process->SetPrivateState (stop_state);
2922 process->SetLastStopPacket (response);
2923 process->ClearThreadIDList();
2924 response.SetFilePos(1);
2925 process->SetExitStatus(response.GetHexU8(), NULL);
2930 process->SetExitStatus(-1, "lost connection");
2934 process->SetPrivateState (stop_state);
2941 case eBroadcastBitAsyncThreadShouldExit:
2943 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2949 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2954 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2956 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2958 process->SetExitStatus (-1, "lost connection");
2966 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2973 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
2975 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2980 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2982 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2983 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2984 // if (m_local_debugserver)
2986 // return Host::ListProcessesMatchingName (name, matches, pids);
2990 // // FIXME: Implement talking to the remote debugserver.
2997 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2998 lldb_private::StoppointCallbackContext *context,
2999 lldb::user_id_t break_id,
3000 lldb::user_id_t break_loc_id)
3002 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3003 // run so I can stop it if that's what I want to do.
3004 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3006 log->Printf("Hit New Thread Notification breakpoint.");
3012 ProcessGDBRemote::StartNoticingNewThreads()
3014 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3015 if (m_thread_create_bp_sp)
3017 if (log && log->GetVerbose())
3018 log->Printf("Enabled noticing new thread breakpoint.");
3019 m_thread_create_bp_sp->SetEnabled(true);
3023 PlatformSP platform_sp (m_target.GetPlatform());
3026 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3027 if (m_thread_create_bp_sp)
3029 if (log && log->GetVerbose())
3030 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3031 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3036 log->Printf("Failed to create new thread notification breakpoint.");
3040 return m_thread_create_bp_sp.get() != NULL;
3044 ProcessGDBRemote::StopNoticingNewThreads()
3046 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3047 if (log && log->GetVerbose())
3048 log->Printf ("Disabling new thread notification breakpoint.");
3050 if (m_thread_create_bp_sp)
3051 m_thread_create_bp_sp->SetEnabled(false);
3056 lldb_private::DynamicLoader *
3057 ProcessGDBRemote::GetDynamicLoader ()
3059 if (m_dyld_ap.get() == NULL)
3060 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3061 return m_dyld_ap.get();
3065 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3070 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3071 CommandObjectParsed (interpreter,
3072 "process plugin packet history",
3073 "Dumps the packet history buffer. ",
3078 ~CommandObjectProcessGDBRemotePacketHistory ()
3083 DoExecute (Args& command, CommandReturnObject &result)
3085 const size_t argc = command.GetArgumentCount();
3088 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3091 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3092 result.SetStatus (eReturnStatusSuccessFinishResult);
3098 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3100 result.SetStatus (eReturnStatusFailed);
3105 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3110 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3111 CommandObjectParsed (interpreter,
3112 "process plugin packet send",
3113 "Send a custom packet through the GDB remote protocol and print the answer. "
3114 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3119 ~CommandObjectProcessGDBRemotePacketSend ()
3124 DoExecute (Args& command, CommandReturnObject &result)
3126 const size_t argc = command.GetArgumentCount();
3129 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3130 result.SetStatus (eReturnStatusFailed);
3134 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3137 for (size_t i=0; i<argc; ++ i)
3139 const char *packet_cstr = command.GetArgumentAtIndex(0);
3140 bool send_async = true;
3141 StringExtractorGDBRemote response;
3142 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3143 result.SetStatus (eReturnStatusSuccessFinishResult);
3144 Stream &output_strm = result.GetOutputStream();
3145 output_strm.Printf (" packet: %s\n", packet_cstr);
3146 std::string &response_str = response.GetStringRef();
3148 if (strstr(packet_cstr, "qGetProfileData") != NULL)
3150 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3153 if (response_str.empty())
3154 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3156 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3163 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3168 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3169 CommandObjectRaw (interpreter,
3170 "process plugin packet monitor",
3171 "Send a qRcmd packet through the GDB remote protocol and print the response."
3172 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3177 ~CommandObjectProcessGDBRemotePacketMonitor ()
3182 DoExecute (const char *command, CommandReturnObject &result)
3184 if (command == NULL || command[0] == '\0')
3186 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3187 result.SetStatus (eReturnStatusFailed);
3191 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3194 StreamString packet;
3195 packet.PutCString("qRcmd,");
3196 packet.PutBytesAsRawHex8(command, strlen(command));
3197 const char *packet_cstr = packet.GetString().c_str();
3199 bool send_async = true;
3200 StringExtractorGDBRemote response;
3201 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3202 result.SetStatus (eReturnStatusSuccessFinishResult);
3203 Stream &output_strm = result.GetOutputStream();
3204 output_strm.Printf (" packet: %s\n", packet_cstr);
3205 const std::string &response_str = response.GetStringRef();
3207 if (response_str.empty())
3208 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3210 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3216 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3221 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3222 CommandObjectMultiword (interpreter,
3223 "process plugin packet",
3224 "Commands that deal with GDB remote packets.",
3227 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3228 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3229 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3232 ~CommandObjectProcessGDBRemotePacket ()
3237 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3240 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3241 CommandObjectMultiword (interpreter,
3243 "A set of commands for operating on a ProcessGDBRemote process.",
3244 "process plugin <subcommand> [<subcommand-options>]")
3246 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3249 ~CommandObjectMultiwordProcessGDBRemote ()
3255 ProcessGDBRemote::GetPluginCommandObject()
3258 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3259 return m_command_sp.get();