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
17 #include <netinet/in.h>
18 #include <sys/mman.h> // for mmap
21 #include <sys/types.h>
28 // Other libraries and framework includes
30 #include "lldb/Breakpoint/Watchpoint.h"
31 #include "lldb/Interpreter/Args.h"
32 #include "lldb/Core/ArchSpec.h"
33 #include "lldb/Core/Debugger.h"
34 #include "lldb/Host/ConnectionFileDescriptor.h"
35 #include "lldb/Host/FileSpec.h"
36 #include "lldb/Core/Module.h"
37 #include "lldb/Core/ModuleSpec.h"
38 #include "lldb/Core/PluginManager.h"
39 #include "lldb/Core/State.h"
40 #include "lldb/Core/StreamFile.h"
41 #include "lldb/Core/StreamString.h"
42 #include "lldb/Core/Timer.h"
43 #include "lldb/Core/Value.h"
44 #include "lldb/Host/HostThread.h"
45 #include "lldb/Host/Symbols.h"
46 #include "lldb/Host/ThreadLauncher.h"
47 #include "lldb/Host/TimeValue.h"
48 #include "lldb/Interpreter/CommandInterpreter.h"
49 #include "lldb/Interpreter/CommandObject.h"
50 #include "lldb/Interpreter/CommandObjectMultiword.h"
51 #include "lldb/Interpreter/CommandReturnObject.h"
52 #ifndef LLDB_DISABLE_PYTHON
53 #include "lldb/Interpreter/PythonDataObjects.h"
55 #include "lldb/Symbol/ObjectFile.h"
56 #include "lldb/Target/DynamicLoader.h"
57 #include "lldb/Target/Target.h"
58 #include "lldb/Target/TargetList.h"
59 #include "lldb/Target/ThreadPlanCallFunction.h"
60 #include "lldb/Target/SystemRuntime.h"
61 #include "lldb/Utility/PseudoTerminal.h"
64 #include "lldb/Host/Host.h"
65 #include "Plugins/Process/Utility/FreeBSDSignals.h"
66 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
67 #include "Plugins/Process/Utility/LinuxSignals.h"
68 #include "Plugins/Process/Utility/StopInfoMachException.h"
69 #include "Utility/StringExtractorGDBRemote.h"
70 #include "GDBRemoteRegisterContext.h"
71 #include "ProcessGDBRemote.h"
72 #include "ProcessGDBRemoteLog.h"
73 #include "ThreadGDBRemote.h"
78 // Provide a function that can easily dump the packet history if we know a
79 // ProcessGDBRemote * value (which we can get from logs or from debugging).
80 // We need the function in the lldb namespace so it makes it into the final
81 // executable since the LLDB shared library only exports stuff in the lldb
82 // namespace. This allows you to attach with a debugger and call this
83 // function and get the packet history dumped to a file.
85 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
87 lldb_private::StreamFile strm;
88 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
90 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
94 #define DEBUGSERVER_BASENAME "debugserver"
96 using namespace lldb_private;
101 static PropertyDefinition
104 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
105 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
106 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111 ePropertyPacketTimeout,
112 ePropertyTargetDefinitionFile
115 class PluginProperties : public Properties
122 return ProcessGDBRemote::GetPluginNameStatic();
128 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
129 m_collection_sp->Initialize(g_properties);
140 const uint32_t idx = ePropertyPacketTimeout;
141 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
145 SetPacketTimeout(uint64_t timeout)
147 const uint32_t idx = ePropertyPacketTimeout;
148 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
152 GetTargetDefinitionFile () const
154 const uint32_t idx = ePropertyTargetDefinitionFile;
155 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
159 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
161 static const ProcessKDPPropertiesSP &
162 GetGlobalPluginProperties()
164 static ProcessKDPPropertiesSP g_settings_sp;
166 g_settings_sp.reset (new PluginProperties ());
167 return g_settings_sp;
170 } // anonymous namespace end
172 // TODO Randomly assigning a port is unsafe. We should get an unused
173 // ephemeral port from the kernel and make sure we reserve it before passing
174 // it to debugserver.
176 #if defined (__APPLE__)
177 #define LOW_PORT (IPPORT_RESERVED)
178 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
180 #define LOW_PORT (1024u)
181 #define HIGH_PORT (49151u)
184 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
185 static bool rand_initialized = false;
187 static inline uint16_t
190 if (!rand_initialized)
192 time_t seed = time(NULL);
194 rand_initialized = true;
197 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
201 lldb_private::ConstString
202 ProcessGDBRemote::GetPluginNameStatic()
204 static ConstString g_name("gdb-remote");
209 ProcessGDBRemote::GetPluginDescriptionStatic()
211 return "GDB Remote protocol based debugging plug-in.";
215 ProcessGDBRemote::Terminate()
217 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
222 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
224 lldb::ProcessSP process_sp;
225 if (crash_file_path == NULL)
226 process_sp.reset (new ProcessGDBRemote (target, listener));
231 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
233 if (plugin_specified_by_name)
236 // For now we are just making sure the file exists for a given module
237 Module *exe_module = target.GetExecutableModulePointer();
240 ObjectFile *exe_objfile = exe_module->GetObjectFile();
241 // We can't debug core files...
242 switch (exe_objfile->GetType())
244 case ObjectFile::eTypeInvalid:
245 case ObjectFile::eTypeCoreFile:
246 case ObjectFile::eTypeDebugInfo:
247 case ObjectFile::eTypeObjectFile:
248 case ObjectFile::eTypeSharedLibrary:
249 case ObjectFile::eTypeStubLibrary:
250 case ObjectFile::eTypeJIT:
252 case ObjectFile::eTypeExecutable:
253 case ObjectFile::eTypeDynamicLinker:
254 case ObjectFile::eTypeUnknown:
257 return exe_module->GetFileSpec().Exists();
259 // However, if there is no executable module, we return true since we might be preparing to attach.
263 //----------------------------------------------------------------------
264 // ProcessGDBRemote constructor
265 //----------------------------------------------------------------------
266 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
267 Process (target, listener),
270 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
271 m_last_stop_packet (),
272 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
274 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
275 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
277 m_continue_c_tids (),
278 m_continue_C_tids (),
279 m_continue_s_tids (),
280 m_continue_S_tids (),
281 m_max_memory_size (0),
282 m_remote_stub_max_memory_size (0),
283 m_addr_to_mmap_size (),
284 m_thread_create_bp_sp (),
285 m_waiting_for_attach (false),
286 m_destroy_tried_resuming (false),
288 m_breakpoint_pc_offset (0)
290 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
291 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
292 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
293 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
294 if (timeout_seconds > 0)
295 m_gdb_comm.SetPacketTimeout(timeout_seconds);
298 //----------------------------------------------------------------------
300 //----------------------------------------------------------------------
301 ProcessGDBRemote::~ProcessGDBRemote()
303 // m_mach_process.UnregisterNotificationCallbacks (this);
305 // We need to call finalize on the process before destroying ourselves
306 // to make sure all of the broadcaster cleanup goes as planned. If we
307 // destruct this class, then Process::~Process() might have problems
308 // trying to fully destroy the broadcaster.
311 // The general Finalize is going to try to destroy the process and that SHOULD
312 // shut down the async thread. However, if we don't kill it it will get stranded and
313 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
315 KillDebugserverProcess();
318 //----------------------------------------------------------------------
320 //----------------------------------------------------------------------
322 ProcessGDBRemote::GetPluginName()
324 return GetPluginNameStatic();
328 ProcessGDBRemote::GetPluginVersion()
334 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
336 #ifndef LLDB_DISABLE_PYTHON
337 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
339 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
340 if (module_object_sp)
342 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
344 "gdb-server-target-definition",
347 PythonDictionary target_dict(target_definition_sp);
351 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
354 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
356 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
358 GetTarget().SetArchitecture(host_arch);
362 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
364 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
376 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
378 if (!force && m_register_info.GetNumRegisters() > 0)
382 m_register_info.Clear();
383 uint32_t reg_offset = 0;
384 uint32_t reg_num = 0;
385 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
386 response_type == StringExtractorGDBRemote::eResponse;
389 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
390 assert (packet_len < (int)sizeof(packet));
391 StringExtractorGDBRemote response;
392 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
394 response_type = response.GetResponseType();
395 if (response_type == StringExtractorGDBRemote::eResponse)
399 ConstString reg_name;
400 ConstString alt_name;
401 ConstString set_name;
402 std::vector<uint32_t> value_regs;
403 std::vector<uint32_t> invalidate_regs;
404 RegisterInfo reg_info = { NULL, // Name
407 reg_offset, // offset
408 eEncodingUint, // encoding
409 eFormatHex, // formate
411 LLDB_INVALID_REGNUM, // GCC reg num
412 LLDB_INVALID_REGNUM, // DWARF reg num
413 LLDB_INVALID_REGNUM, // generic reg num
414 reg_num, // GDB reg num
415 reg_num // native register number
421 while (response.GetNameColonValue(name, value))
423 if (name.compare("name") == 0)
425 reg_name.SetCString(value.c_str());
427 else if (name.compare("alt-name") == 0)
429 alt_name.SetCString(value.c_str());
431 else if (name.compare("bitsize") == 0)
433 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
435 else if (name.compare("offset") == 0)
437 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
438 if (reg_offset != offset)
443 else if (name.compare("encoding") == 0)
445 const Encoding encoding = Args::StringToEncoding (value.c_str());
446 if (encoding != eEncodingInvalid)
447 reg_info.encoding = encoding;
449 else if (name.compare("format") == 0)
451 Format format = eFormatInvalid;
452 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
453 reg_info.format = format;
454 else if (value.compare("binary") == 0)
455 reg_info.format = eFormatBinary;
456 else if (value.compare("decimal") == 0)
457 reg_info.format = eFormatDecimal;
458 else if (value.compare("hex") == 0)
459 reg_info.format = eFormatHex;
460 else if (value.compare("float") == 0)
461 reg_info.format = eFormatFloat;
462 else if (value.compare("vector-sint8") == 0)
463 reg_info.format = eFormatVectorOfSInt8;
464 else if (value.compare("vector-uint8") == 0)
465 reg_info.format = eFormatVectorOfUInt8;
466 else if (value.compare("vector-sint16") == 0)
467 reg_info.format = eFormatVectorOfSInt16;
468 else if (value.compare("vector-uint16") == 0)
469 reg_info.format = eFormatVectorOfUInt16;
470 else if (value.compare("vector-sint32") == 0)
471 reg_info.format = eFormatVectorOfSInt32;
472 else if (value.compare("vector-uint32") == 0)
473 reg_info.format = eFormatVectorOfUInt32;
474 else if (value.compare("vector-float32") == 0)
475 reg_info.format = eFormatVectorOfFloat32;
476 else if (value.compare("vector-uint128") == 0)
477 reg_info.format = eFormatVectorOfUInt128;
479 else if (name.compare("set") == 0)
481 set_name.SetCString(value.c_str());
483 else if (name.compare("gcc") == 0)
485 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
487 else if (name.compare("dwarf") == 0)
489 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
491 else if (name.compare("generic") == 0)
493 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
495 else if (name.compare("container-regs") == 0)
497 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
498 value_pair.second = value;
501 value_pair = value_pair.second.split(',');
502 if (!value_pair.first.empty())
504 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
505 if (reg != LLDB_INVALID_REGNUM)
506 value_regs.push_back (reg);
508 } while (!value_pair.second.empty());
510 else if (name.compare("invalidate-regs") == 0)
512 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
513 value_pair.second = value;
516 value_pair = value_pair.second.split(',');
517 if (!value_pair.first.empty())
519 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
520 if (reg != LLDB_INVALID_REGNUM)
521 invalidate_regs.push_back (reg);
523 } while (!value_pair.second.empty());
527 reg_info.byte_offset = reg_offset;
528 assert (reg_info.byte_size != 0);
529 reg_offset += reg_info.byte_size;
530 if (!value_regs.empty())
532 value_regs.push_back(LLDB_INVALID_REGNUM);
533 reg_info.value_regs = value_regs.data();
535 if (!invalidate_regs.empty())
537 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
538 reg_info.invalidate_regs = invalidate_regs.data();
541 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
545 break; // ensure exit before reg_num is incremented
554 // Check if qHostInfo specified a specific packet timeout for this connection.
555 // If so then lets update our setting so the user knows what the timeout is
557 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
558 if (host_packet_timeout)
560 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
566 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
568 if (target_definition_fspec)
570 // See if we can get register definitions from a python file
571 if (ParsePythonTargetDefinition (target_definition_fspec))
576 // We didn't get anything if the accumulated reg_num is zero. See if we are
577 // debugging ARM and fill with a hard coded register set until we can get an
578 // updated debugserver down on the devices.
579 // On the other hand, if the accumulated reg_num is positive, see if we can
580 // add composite registers to the existing primordial ones.
581 bool from_scratch = (reg_num == 0);
583 const ArchSpec &target_arch = GetTarget().GetArchitecture();
584 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
585 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
587 // Use the process' architecture instead of the host arch, if available
588 ArchSpec remote_arch;
589 if (remote_process_arch.IsValid ())
590 remote_arch = remote_process_arch;
592 remote_arch = remote_host_arch;
594 if (!target_arch.IsValid())
596 if (remote_arch.IsValid()
597 && remote_arch.GetMachine() == llvm::Triple::arm
598 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
599 m_register_info.HardcodeARMRegisters(from_scratch);
601 else if (target_arch.GetMachine() == llvm::Triple::arm)
603 m_register_info.HardcodeARMRegisters(from_scratch);
606 // At this point, we can finalize our register info.
607 m_register_info.Finalize ();
611 ProcessGDBRemote::WillLaunch (Module* module)
613 return WillLaunchOrAttach ();
617 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
619 return WillLaunchOrAttach ();
623 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
625 return WillLaunchOrAttach ();
629 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
631 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
632 Error error (WillLaunchOrAttach ());
637 error = ConnectToDebugserver (remote_url);
643 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
644 if (pid == LLDB_INVALID_PROCESS_ID)
646 // We don't have a valid process ID, so note that we are connected
647 // and could now request to launch or attach, or get remote process
649 SetPrivateState (eStateConnected);
653 // We have a valid process
656 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
658 if (!m_target.GetArchitecture().IsValid())
660 if (m_gdb_comm.GetProcessArchitecture().IsValid())
662 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
666 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
670 const StateType state = SetThreadStopInfo (m_last_stop_packet);
671 if (state == eStateStopped)
673 SetPrivateState (state);
676 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
679 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
683 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s (GetTarget().GetArchitecture().IsValid() %s, m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str (), GetTarget ().GetArchitecture ().IsValid () ? "true" : "false", m_gdb_comm.GetHostArchitecture ().IsValid () ? "true" : "false");
687 && !GetTarget().GetArchitecture().IsValid()
688 && m_gdb_comm.GetHostArchitecture().IsValid())
690 // Prefer the *process'* architecture over that of the *host*, if available.
691 if (m_gdb_comm.GetProcessArchitecture().IsValid())
692 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
694 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
698 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
700 // Set the Unix signals properly for the target.
701 // FIXME Add a gdb-remote packet to discover dynamically.
702 if (error.Success ())
704 const ArchSpec arch_spec = GetTarget ().GetArchitecture ();
705 if (arch_spec.IsValid ())
708 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": determining unix signals type based on architecture %s, triple %s", __FUNCTION__, GetID (), arch_spec.GetArchitectureName () ? arch_spec.GetArchitectureName () : "<null>", arch_spec.GetTriple ().getTriple ().c_str ());
710 switch (arch_spec.GetTriple ().getOS ())
712 case llvm::Triple::Linux:
713 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
715 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
717 case llvm::Triple::OpenBSD:
718 case llvm::Triple::FreeBSD:
719 case llvm::Triple::NetBSD:
720 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
722 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
725 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
727 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
737 ProcessGDBRemote::WillLaunchOrAttach ()
740 m_stdio_communication.Clear ();
744 //----------------------------------------------------------------------
746 //----------------------------------------------------------------------
748 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
750 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
754 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
756 uint32_t launch_flags = launch_info.GetFlags().Get();
757 const char *stdin_path = NULL;
758 const char *stdout_path = NULL;
759 const char *stderr_path = NULL;
760 const char *working_dir = launch_info.GetWorkingDirectory();
762 const FileAction *file_action;
763 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
766 if (file_action->GetAction() == FileAction::eFileActionOpen)
767 stdin_path = file_action->GetPath();
769 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
772 if (file_action->GetAction() == FileAction::eFileActionOpen)
773 stdout_path = file_action->GetPath();
775 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
778 if (file_action->GetAction() == FileAction::eFileActionOpen)
779 stderr_path = file_action->GetPath();
784 if (stdin_path || stdout_path || stderr_path)
785 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stdout=%s",
787 stdin_path ? stdin_path : "<null>",
788 stdout_path ? stdout_path : "<null>",
789 stderr_path ? stderr_path : "<null>");
791 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
794 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
795 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
796 // ::LogSetLogFile ("/dev/stdout");
798 ObjectFile * object_file = exe_module->GetObjectFile();
801 // Make sure we aren't already connected?
802 if (!m_gdb_comm.IsConnected())
804 error = LaunchAndConnectToDebugserver (launch_info);
809 lldb_utility::PseudoTerminal pty;
810 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
812 // If the debugserver is local and we aren't disabling STDIO, lets use
813 // a pseudo terminal to instead of relying on the 'O' packets for stdio
814 // since 'O' packets can really slow down debugging if the inferior
815 // does a lot of output.
816 PlatformSP platform_sp (m_target.GetPlatform());
817 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
819 const char *slave_name = NULL;
820 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
822 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
823 slave_name = pty.GetSlaveName (NULL, 0);
825 if (stdin_path == NULL)
826 stdin_path = slave_name;
828 if (stdout_path == NULL)
829 stdout_path = slave_name;
831 if (stderr_path == NULL)
832 stderr_path = slave_name;
835 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stdout=%s",
837 stdin_path ? stdin_path : "<null>",
838 stdout_path ? stdout_path : "<null>",
839 stderr_path ? stderr_path : "<null>");
842 // Set STDIN to /dev/null if we want STDIO disabled or if either
843 // STDOUT or STDERR have been set to something and STDIN hasn't
844 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
845 stdin_path = "/dev/null";
847 // Set STDOUT to /dev/null if we want STDIO disabled or if either
848 // STDIN or STDERR have been set to something and STDOUT hasn't
849 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
850 stdout_path = "/dev/null";
852 // Set STDERR to /dev/null if we want STDIO disabled or if either
853 // STDIN or STDOUT have been set to something and STDERR hasn't
854 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
855 stderr_path = "/dev/null";
858 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stdout=%s",
860 stdin_path ? stdin_path : "<null>",
861 stdout_path ? stdout_path : "<null>",
862 stderr_path ? stderr_path : "<null>");
865 m_gdb_comm.SetSTDIN (stdin_path);
867 m_gdb_comm.SetSTDOUT (stdout_path);
869 m_gdb_comm.SetSTDERR (stderr_path);
871 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
872 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
874 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
876 const char * launch_event_data = launch_info.GetLaunchEventData();
877 if (launch_event_data != NULL && *launch_event_data != '\0')
878 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
880 if (working_dir && working_dir[0])
882 m_gdb_comm.SetWorkingDir (working_dir);
885 // Send the environment and the program + arguments after we connect
886 const Args &environment = launch_info.GetEnvironmentEntries();
887 if (environment.GetArgumentCount())
889 size_t num_environment_entries = environment.GetArgumentCount();
890 for (size_t i=0; i<num_environment_entries; ++i)
892 const char *env_entry = environment.GetArgumentAtIndex(i);
893 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
898 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
899 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
900 if (arg_packet_err == 0)
902 std::string error_str;
903 if (m_gdb_comm.GetLaunchSuccess (error_str))
905 SetID (m_gdb_comm.GetCurrentProcessID ());
909 error.SetErrorString (error_str.c_str());
914 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
917 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
919 if (GetID() == LLDB_INVALID_PROCESS_ID)
922 log->Printf("failed to connect to debugserver: %s", error.AsCString());
923 KillDebugserverProcess ();
927 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
929 if (!m_target.GetArchitecture().IsValid())
931 if (m_gdb_comm.GetProcessArchitecture().IsValid())
933 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
937 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
941 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
945 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
946 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
953 log->Printf("failed to connect to debugserver: %s", error.AsCString());
958 // Set our user ID to an invalid process ID.
959 SetID(LLDB_INVALID_PROCESS_ID);
960 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
961 exe_module->GetFileSpec().GetFilename().AsCString(),
962 exe_module->GetArchitecture().GetArchitectureName());
970 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
973 // Only connect if we have a valid connect URL
975 if (connect_url && connect_url[0])
977 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
980 const uint32_t max_retry_count = 50;
981 uint32_t retry_count = 0;
982 while (!m_gdb_comm.IsConnected())
984 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
986 m_gdb_comm.SetConnection (conn_ap.release());
989 else if (error.WasInterrupted())
991 // If we were interrupted, don't keep retrying.
997 if (retry_count >= max_retry_count)
1005 if (!m_gdb_comm.IsConnected())
1007 if (error.Success())
1008 error.SetErrorString("not connected to remote gdb server");
1012 // We always seem to be able to open a connection to a local port
1013 // so we need to make sure we can then send data to it. If we can't
1014 // then we aren't actually connected to anything, so try and do the
1015 // handshake with the remote GDB server and make sure that goes
1017 if (!m_gdb_comm.HandshakeWithServer (&error))
1019 m_gdb_comm.Disconnect();
1020 if (error.Success())
1021 error.SetErrorString("not connected to remote gdb server");
1024 m_gdb_comm.GetThreadSuffixSupported ();
1025 m_gdb_comm.GetListThreadsInStopReplySupported ();
1026 m_gdb_comm.GetHostInfo ();
1027 m_gdb_comm.GetVContSupported ('c');
1028 m_gdb_comm.GetVAttachOrWaitSupported();
1030 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1031 for (size_t idx = 0; idx < num_cmds; idx++)
1033 StringExtractorGDBRemote response;
1034 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1040 ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
1042 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1044 log->Printf ("ProcessGDBRemote::DidLaunch()");
1045 if (GetID() != LLDB_INVALID_PROCESS_ID)
1047 BuildDynamicRegisterInfo (false);
1049 // See if the GDB server supports the qHostInfo information
1052 // See if the GDB server supports the qProcessInfo packet, if so
1053 // prefer that over the Host information as it will be more specific
1056 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1057 if (remote_process_arch.IsValid())
1059 process_arch = remote_process_arch;
1061 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1063 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1064 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1068 process_arch = m_gdb_comm.GetHostArchitecture();
1070 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1072 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1073 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1076 if (process_arch.IsValid())
1078 ArchSpec &target_arch = GetTarget().GetArchitecture();
1079 if (target_arch.IsValid())
1082 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1084 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1085 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1087 // If the remote host is ARM and we have apple as the vendor, then
1088 // ARM executables and shared libraries can have mixed ARM architectures.
1089 // You can have an armv6 executable, and if the host is armv7, then the
1090 // system will load the best possible architecture for all shared libraries
1091 // it has, so we really need to take the remote host architecture as our
1092 // defacto architecture in this case.
1094 if (process_arch.GetMachine() == llvm::Triple::arm &&
1095 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1097 GetTarget().SetArchitecture (process_arch);
1099 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1101 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1102 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1106 // Fill in what is missing in the triple
1107 const llvm::Triple &remote_triple = process_arch.GetTriple();
1108 llvm::Triple &target_triple = target_arch.GetTriple();
1109 if (target_triple.getVendorName().size() == 0)
1111 target_triple.setVendor (remote_triple.getVendor());
1113 if (target_triple.getOSName().size() == 0)
1115 target_triple.setOS (remote_triple.getOS());
1117 if (target_triple.getEnvironmentName().size() == 0)
1118 target_triple.setEnvironment (remote_triple.getEnvironment());
1125 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1127 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1128 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1132 // The target doesn't have a valid architecture yet, set it from
1133 // the architecture we got from the remote GDB server
1134 GetTarget().SetArchitecture (process_arch);
1141 ProcessGDBRemote::DidLaunch ()
1143 ArchSpec process_arch;
1144 DidLaunchOrAttach (process_arch);
1148 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
1150 ProcessAttachInfo attach_info;
1151 return DoAttachToProcessWithID(attach_pid, attach_info);
1155 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1161 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1163 // Clear out and clean up from any current state
1165 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1167 // Make sure we aren't already connected?
1168 if (!m_gdb_comm.IsConnected())
1170 error = LaunchAndConnectToDebugserver (attach_info);
1174 const char *error_string = error.AsCString();
1175 if (error_string == NULL)
1176 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1178 SetExitStatus (-1, error_string);
1182 if (error.Success())
1184 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1187 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1189 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1197 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1200 // Clear out and clean up from any current state
1203 if (process_name && process_name[0])
1205 // Make sure we aren't already connected?
1206 if (!m_gdb_comm.IsConnected())
1208 error = LaunchAndConnectToDebugserver (attach_info);
1212 const char *error_string = error.AsCString();
1213 if (error_string == NULL)
1214 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1216 SetExitStatus (-1, error_string);
1220 if (error.Success())
1222 StreamString packet;
1224 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1226 if (attach_info.GetWaitForLaunch())
1228 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1230 packet.PutCString ("vAttachWait");
1234 if (attach_info.GetIgnoreExisting())
1235 packet.PutCString("vAttachWait");
1237 packet.PutCString ("vAttachOrWait");
1241 packet.PutCString("vAttachName");
1242 packet.PutChar(';');
1243 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1245 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1254 ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1256 m_gdb_comm.Disconnect();
1257 return Process::SetExitStatus (exit_status, cstr);
1261 ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
1263 // If you can figure out what the architecture is, fill it in here.
1264 process_arch.Clear();
1265 DidLaunchOrAttach (process_arch);
1270 ProcessGDBRemote::WillResume ()
1272 m_continue_c_tids.clear();
1273 m_continue_C_tids.clear();
1274 m_continue_s_tids.clear();
1275 m_continue_S_tids.clear();
1280 ProcessGDBRemote::DoResume ()
1283 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1285 log->Printf ("ProcessGDBRemote::Resume()");
1287 Listener listener ("gdb-remote.resume-packet-sent");
1288 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1290 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1292 const size_t num_threads = GetThreadList().GetSize();
1294 StreamString continue_packet;
1295 bool continue_packet_error = false;
1296 if (m_gdb_comm.HasAnyVContSupport ())
1298 if (m_continue_c_tids.size() == num_threads ||
1299 (m_continue_c_tids.empty() &&
1300 m_continue_C_tids.empty() &&
1301 m_continue_s_tids.empty() &&
1302 m_continue_S_tids.empty()))
1304 // All threads are continuing, just send a "c" packet
1305 continue_packet.PutCString ("c");
1309 continue_packet.PutCString ("vCont");
1311 if (!m_continue_c_tids.empty())
1313 if (m_gdb_comm.GetVContSupported ('c'))
1315 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)
1316 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1319 continue_packet_error = true;
1322 if (!continue_packet_error && !m_continue_C_tids.empty())
1324 if (m_gdb_comm.GetVContSupported ('C'))
1326 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)
1327 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1330 continue_packet_error = true;
1333 if (!continue_packet_error && !m_continue_s_tids.empty())
1335 if (m_gdb_comm.GetVContSupported ('s'))
1337 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)
1338 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1341 continue_packet_error = true;
1344 if (!continue_packet_error && !m_continue_S_tids.empty())
1346 if (m_gdb_comm.GetVContSupported ('S'))
1348 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)
1349 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1352 continue_packet_error = true;
1355 if (continue_packet_error)
1356 continue_packet.GetString().clear();
1360 continue_packet_error = true;
1362 if (continue_packet_error)
1364 // Either no vCont support, or we tried to use part of the vCont
1365 // packet that wasn't supported by the remote GDB server.
1366 // We need to try and make a simple packet that can do our continue
1367 const size_t num_continue_c_tids = m_continue_c_tids.size();
1368 const size_t num_continue_C_tids = m_continue_C_tids.size();
1369 const size_t num_continue_s_tids = m_continue_s_tids.size();
1370 const size_t num_continue_S_tids = m_continue_S_tids.size();
1371 if (num_continue_c_tids > 0)
1373 if (num_continue_c_tids == num_threads)
1375 // All threads are resuming...
1376 m_gdb_comm.SetCurrentThreadForRun (-1);
1377 continue_packet.PutChar ('c');
1378 continue_packet_error = false;
1380 else if (num_continue_c_tids == 1 &&
1381 num_continue_C_tids == 0 &&
1382 num_continue_s_tids == 0 &&
1383 num_continue_S_tids == 0 )
1385 // Only one thread is continuing
1386 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1387 continue_packet.PutChar ('c');
1388 continue_packet_error = false;
1392 if (continue_packet_error && num_continue_C_tids > 0)
1394 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1395 num_continue_C_tids > 0 &&
1396 num_continue_s_tids == 0 &&
1397 num_continue_S_tids == 0 )
1399 const int continue_signo = m_continue_C_tids.front().second;
1400 // Only one thread is continuing
1401 if (num_continue_C_tids > 1)
1403 // More that one thread with a signal, yet we don't have
1404 // vCont support and we are being asked to resume each
1405 // thread with a signal, we need to make sure they are
1406 // all the same signal, or we can't issue the continue
1407 // accurately with the current support...
1408 if (num_continue_C_tids > 1)
1410 continue_packet_error = false;
1411 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1413 if (m_continue_C_tids[i].second != continue_signo)
1414 continue_packet_error = true;
1417 if (!continue_packet_error)
1418 m_gdb_comm.SetCurrentThreadForRun (-1);
1422 // Set the continue thread ID
1423 continue_packet_error = false;
1424 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1426 if (!continue_packet_error)
1428 // Add threads continuing with the same signo...
1429 continue_packet.Printf("C%2.2x", continue_signo);
1434 if (continue_packet_error && num_continue_s_tids > 0)
1436 if (num_continue_s_tids == num_threads)
1438 // All threads are resuming...
1439 m_gdb_comm.SetCurrentThreadForRun (-1);
1440 continue_packet.PutChar ('s');
1441 continue_packet_error = false;
1443 else if (num_continue_c_tids == 0 &&
1444 num_continue_C_tids == 0 &&
1445 num_continue_s_tids == 1 &&
1446 num_continue_S_tids == 0 )
1448 // Only one thread is stepping
1449 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1450 continue_packet.PutChar ('s');
1451 continue_packet_error = false;
1455 if (!continue_packet_error && num_continue_S_tids > 0)
1457 if (num_continue_S_tids == num_threads)
1459 const int step_signo = m_continue_S_tids.front().second;
1460 // Are all threads trying to step with the same signal?
1461 continue_packet_error = false;
1462 if (num_continue_S_tids > 1)
1464 for (size_t i=1; i<num_threads; ++i)
1466 if (m_continue_S_tids[i].second != step_signo)
1467 continue_packet_error = true;
1470 if (!continue_packet_error)
1472 // Add threads stepping with the same signo...
1473 m_gdb_comm.SetCurrentThreadForRun (-1);
1474 continue_packet.Printf("S%2.2x", step_signo);
1477 else if (num_continue_c_tids == 0 &&
1478 num_continue_C_tids == 0 &&
1479 num_continue_s_tids == 0 &&
1480 num_continue_S_tids == 1 )
1482 // Only one thread is stepping with signal
1483 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1484 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1485 continue_packet_error = false;
1490 if (continue_packet_error)
1492 error.SetErrorString ("can't make continue packet for this resume");
1498 timeout = TimeValue::Now();
1499 timeout.OffsetWithSeconds (5);
1500 if (!m_async_thread.IsJoinable())
1502 error.SetErrorString ("Trying to resume but the async thread is dead.");
1504 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1508 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1510 if (listener.WaitForEvent (&timeout, event_sp) == false)
1512 error.SetErrorString("Resume timed out.");
1514 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1516 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1518 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1520 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1530 ProcessGDBRemote::ClearThreadIDList ()
1532 Mutex::Locker locker(m_thread_list_real.GetMutex());
1533 m_thread_ids.clear();
1537 ProcessGDBRemote::UpdateThreadIDList ()
1539 Mutex::Locker locker(m_thread_list_real.GetMutex());
1540 bool sequence_mutex_unavailable = false;
1541 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1542 if (sequence_mutex_unavailable)
1544 return false; // We just didn't get the list
1550 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1552 // locker will keep a mutex locked until it goes out of scope
1553 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1554 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1555 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1557 size_t num_thread_ids = m_thread_ids.size();
1558 // The "m_thread_ids" thread ID list should always be updated after each stop
1559 // reply packet, but in case it isn't, update it here.
1560 if (num_thread_ids == 0)
1562 if (!UpdateThreadIDList ())
1564 num_thread_ids = m_thread_ids.size();
1567 ThreadList old_thread_list_copy(old_thread_list);
1568 if (num_thread_ids > 0)
1570 for (size_t i=0; i<num_thread_ids; ++i)
1572 tid_t tid = m_thread_ids[i];
1573 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1576 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1577 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1579 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1580 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1581 thread_sp->GetID());
1585 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1587 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1588 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1589 thread_sp->GetID());
1591 new_thread_list.AddThread(thread_sp);
1595 // Whatever that is left in old_thread_list_copy are not
1596 // present in new_thread_list. Remove non-existent threads from internal id table.
1597 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1598 for (size_t i=0; i<old_num_thread_ids; i++)
1600 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1603 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1604 m_thread_id_to_index_id_map.erase(old_thread_id);
1613 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1615 stop_packet.SetFilePos (0);
1616 const char stop_type = stop_packet.GetChar();
1622 // This is a bit of a hack, but is is required. If we did exec, we
1623 // need to clear our thread lists and also know to rebuild our dynamic
1624 // register info before we lookup and threads and populate the expedited
1625 // register values so we need to know this right away so we can cleanup
1626 // and update our registers.
1627 const uint32_t stop_id = GetStopID();
1630 // Our first stop, make sure we have a process ID, and also make
1631 // sure we know about our registers
1632 if (GetID() == LLDB_INVALID_PROCESS_ID)
1634 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1635 if (pid != LLDB_INVALID_PROCESS_ID)
1638 BuildDynamicRegisterInfo (true);
1640 // Stop with signal and thread info
1641 const uint8_t signo = stop_packet.GetHexU8();
1644 std::string thread_name;
1646 std::string description;
1647 uint32_t exc_type = 0;
1648 std::vector<addr_t> exc_data;
1649 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1651 ThreadGDBRemote *gdb_thread = NULL;
1653 while (stop_packet.GetNameColonValue(name, value))
1655 if (name.compare("metype") == 0)
1657 // exception type in big endian hex
1658 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1660 else if (name.compare("medata") == 0)
1662 // exception data in big endian hex
1663 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1665 else if (name.compare("thread") == 0)
1667 // thread in big endian hex
1668 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1669 // m_thread_list_real does have its own mutex, but we need to
1670 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1671 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1672 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1673 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1677 // Create the thread if we need to
1678 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1679 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1680 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1681 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1683 static_cast<void*>(thread_sp.get()),
1684 thread_sp->GetID());
1686 m_thread_list_real.AddThread(thread_sp);
1688 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1691 else if (name.compare("threads") == 0)
1693 Mutex::Locker locker(m_thread_list_real.GetMutex());
1694 m_thread_ids.clear();
1695 // A comma separated list of all threads in the current
1696 // process that includes the thread for this stop reply
1700 while ((comma_pos = value.find(',')) != std::string::npos)
1702 value[comma_pos] = '\0';
1703 // thread in big endian hex
1704 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1705 if (tid != LLDB_INVALID_THREAD_ID)
1706 m_thread_ids.push_back (tid);
1707 value.erase(0, comma_pos + 1);
1709 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1710 if (tid != LLDB_INVALID_THREAD_ID)
1711 m_thread_ids.push_back (tid);
1713 else if (name.compare("hexname") == 0)
1715 StringExtractor name_extractor;
1716 // Swap "value" over into "name_extractor"
1717 name_extractor.GetStringRef().swap(value);
1718 // Now convert the HEX bytes into a string value
1719 name_extractor.GetHexByteString (value);
1720 thread_name.swap (value);
1722 else if (name.compare("name") == 0)
1724 thread_name.swap (value);
1726 else if (name.compare("qaddr") == 0)
1728 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1730 else if (name.compare("reason") == 0)
1734 else if (name.compare("description") == 0)
1736 StringExtractor desc_extractor;
1737 // Swap "value" over into "name_extractor"
1738 desc_extractor.GetStringRef().swap(value);
1739 // Now convert the HEX bytes into a string value
1740 desc_extractor.GetHexByteString (thread_name);
1742 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1744 // We have a register number that contains an expedited
1745 // register value. Lets supply this register to our thread
1746 // so it won't have to go and read it.
1749 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1751 if (reg != UINT32_MAX)
1753 StringExtractor reg_value_extractor;
1754 // Swap "value" over into "reg_value_extractor"
1755 reg_value_extractor.GetStringRef().swap(value);
1756 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1758 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1762 reg_value_extractor.GetStringRef().c_str(),
1763 stop_packet.GetStringRef().c_str());
1770 // If the response is old style 'S' packet which does not provide us with thread information
1771 // then update the thread list and choose the first one.
1774 UpdateThreadIDList ();
1776 if (!m_thread_ids.empty ())
1778 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1779 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1781 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1787 // Clear the stop info just in case we don't set it to anything
1788 thread_sp->SetStopInfo (StopInfoSP());
1790 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1791 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1794 const size_t exc_data_size = exc_data.size();
1796 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1799 exc_data_size >= 1 ? exc_data[0] : 0,
1800 exc_data_size >= 2 ? exc_data[1] : 0,
1801 exc_data_size >= 3 ? exc_data[2] : 0));
1805 bool handled = false;
1806 bool did_exec = false;
1807 if (!reason.empty())
1809 if (reason.compare("trace") == 0)
1811 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1814 else if (reason.compare("breakpoint") == 0)
1816 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1817 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1820 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1821 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1822 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1824 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1826 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1830 StopInfoSP invalid_stop_info_sp;
1831 thread_sp->SetStopInfo (invalid_stop_info_sp);
1835 else if (reason.compare("trap") == 0)
1837 // Let the trap just use the standard signal stop reason below...
1839 else if (reason.compare("watchpoint") == 0)
1841 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1842 // TODO: locate the watchpoint somehow...
1843 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1846 else if (reason.compare("exception") == 0)
1848 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1851 else if (reason.compare("exec") == 0)
1854 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1859 if (!handled && signo && did_exec == false)
1861 if (signo == SIGTRAP)
1863 // Currently we are going to assume SIGTRAP means we are either
1864 // hitting a breakpoint or hardware single stepping.
1866 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1867 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1871 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1872 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1873 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1874 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1876 if(m_breakpoint_pc_offset != 0)
1877 thread_sp->GetRegisterContext()->SetPC(pc);
1878 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1882 StopInfoSP invalid_stop_info_sp;
1883 thread_sp->SetStopInfo (invalid_stop_info_sp);
1888 // If we were stepping then assume the stop was the result of the trace. If we were
1889 // not stepping then report the SIGTRAP.
1890 // FIXME: We are still missing the case where we single step over a trap instruction.
1891 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1892 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1894 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1898 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1901 if (!description.empty())
1903 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1906 stop_info_sp->SetDescription (description.c_str());
1910 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1915 return eStateStopped;
1922 return eStateExited;
1927 return eStateInvalid;
1931 ProcessGDBRemote::RefreshStateAfterStop ()
1933 Mutex::Locker locker(m_thread_list_real.GetMutex());
1934 m_thread_ids.clear();
1935 // Set the thread stop info. It might have a "threads" key whose value is
1936 // a list of all thread IDs in the current process, so m_thread_ids might
1938 SetThreadStopInfo (m_last_stop_packet);
1939 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1940 if (m_thread_ids.empty())
1942 // No, we need to fetch the thread list manually
1943 UpdateThreadIDList();
1946 // Let all threads recover from stopping and do any clean up based
1947 // on the previous thread state (if any).
1948 m_thread_list_real.RefreshStateAfterStop();
1953 ProcessGDBRemote::DoHalt (bool &caused_stop)
1957 bool timed_out = false;
1958 Mutex::Locker locker;
1960 if (m_public_state.GetValue() == eStateAttaching)
1962 // We are being asked to halt during an attach. We need to just close
1963 // our file handle and debugserver will go away, and we can be done...
1964 m_gdb_comm.Disconnect();
1968 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1971 error.SetErrorString("timed out sending interrupt packet");
1973 error.SetErrorString("unknown error sending interrupt packet");
1976 caused_stop = m_gdb_comm.GetInterruptWasSent ();
1982 ProcessGDBRemote::DoDetach(bool keep_stopped)
1985 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1987 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1989 error = m_gdb_comm.Detach (keep_stopped);
1992 if (error.Success())
1993 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1995 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
1998 if (!error.Success())
2001 // Sleep for one second to let the process get all detached...
2004 SetPrivateState (eStateDetached);
2005 ResumePrivateStateThread();
2007 //KillDebugserverProcess ();
2013 ProcessGDBRemote::DoDestroy ()
2016 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2018 log->Printf ("ProcessGDBRemote::DoDestroy()");
2020 #if 0 // XXX Currently no iOS target support on FreeBSD
2021 // There is a bug in older iOS debugservers where they don't shut down the process
2022 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2023 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2024 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2025 // destroy it again.
2027 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2028 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2029 // the debugservers with this bug are equal. There really should be a better way to test this!
2031 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2032 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2033 // just do the straight-forward kill.
2035 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2036 // necessary (or helpful) to do any of this.
2038 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2040 PlatformSP platform_sp = GetTarget().GetPlatform();
2042 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2044 && platform_sp->GetName()
2045 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
2047 if (m_destroy_tried_resuming)
2050 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
2054 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2055 // but we really need it to happen here and it doesn't matter if we do it twice.
2056 m_thread_list.DiscardThreadPlans();
2057 DisableAllBreakpointSites();
2059 bool stop_looks_like_crash = false;
2060 ThreadList &threads = GetThreadList();
2063 Mutex::Locker locker(threads.GetMutex());
2065 size_t num_threads = threads.GetSize();
2066 for (size_t i = 0; i < num_threads; i++)
2068 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2069 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2070 StopReason reason = eStopReasonInvalid;
2072 reason = stop_info_sp->GetStopReason();
2073 if (reason == eStopReasonBreakpoint
2074 || reason == eStopReasonException)
2077 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2078 thread_sp->GetProtocolID(),
2079 stop_info_sp->GetDescription());
2080 stop_looks_like_crash = true;
2086 if (stop_looks_like_crash)
2089 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2090 m_destroy_tried_resuming = true;
2092 // If we are going to run again before killing, it would be good to suspend all the threads
2093 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2094 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2095 // have to run the risk of letting those threads proceed a bit.
2098 Mutex::Locker locker(threads.GetMutex());
2100 size_t num_threads = threads.GetSize();
2101 for (size_t i = 0; i < num_threads; i++)
2103 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2104 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2105 StopReason reason = eStopReasonInvalid;
2107 reason = stop_info_sp->GetStopReason();
2108 if (reason != eStopReasonBreakpoint
2109 && reason != eStopReasonException)
2112 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2113 thread_sp->GetProtocolID());
2114 thread_sp->SetResumeState(eStateSuspended);
2126 // Interrupt if our inferior is running...
2127 int exit_status = SIGABRT;
2128 std::string exit_string;
2130 if (m_gdb_comm.IsConnected())
2132 if (m_public_state.GetValue() != eStateAttaching)
2135 StringExtractorGDBRemote response;
2136 bool send_async = true;
2137 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2139 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2141 char packet_cmd = response.GetChar(0);
2143 if (packet_cmd == 'W' || packet_cmd == 'X')
2145 #if defined(__APPLE__)
2146 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2147 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2148 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2149 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2150 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2151 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2152 // Anyway, so call waitpid here to finally reap it.
2153 PlatformSP platform_sp(GetTarget().GetPlatform());
2154 if (platform_sp && platform_sp->IsHost())
2158 reap_pid = waitpid (GetID(), &status, WNOHANG);
2160 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2163 SetLastStopPacket (response);
2164 ClearThreadIDList ();
2165 exit_status = response.GetHexU8();
2170 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2171 exit_string.assign("got unexpected response to k packet: ");
2172 exit_string.append(response.GetStringRef());
2178 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2179 exit_string.assign("failed to send the k packet");
2182 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
2187 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
2188 exit_string.assign ("killed or interrupted while attaching.");
2193 // If we missed setting the exit status on the way out, do it here.
2194 // NB set exit status can be called multiple times, the first one sets the status.
2195 exit_string.assign("destroying when not connected to debugserver");
2198 SetExitStatus(exit_status, exit_string.c_str());
2201 KillDebugserverProcess ();
2206 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2208 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2209 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2212 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2214 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2216 m_thread_list_real.Clear();
2217 m_thread_list.Clear();
2218 BuildDynamicRegisterInfo (true);
2219 m_gdb_comm.ResetDiscoverableSettings();
2221 m_last_stop_packet = response;
2225 //------------------------------------------------------------------
2227 //------------------------------------------------------------------
2230 ProcessGDBRemote::IsAlive ()
2232 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2236 ProcessGDBRemote::GetImageInfoAddress()
2238 return m_gdb_comm.GetShlibInfoAddr();
2241 //------------------------------------------------------------------
2243 //------------------------------------------------------------------
2245 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2247 GetMaxMemorySize ();
2248 if (size > m_max_memory_size)
2250 // Keep memory read sizes down to a sane limit. This function will be
2251 // called multiple times in order to complete the task by
2252 // lldb_private::Process so it is ok to do this.
2253 size = m_max_memory_size;
2258 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2259 if (binary_memory_read)
2261 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2265 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2267 assert (packet_len + 1 < (int)sizeof(packet));
2268 StringExtractorGDBRemote response;
2269 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2271 if (response.IsNormalResponse())
2274 if (binary_memory_read)
2276 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2277 // 0x7d character escaping that was present in the packet
2279 size_t data_received_size = response.GetBytesLeft();
2280 if (data_received_size > size)
2282 // Don't write past the end of BUF if the remote debug server gave us too
2283 // much data for some reason.
2284 data_received_size = size;
2286 memcpy (buf, response.GetStringRef().data(), data_received_size);
2287 return data_received_size;
2291 return response.GetHexBytes(buf, size, '\xdd');
2294 else if (response.IsErrorResponse())
2295 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2296 else if (response.IsUnsupportedResponse())
2297 error.SetErrorStringWithFormat("GDB server does not support reading memory");
2299 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2303 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2309 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2311 GetMaxMemorySize ();
2312 if (size > m_max_memory_size)
2314 // Keep memory read sizes down to a sane limit. This function will be
2315 // called multiple times in order to complete the task by
2316 // lldb_private::Process so it is ok to do this.
2317 size = m_max_memory_size;
2320 StreamString packet;
2321 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2322 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2323 StringExtractorGDBRemote response;
2324 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2326 if (response.IsOKResponse())
2331 else if (response.IsErrorResponse())
2332 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2333 else if (response.IsUnsupportedResponse())
2334 error.SetErrorStringWithFormat("GDB server does not support writing memory");
2336 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2340 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2346 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2348 lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
2349 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2351 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2354 case eLazyBoolCalculate:
2356 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2357 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2358 return allocated_addr;
2361 // Call mmap() to create memory in the inferior..
2363 if (permissions & lldb::ePermissionsReadable)
2364 prot |= eMmapProtRead;
2365 if (permissions & lldb::ePermissionsWritable)
2366 prot |= eMmapProtWrite;
2367 if (permissions & lldb::ePermissionsExecutable)
2368 prot |= eMmapProtExec;
2370 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2371 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2372 m_addr_to_mmap_size[allocated_addr] = size;
2375 allocated_addr = LLDB_INVALID_ADDRESS;
2377 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2382 if (allocated_addr == LLDB_INVALID_ADDRESS)
2383 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2386 return allocated_addr;
2390 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2391 MemoryRegionInfo ®ion_info)
2394 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2399 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2402 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2407 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2409 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2414 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2417 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2421 case eLazyBoolCalculate:
2422 // We should never be deallocating memory without allocating memory
2423 // first so we should never get eLazyBoolCalculate
2424 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2428 if (!m_gdb_comm.DeallocateMemory (addr))
2429 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2433 // Call munmap() to deallocate memory in the inferior..
2435 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2436 if (pos != m_addr_to_mmap_size.end() &&
2437 InferiorCallMunmap(this, addr, pos->second))
2438 m_addr_to_mmap_size.erase (pos);
2440 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2449 //------------------------------------------------------------------
2451 //------------------------------------------------------------------
2453 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2455 if (m_stdio_communication.IsConnected())
2457 ConnectionStatus status;
2458 m_stdio_communication.Write(src, src_len, status, NULL);
2464 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2467 assert(bp_site != NULL);
2470 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2471 user_id_t site_id = bp_site->GetID();
2473 // Get the breakpoint address
2474 const addr_t addr = bp_site->GetLoadAddress();
2476 // Log that a breakpoint was requested
2478 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2480 // Breakpoint already exists and is enabled
2481 if (bp_site->IsEnabled())
2484 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2488 // Get the software breakpoint trap opcode size
2489 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2491 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2492 // is supported by the remote stub. These are set to true by default, and later set to false
2493 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2494 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2495 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2496 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2497 // skip over software breakpoints.
2498 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2500 // Try to send off a software breakpoint packet ($Z0)
2501 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2503 // The breakpoint was placed successfully
2504 bp_site->SetEnabled(true);
2505 bp_site->SetType(BreakpointSite::eExternal);
2509 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2510 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2511 // or if we have learned that this breakpoint type is unsupported. To do this, we
2512 // must test the support boolean for this breakpoint type to see if it now indicates that
2513 // this breakpoint type is unsupported. If they are still supported then we should return
2514 // with the error code. If they are now unsupported, then we would like to fall through
2515 // and try another form of breakpoint.
2516 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2519 // We reach here when software breakpoints have been found to be unsupported. For future
2520 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2521 // known not to be supported.
2523 log->Printf("Software breakpoints are unsupported");
2525 // So we will fall through and try a hardware breakpoint
2528 // The process of setting a hardware breakpoint is much the same as above. We check the
2529 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2530 // will try to set this breakpoint with a hardware breakpoint.
2531 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2533 // Try to send off a hardware breakpoint packet ($Z1)
2534 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2536 // The breakpoint was placed successfully
2537 bp_site->SetEnabled(true);
2538 bp_site->SetType(BreakpointSite::eHardware);
2542 // Check if the error was something other then an unsupported breakpoint type
2543 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2545 // Unable to set this hardware breakpoint
2546 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2550 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
2552 log->Printf("Hardware breakpoints are unsupported");
2554 // Finally we will falling through to a #trap style breakpoint
2557 // Don't fall through when hardware breakpoints were specifically requested
2558 if (bp_site->HardwareRequired())
2560 error.SetErrorString("hardware breakpoints are not supported");
2564 // As a last resort we want to place a manual breakpoint. An instruction
2565 // is placed into the process memory using memory write packets.
2566 return EnableSoftwareBreakpoint(bp_site);
2570 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2573 assert (bp_site != NULL);
2574 addr_t addr = bp_site->GetLoadAddress();
2575 user_id_t site_id = bp_site->GetID();
2576 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2578 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2580 if (bp_site->IsEnabled())
2582 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2584 BreakpointSite::Type bp_type = bp_site->GetType();
2587 case BreakpointSite::eSoftware:
2588 error = DisableSoftwareBreakpoint (bp_site);
2591 case BreakpointSite::eHardware:
2592 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
2593 error.SetErrorToGenericError();
2596 case BreakpointSite::eExternal:
2598 GDBStoppointType stoppoint_type;
2599 if (bp_site->IsHardware())
2600 stoppoint_type = eBreakpointHardware;
2602 stoppoint_type = eBreakpointSoftware;
2604 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
2605 error.SetErrorToGenericError();
2609 if (error.Success())
2610 bp_site->SetEnabled(false);
2615 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2619 if (error.Success())
2620 error.SetErrorToGenericError();
2624 // Pre-requisite: wp != NULL.
2625 static GDBStoppointType
2626 GetGDBStoppointType (Watchpoint *wp)
2629 bool watch_read = wp->WatchpointRead();
2630 bool watch_write = wp->WatchpointWrite();
2632 // watch_read and watch_write cannot both be false.
2633 assert(watch_read || watch_write);
2634 if (watch_read && watch_write)
2635 return eWatchpointReadWrite;
2636 else if (watch_read)
2637 return eWatchpointRead;
2638 else // Must be watch_write, then.
2639 return eWatchpointWrite;
2643 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2648 user_id_t watchID = wp->GetID();
2649 addr_t addr = wp->GetLoadAddress();
2650 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2652 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2653 if (wp->IsEnabled())
2656 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2660 GDBStoppointType type = GetGDBStoppointType(wp);
2661 // Pass down an appropriate z/Z packet...
2662 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2664 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2666 wp->SetEnabled(true, notify);
2670 error.SetErrorString("sending gdb watchpoint packet failed");
2673 error.SetErrorString("watchpoints not supported");
2677 error.SetErrorString("Watchpoint argument was NULL.");
2679 if (error.Success())
2680 error.SetErrorToGenericError();
2685 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2690 user_id_t watchID = wp->GetID();
2692 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2694 addr_t addr = wp->GetLoadAddress();
2697 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2699 if (!wp->IsEnabled())
2702 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2703 // See also 'class WatchpointSentry' within StopInfo.cpp.
2704 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2705 // the watchpoint object to intelligently process this action.
2706 wp->SetEnabled(false, notify);
2710 if (wp->IsHardware())
2712 GDBStoppointType type = GetGDBStoppointType(wp);
2713 // Pass down an appropriate z/Z packet...
2714 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2716 wp->SetEnabled(false, notify);
2720 error.SetErrorString("sending gdb watchpoint packet failed");
2722 // TODO: clear software watchpoints if we implement them
2726 error.SetErrorString("Watchpoint argument was NULL.");
2728 if (error.Success())
2729 error.SetErrorToGenericError();
2734 ProcessGDBRemote::Clear()
2737 m_thread_list_real.Clear();
2738 m_thread_list.Clear();
2742 ProcessGDBRemote::DoSignal (int signo)
2745 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2747 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2749 if (!m_gdb_comm.SendAsyncSignal (signo))
2750 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2755 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
2758 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2760 // If we locate debugserver, keep that located version around
2761 static FileSpec g_debugserver_file_spec;
2763 ProcessLaunchInfo debugserver_launch_info;
2764 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2765 debugserver_launch_info.SetUserID(process_info.GetUserID());
2767 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
2768 // On iOS, still do a local connection using a random port
2769 const char *hostname = "127.0.0.1";
2770 uint16_t port = get_random_port ();
2772 // Set hostname being NULL to do the reverse connect where debugserver
2773 // will bind to port zero and it will communicate back to us the port
2774 // that we will connect to
2775 const char *hostname = NULL;
2779 error = m_gdb_comm.StartDebugserverProcess (hostname,
2781 debugserver_launch_info,
2784 if (error.Success ())
2785 m_debugserver_pid = debugserver_launch_info.GetProcessID();
2787 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2789 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2790 StartAsyncThread ();
2794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2797 log->Printf("failed to start debugserver process: %s", error.AsCString());
2801 if (m_gdb_comm.IsConnected())
2803 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2804 ConnectToDebugserver (NULL);
2808 StreamString connect_url;
2809 connect_url.Printf("connect://%s:%u", hostname, port);
2810 error = ConnectToDebugserver (connect_url.GetString().c_str());
2818 ProcessGDBRemote::MonitorDebugserverProcess
2820 void *callback_baton,
2821 lldb::pid_t debugserver_pid,
2822 bool exited, // True if the process did exit
2823 int signo, // Zero for no signal
2824 int exit_status // Exit value of process if signal is zero
2827 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2828 // and might not exist anymore, so we need to carefully try to get the
2829 // target for this process first since we have a race condition when
2830 // we are done running between getting the notice that the inferior
2831 // process has died and the debugserver that was debugging this process.
2832 // In our test suite, we are also continually running process after
2833 // process, so we must be very careful to make sure:
2834 // 1 - process object hasn't been deleted already
2835 // 2 - that a new process object hasn't been recreated in its place
2837 // "debugserver_pid" argument passed in is the process ID for
2838 // debugserver that we are tracking...
2839 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2841 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2843 // Get a shared pointer to the target that has a matching process pointer.
2844 // This target could be gone, or the target could already have a new process
2845 // object inside of it
2846 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2849 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2853 // We found a process in a target that matches, but another thread
2854 // might be in the process of launching a new process that will
2855 // soon replace it, so get a shared pointer to the process so we
2856 // can keep it alive.
2857 ProcessSP process_sp (target_sp->GetProcessSP());
2858 // Now we have a shared pointer to the process that can't go away on us
2859 // so we now make sure it was the same as the one passed in, and also make
2860 // sure that our previous "process *" didn't get deleted and have a new
2861 // "process *" created in its place with the same pointer. To verify this
2862 // we make sure the process has our debugserver process ID. If we pass all
2863 // of these tests, then we are sure that this process is the one we were
2865 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2867 // Sleep for a half a second to make sure our inferior process has
2868 // time to set its exit status before we set it incorrectly when
2869 // both the debugserver and the inferior process shut down.
2871 // If our process hasn't yet exited, debugserver might have died.
2872 // If the process did exit, the we are reaping it.
2873 const StateType state = process->GetState();
2875 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2876 state != eStateInvalid &&
2877 state != eStateUnloaded &&
2878 state != eStateExited &&
2879 state != eStateDetached)
2881 char error_str[1024];
2884 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2886 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2888 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2892 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2895 process->SetExitStatus (-1, error_str);
2897 // Debugserver has exited we need to let our ProcessGDBRemote
2898 // know that it no longer has a debugserver instance
2899 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2906 ProcessGDBRemote::KillDebugserverProcess ()
2908 m_gdb_comm.Disconnect();
2909 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2911 Host::Kill (m_debugserver_pid, SIGINT);
2912 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2917 ProcessGDBRemote::Initialize()
2919 static bool g_initialized = false;
2921 if (g_initialized == false)
2923 g_initialized = true;
2924 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2925 GetPluginDescriptionStatic(),
2927 DebuggerInitialize);
2929 Log::Callbacks log_callbacks = {
2930 ProcessGDBRemoteLog::DisableLog,
2931 ProcessGDBRemoteLog::EnableLog,
2932 ProcessGDBRemoteLog::ListLogCategories
2935 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2940 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2942 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2944 const bool is_global_setting = true;
2945 PluginManager::CreateSettingForProcessPlugin (debugger,
2946 GetGlobalPluginProperties()->GetValueProperties(),
2947 ConstString ("Properties for the gdb-remote process plug-in."),
2953 ProcessGDBRemote::StartAsyncThread ()
2955 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2958 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2960 Mutex::Locker start_locker(m_async_thread_state_mutex);
2961 if (!m_async_thread.IsJoinable())
2963 // Create a thread that watches our internal state and controls which
2964 // events make it to clients (into the DCProcess event queue).
2966 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2969 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
2971 return m_async_thread.IsJoinable();
2975 ProcessGDBRemote::StopAsyncThread ()
2977 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2980 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2982 Mutex::Locker start_locker(m_async_thread_state_mutex);
2983 if (m_async_thread.IsJoinable())
2985 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2987 // This will shut down the async thread.
2988 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2990 // Stop the stdio thread
2991 m_async_thread.Join(nullptr);
2994 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
2999 ProcessGDBRemote::AsyncThread (void *arg)
3001 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3003 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3005 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
3007 Listener listener ("ProcessGDBRemote::AsyncThread");
3009 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3010 eBroadcastBitAsyncThreadShouldExit;
3012 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3014 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3020 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3021 if (listener.WaitForEvent (NULL, event_sp))
3023 const uint32_t event_type = event_sp->GetType();
3024 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
3027 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3031 case eBroadcastBitAsyncContinue:
3033 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3035 if (continue_packet)
3037 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3038 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3040 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3042 if (::strstr (continue_cstr, "vAttach") == NULL)
3043 process->SetPrivateState(eStateRunning);
3044 StringExtractorGDBRemote response;
3045 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3047 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3048 // The thread ID list might be contained within the "response", or the stop reply packet that
3049 // caused the stop. So clear it now before we give the stop reply packet to the process
3050 // using the process->SetLastStopPacket()...
3051 process->ClearThreadIDList ();
3057 case eStateSuspended:
3058 process->SetLastStopPacket (response);
3059 process->SetPrivateState (stop_state);
3064 process->SetLastStopPacket (response);
3065 process->ClearThreadIDList();
3066 response.SetFilePos(1);
3068 int exit_status = response.GetHexU8();
3069 const char *desc_cstr = NULL;
3070 StringExtractor extractor;
3071 std::string desc_string;
3072 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3074 std::string desc_token;
3075 while (response.GetNameColonValue (desc_token, desc_string))
3077 if (desc_token == "description")
3079 extractor.GetStringRef().swap(desc_string);
3080 extractor.SetFilePos(0);
3081 extractor.GetHexByteString (desc_string);
3082 desc_cstr = desc_string.c_str();
3086 process->SetExitStatus(exit_status, desc_cstr);
3091 process->SetExitStatus(-1, "lost connection");
3095 process->SetPrivateState (stop_state);
3102 case eBroadcastBitAsyncThreadShouldExit:
3104 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3110 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3115 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3117 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3119 process->SetExitStatus (-1, "lost connection");
3127 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3134 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
3136 process->m_async_thread.Reset();
3141 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3143 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3144 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3145 // if (m_local_debugserver)
3147 // return Host::ListProcessesMatchingName (name, matches, pids);
3151 // // FIXME: Implement talking to the remote debugserver.
3158 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3159 lldb_private::StoppointCallbackContext *context,
3160 lldb::user_id_t break_id,
3161 lldb::user_id_t break_loc_id)
3163 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3164 // run so I can stop it if that's what I want to do.
3165 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3167 log->Printf("Hit New Thread Notification breakpoint.");
3173 ProcessGDBRemote::StartNoticingNewThreads()
3175 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3176 if (m_thread_create_bp_sp)
3178 if (log && log->GetVerbose())
3179 log->Printf("Enabled noticing new thread breakpoint.");
3180 m_thread_create_bp_sp->SetEnabled(true);
3184 PlatformSP platform_sp (m_target.GetPlatform());
3187 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3188 if (m_thread_create_bp_sp)
3190 if (log && log->GetVerbose())
3191 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3192 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3197 log->Printf("Failed to create new thread notification breakpoint.");
3201 return m_thread_create_bp_sp.get() != NULL;
3205 ProcessGDBRemote::StopNoticingNewThreads()
3207 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3208 if (log && log->GetVerbose())
3209 log->Printf ("Disabling new thread notification breakpoint.");
3211 if (m_thread_create_bp_sp)
3212 m_thread_create_bp_sp->SetEnabled(false);
3217 lldb_private::DynamicLoader *
3218 ProcessGDBRemote::GetDynamicLoader ()
3220 if (m_dyld_ap.get() == NULL)
3221 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3222 return m_dyld_ap.get();
3226 ProcessGDBRemote::SendEventData(const char *data)
3233 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3234 if (return_value != 0)
3237 error.SetErrorString("Sending events is not supported for this process.");
3239 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3245 ProcessGDBRemote::GetAuxvData()
3248 if (m_gdb_comm.GetQXferAuxvReadSupported())
3250 std::string response_string;
3251 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3252 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3257 StructuredData::ObjectSP
3258 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3260 StructuredData::ObjectSP object_sp;
3262 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3264 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3265 SystemRuntime *runtime = GetSystemRuntime();
3268 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3270 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3272 StreamString packet;
3273 packet << "jThreadExtendedInfo:";
3274 args_dict->Dump (packet);
3276 // FIXME the final character of a JSON dictionary, '}', is the escape
3277 // character in gdb-remote binary mode. lldb currently doesn't escape
3278 // these characters in its packet output -- so we add the quoted version
3279 // of the } character here manually in case we talk to a debugserver which
3280 // un-escapes the characters at packet read time.
3281 packet << (char) (0x7d ^ 0x20);
3283 StringExtractorGDBRemote response;
3284 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3286 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3287 if (response_type == StringExtractorGDBRemote::eResponse)
3289 if (!response.Empty())
3291 // The packet has already had the 0x7d xor quoting stripped out at the
3292 // GDBRemoteCommunication packet receive level.
3293 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3301 // Establish the largest memory read/write payloads we should use.
3302 // If the remote stub has a max packet size, stay under that size.
3304 // If the remote stub's max packet size is crazy large, use a
3305 // reasonable largeish default.
3307 // If the remote stub doesn't advertise a max packet size, use a
3308 // conservative default.
3311 ProcessGDBRemote::GetMaxMemorySize()
3313 const uint64_t reasonable_largeish_default = 128 * 1024;
3314 const uint64_t conservative_default = 512;
3316 if (m_max_memory_size == 0)
3318 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3319 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3321 // Save the stub's claimed maximum packet size
3322 m_remote_stub_max_memory_size = stub_max_size;
3324 // Even if the stub says it can support ginormous packets,
3325 // don't exceed our reasonable largeish default packet size.
3326 if (stub_max_size > reasonable_largeish_default)
3328 stub_max_size = reasonable_largeish_default;
3331 m_max_memory_size = stub_max_size;
3335 m_max_memory_size = conservative_default;
3341 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3343 if (user_specified_max != 0)
3345 GetMaxMemorySize ();
3347 if (m_remote_stub_max_memory_size != 0)
3349 if (m_remote_stub_max_memory_size < user_specified_max)
3351 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3352 // as the remote stub says we can go.
3356 m_max_memory_size = user_specified_max; // user's packet size is good
3361 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3366 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3371 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3372 CommandObjectParsed (interpreter,
3373 "process plugin packet history",
3374 "Dumps the packet history buffer. ",
3379 ~CommandObjectProcessGDBRemotePacketHistory ()
3384 DoExecute (Args& command, CommandReturnObject &result)
3386 const size_t argc = command.GetArgumentCount();
3389 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3392 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3393 result.SetStatus (eReturnStatusSuccessFinishResult);
3399 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3401 result.SetStatus (eReturnStatusFailed);
3406 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3411 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3412 CommandObjectParsed (interpreter,
3413 "process plugin packet xfer-size",
3414 "Maximum size that lldb will try to read/write one one chunk.",
3419 ~CommandObjectProcessGDBRemotePacketXferSize ()
3424 DoExecute (Args& command, CommandReturnObject &result)
3426 const size_t argc = command.GetArgumentCount();
3429 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3430 result.SetStatus (eReturnStatusFailed);
3434 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3437 const char *packet_size = command.GetArgumentAtIndex(0);
3439 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3440 if (errno == 0 && user_specified_max != 0)
3442 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3443 result.SetStatus (eReturnStatusSuccessFinishResult);
3447 result.SetStatus (eReturnStatusFailed);
3453 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3458 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3459 CommandObjectParsed (interpreter,
3460 "process plugin packet send",
3461 "Send a custom packet through the GDB remote protocol and print the answer. "
3462 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3467 ~CommandObjectProcessGDBRemotePacketSend ()
3472 DoExecute (Args& command, CommandReturnObject &result)
3474 const size_t argc = command.GetArgumentCount();
3477 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3478 result.SetStatus (eReturnStatusFailed);
3482 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3485 for (size_t i=0; i<argc; ++ i)
3487 const char *packet_cstr = command.GetArgumentAtIndex(0);
3488 bool send_async = true;
3489 StringExtractorGDBRemote response;
3490 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3491 result.SetStatus (eReturnStatusSuccessFinishResult);
3492 Stream &output_strm = result.GetOutputStream();
3493 output_strm.Printf (" packet: %s\n", packet_cstr);
3494 std::string &response_str = response.GetStringRef();
3496 if (strstr(packet_cstr, "qGetProfileData") != NULL)
3498 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3501 if (response_str.empty())
3502 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3504 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3511 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3516 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3517 CommandObjectRaw (interpreter,
3518 "process plugin packet monitor",
3519 "Send a qRcmd packet through the GDB remote protocol and print the response."
3520 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3525 ~CommandObjectProcessGDBRemotePacketMonitor ()
3530 DoExecute (const char *command, CommandReturnObject &result)
3532 if (command == NULL || command[0] == '\0')
3534 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3535 result.SetStatus (eReturnStatusFailed);
3539 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3542 StreamString packet;
3543 packet.PutCString("qRcmd,");
3544 packet.PutBytesAsRawHex8(command, strlen(command));
3545 const char *packet_cstr = packet.GetString().c_str();
3547 bool send_async = true;
3548 StringExtractorGDBRemote response;
3549 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3550 result.SetStatus (eReturnStatusSuccessFinishResult);
3551 Stream &output_strm = result.GetOutputStream();
3552 output_strm.Printf (" packet: %s\n", packet_cstr);
3553 const std::string &response_str = response.GetStringRef();
3555 if (response_str.empty())
3556 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3558 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3564 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3569 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3570 CommandObjectMultiword (interpreter,
3571 "process plugin packet",
3572 "Commands that deal with GDB remote packets.",
3575 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3576 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3577 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3578 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
3581 ~CommandObjectProcessGDBRemotePacket ()
3586 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3589 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3590 CommandObjectMultiword (interpreter,
3592 "A set of commands for operating on a ProcessGDBRemote process.",
3593 "process plugin <subcommand> [<subcommand-options>]")
3595 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3598 ~CommandObjectMultiwordProcessGDBRemote ()
3604 ProcessGDBRemote::GetPluginCommandObject()
3607 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3608 return m_command_sp.get();