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/Host/Config.h"
15 #ifndef LLDB_DISABLE_POSIX
16 #include <netinet/in.h>
17 #include <sys/mman.h> // for mmap
20 #include <sys/types.h>
28 #include "lldb/Breakpoint/Watchpoint.h"
29 #include "lldb/Interpreter/Args.h"
30 #include "lldb/Core/ArchSpec.h"
31 #include "lldb/Core/Debugger.h"
32 #include "lldb/Host/ConnectionFileDescriptor.h"
33 #include "lldb/Host/FileSpec.h"
34 #include "lldb/Core/Module.h"
35 #include "lldb/Core/ModuleSpec.h"
36 #include "lldb/Core/PluginManager.h"
37 #include "lldb/Core/State.h"
38 #include "lldb/Core/StreamFile.h"
39 #include "lldb/Core/StreamString.h"
40 #include "lldb/Core/Timer.h"
41 #include "lldb/Core/Value.h"
42 #include "lldb/DataFormatters/FormatManager.h"
43 #include "lldb/Host/FileSystem.h"
44 #include "lldb/Host/HostThread.h"
45 #include "lldb/Host/StringConvert.h"
46 #include "lldb/Host/Symbols.h"
47 #include "lldb/Host/ThreadLauncher.h"
48 #include "lldb/Host/TimeValue.h"
49 #include "lldb/Host/XML.h"
50 #include "lldb/Interpreter/CommandInterpreter.h"
51 #include "lldb/Interpreter/CommandObject.h"
52 #include "lldb/Interpreter/CommandObjectMultiword.h"
53 #include "lldb/Interpreter/CommandReturnObject.h"
54 #include "lldb/Interpreter/OptionValueProperties.h"
55 #include "lldb/Interpreter/Options.h"
56 #include "lldb/Interpreter/OptionGroupBoolean.h"
57 #include "lldb/Interpreter/OptionGroupUInt64.h"
58 #include "lldb/Interpreter/Property.h"
59 #include "lldb/Symbol/ObjectFile.h"
60 #include "lldb/Target/ABI.h"
61 #include "lldb/Target/DynamicLoader.h"
62 #include "lldb/Target/Target.h"
63 #include "lldb/Target/TargetList.h"
64 #include "lldb/Target/ThreadPlanCallFunction.h"
65 #include "lldb/Target/SystemRuntime.h"
66 #include "lldb/Utility/PseudoTerminal.h"
69 #include "lldb/Host/Host.h"
70 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
71 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
72 #include "Plugins/Process/Utility/StopInfoMachException.h"
73 #include "Utility/StringExtractorGDBRemote.h"
74 #include "GDBRemoteRegisterContext.h"
75 #include "ProcessGDBRemote.h"
76 #include "ProcessGDBRemoteLog.h"
77 #include "ThreadGDBRemote.h"
79 #define DEBUGSERVER_BASENAME "debugserver"
81 using namespace lldb_private;
82 using namespace lldb_private::process_gdb_remote;
86 // Provide a function that can easily dump the packet history if we know a
87 // ProcessGDBRemote * value (which we can get from logs or from debugging).
88 // We need the function in the lldb namespace so it makes it into the final
89 // executable since the LLDB shared library only exports stuff in the lldb
90 // namespace. This allows you to attach with a debugger and call this
91 // function and get the packet history dumped to a file.
93 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
96 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
98 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
104 static PropertyDefinition
107 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
108 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
109 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
114 ePropertyPacketTimeout,
115 ePropertyTargetDefinitionFile
118 class PluginProperties : public Properties
125 return ProcessGDBRemote::GetPluginNameStatic();
131 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
132 m_collection_sp->Initialize(g_properties);
143 const uint32_t idx = ePropertyPacketTimeout;
144 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
148 SetPacketTimeout(uint64_t timeout)
150 const uint32_t idx = ePropertyPacketTimeout;
151 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
155 GetTargetDefinitionFile () const
157 const uint32_t idx = ePropertyTargetDefinitionFile;
158 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
162 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
164 static const ProcessKDPPropertiesSP &
165 GetGlobalPluginProperties()
167 static ProcessKDPPropertiesSP g_settings_sp;
169 g_settings_sp.reset (new PluginProperties ());
170 return g_settings_sp;
173 } // anonymous namespace end
175 // TODO Randomly assigning a port is unsafe. We should get an unused
176 // ephemeral port from the kernel and make sure we reserve it before passing
177 // it to debugserver.
179 #if defined (__APPLE__)
180 #define LOW_PORT (IPPORT_RESERVED)
181 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
183 #define LOW_PORT (1024u)
184 #define HIGH_PORT (49151u)
187 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
188 static bool rand_initialized = false;
190 static inline uint16_t
193 if (!rand_initialized)
195 time_t seed = time(NULL);
197 rand_initialized = true;
200 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
205 ProcessGDBRemote::GetPluginNameStatic()
207 static ConstString g_name("gdb-remote");
212 ProcessGDBRemote::GetPluginDescriptionStatic()
214 return "GDB Remote protocol based debugging plug-in.";
218 ProcessGDBRemote::Terminate()
220 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
225 ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, Listener &listener, const FileSpec *crash_file_path)
227 lldb::ProcessSP process_sp;
228 if (crash_file_path == NULL)
229 process_sp.reset (new ProcessGDBRemote (target_sp, listener));
234 ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
236 if (plugin_specified_by_name)
239 // For now we are just making sure the file exists for a given module
240 Module *exe_module = target_sp->GetExecutableModulePointer();
243 ObjectFile *exe_objfile = exe_module->GetObjectFile();
244 // We can't debug core files...
245 switch (exe_objfile->GetType())
247 case ObjectFile::eTypeInvalid:
248 case ObjectFile::eTypeCoreFile:
249 case ObjectFile::eTypeDebugInfo:
250 case ObjectFile::eTypeObjectFile:
251 case ObjectFile::eTypeSharedLibrary:
252 case ObjectFile::eTypeStubLibrary:
253 case ObjectFile::eTypeJIT:
255 case ObjectFile::eTypeExecutable:
256 case ObjectFile::eTypeDynamicLinker:
257 case ObjectFile::eTypeUnknown:
260 return exe_module->GetFileSpec().Exists();
262 // However, if there is no executable module, we return true since we might be preparing to attach.
266 //----------------------------------------------------------------------
267 // ProcessGDBRemote constructor
268 //----------------------------------------------------------------------
269 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, Listener &listener) :
270 Process (target_sp, listener),
273 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
274 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
276 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
277 m_async_listener("lldb.process.gdb-remote.async-listener"),
278 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
282 m_jthreadsinfo_sp (),
283 m_continue_c_tids (),
284 m_continue_C_tids (),
285 m_continue_s_tids (),
286 m_continue_S_tids (),
287 m_max_memory_size (0),
288 m_remote_stub_max_memory_size (0),
289 m_addr_to_mmap_size (),
290 m_thread_create_bp_sp (),
291 m_waiting_for_attach (false),
292 m_destroy_tried_resuming (false),
294 m_breakpoint_pc_offset (0),
295 m_initial_tid (LLDB_INVALID_THREAD_ID)
297 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
298 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
299 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
301 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_ASYNC));
303 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
305 if (m_async_listener.StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
308 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
311 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit |
312 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
313 if (m_async_listener.StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
316 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
319 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
320 if (timeout_seconds > 0)
321 m_gdb_comm.SetPacketTimeout(timeout_seconds);
324 //----------------------------------------------------------------------
326 //----------------------------------------------------------------------
327 ProcessGDBRemote::~ProcessGDBRemote()
329 // m_mach_process.UnregisterNotificationCallbacks (this);
331 // We need to call finalize on the process before destroying ourselves
332 // to make sure all of the broadcaster cleanup goes as planned. If we
333 // destruct this class, then Process::~Process() might have problems
334 // trying to fully destroy the broadcaster.
337 // The general Finalize is going to try to destroy the process and that SHOULD
338 // shut down the async thread. However, if we don't kill it it will get stranded and
339 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
341 KillDebugserverProcess();
344 //----------------------------------------------------------------------
346 //----------------------------------------------------------------------
348 ProcessGDBRemote::GetPluginName()
350 return GetPluginNameStatic();
354 ProcessGDBRemote::GetPluginVersion()
360 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
362 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
364 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
365 if (module_object_sp)
367 StructuredData::DictionarySP target_definition_sp(
368 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
370 if (target_definition_sp)
372 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
375 if (auto host_info_dict = target_object->GetAsDictionary())
377 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
378 if (auto triple_string_value = triple_value->GetAsString())
380 std::string triple_string = triple_string_value->GetValue();
381 ArchSpec host_arch(triple_string.c_str());
382 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
384 GetTarget().SetArchitecture(host_arch);
389 m_breakpoint_pc_offset = 0;
390 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
391 if (breakpoint_pc_offset_value)
393 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
394 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
397 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
406 // If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
407 // see if the ABI can provide them.
408 // DWARF and eh_frame register numbers are defined as a part of the ABI.
410 AugmentRegisterInfoViaABI (RegisterInfo ®_info, ConstString reg_name, ABISP abi_sp)
412 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
413 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
417 RegisterInfo abi_reg_info;
418 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
420 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
421 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
423 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
425 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
426 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
428 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
430 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
431 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM)
433 reg_info.kinds[eRegisterKindGeneric] = abi_reg_info.kinds[eRegisterKindGeneric];
441 SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> ®nums, int base)
444 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
445 value_pair.second = comma_separated_regiter_numbers;
448 value_pair = value_pair.second.split(',');
449 if (!value_pair.first.empty())
451 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
452 if (reg != LLDB_INVALID_REGNUM)
453 regnums.push_back (reg);
455 } while (!value_pair.second.empty());
456 return regnums.size();
461 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
463 if (!force && m_register_info.GetNumRegisters() > 0)
466 m_register_info.Clear();
468 // Check if qHostInfo specified a specific packet timeout for this connection.
469 // If so then lets update our setting so the user knows what the timeout is
471 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
472 if (host_packet_timeout)
474 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
477 // Register info search order:
478 // 1 - Use the target definition python file if one is specified.
479 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
480 // 3 - Fall back on the qRegisterInfo packets.
482 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
483 if (!target_definition_fspec.Exists())
485 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
486 target_definition_fspec.ResolvePath();
488 if (target_definition_fspec)
490 // See if we can get register definitions from a python file
491 if (ParsePythonTargetDefinition (target_definition_fspec))
497 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
498 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
502 if (GetGDBServerRegisterInfo ())
506 uint32_t reg_offset = 0;
507 uint32_t reg_num = 0;
508 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
509 response_type == StringExtractorGDBRemote::eResponse;
512 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
513 assert (packet_len < (int)sizeof(packet));
514 StringExtractorGDBRemote response;
515 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
517 response_type = response.GetResponseType();
518 if (response_type == StringExtractorGDBRemote::eResponse)
522 ConstString reg_name;
523 ConstString alt_name;
524 ConstString set_name;
525 std::vector<uint32_t> value_regs;
526 std::vector<uint32_t> invalidate_regs;
527 RegisterInfo reg_info = { NULL, // Name
530 reg_offset, // offset
531 eEncodingUint, // encoding
532 eFormatHex, // format
534 LLDB_INVALID_REGNUM, // eh_frame reg num
535 LLDB_INVALID_REGNUM, // DWARF reg num
536 LLDB_INVALID_REGNUM, // generic reg num
537 reg_num, // process plugin reg num
538 reg_num // native register number
544 while (response.GetNameColonValue(name, value))
546 if (name.compare("name") == 0)
548 reg_name.SetCString(value.c_str());
550 else if (name.compare("alt-name") == 0)
552 alt_name.SetCString(value.c_str());
554 else if (name.compare("bitsize") == 0)
556 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
558 else if (name.compare("offset") == 0)
560 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
561 if (reg_offset != offset)
566 else if (name.compare("encoding") == 0)
568 const Encoding encoding = Args::StringToEncoding (value.c_str());
569 if (encoding != eEncodingInvalid)
570 reg_info.encoding = encoding;
572 else if (name.compare("format") == 0)
574 Format format = eFormatInvalid;
575 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
576 reg_info.format = format;
577 else if (value.compare("binary") == 0)
578 reg_info.format = eFormatBinary;
579 else if (value.compare("decimal") == 0)
580 reg_info.format = eFormatDecimal;
581 else if (value.compare("hex") == 0)
582 reg_info.format = eFormatHex;
583 else if (value.compare("float") == 0)
584 reg_info.format = eFormatFloat;
585 else if (value.compare("vector-sint8") == 0)
586 reg_info.format = eFormatVectorOfSInt8;
587 else if (value.compare("vector-uint8") == 0)
588 reg_info.format = eFormatVectorOfUInt8;
589 else if (value.compare("vector-sint16") == 0)
590 reg_info.format = eFormatVectorOfSInt16;
591 else if (value.compare("vector-uint16") == 0)
592 reg_info.format = eFormatVectorOfUInt16;
593 else if (value.compare("vector-sint32") == 0)
594 reg_info.format = eFormatVectorOfSInt32;
595 else if (value.compare("vector-uint32") == 0)
596 reg_info.format = eFormatVectorOfUInt32;
597 else if (value.compare("vector-float32") == 0)
598 reg_info.format = eFormatVectorOfFloat32;
599 else if (value.compare("vector-uint128") == 0)
600 reg_info.format = eFormatVectorOfUInt128;
602 else if (name.compare("set") == 0)
604 set_name.SetCString(value.c_str());
606 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
608 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
610 else if (name.compare("dwarf") == 0)
612 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
614 else if (name.compare("generic") == 0)
616 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
618 else if (name.compare("container-regs") == 0)
620 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
622 else if (name.compare("invalidate-regs") == 0)
624 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
628 reg_info.byte_offset = reg_offset;
629 assert (reg_info.byte_size != 0);
630 reg_offset += reg_info.byte_size;
631 if (!value_regs.empty())
633 value_regs.push_back(LLDB_INVALID_REGNUM);
634 reg_info.value_regs = value_regs.data();
636 if (!invalidate_regs.empty())
638 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
639 reg_info.invalidate_regs = invalidate_regs.data();
642 AugmentRegisterInfoViaABI (reg_info, reg_name, GetABI ());
644 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
648 break; // ensure exit before reg_num is incremented
657 if (m_register_info.GetNumRegisters() > 0)
659 m_register_info.Finalize(GetTarget().GetArchitecture());
663 // We didn't get anything if the accumulated reg_num is zero. See if we are
664 // debugging ARM and fill with a hard coded register set until we can get an
665 // updated debugserver down on the devices.
666 // On the other hand, if the accumulated reg_num is positive, see if we can
667 // add composite registers to the existing primordial ones.
668 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
670 const ArchSpec &target_arch = GetTarget().GetArchitecture();
671 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
672 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
674 // Use the process' architecture instead of the host arch, if available
675 ArchSpec remote_arch;
676 if (remote_process_arch.IsValid ())
677 remote_arch = remote_process_arch;
679 remote_arch = remote_host_arch;
681 if (!target_arch.IsValid())
683 if (remote_arch.IsValid()
684 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
685 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
686 m_register_info.HardcodeARMRegisters(from_scratch);
688 else if (target_arch.GetMachine() == llvm::Triple::arm
689 || target_arch.GetMachine() == llvm::Triple::thumb)
691 m_register_info.HardcodeARMRegisters(from_scratch);
694 // At this point, we can finalize our register info.
695 m_register_info.Finalize (GetTarget().GetArchitecture());
699 ProcessGDBRemote::WillLaunch (Module* module)
701 return WillLaunchOrAttach ();
705 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
707 return WillLaunchOrAttach ();
711 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
713 return WillLaunchOrAttach ();
717 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
719 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
720 Error error (WillLaunchOrAttach ());
725 error = ConnectToDebugserver (remote_url);
731 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
732 if (pid == LLDB_INVALID_PROCESS_ID)
734 // We don't have a valid process ID, so note that we are connected
735 // and could now request to launch or attach, or get remote process
737 SetPrivateState (eStateConnected);
741 // We have a valid process
744 StringExtractorGDBRemote response;
745 if (m_gdb_comm.GetStopReply(response))
747 SetLastStopPacket(response);
749 // '?' Packets must be handled differently in non-stop mode
750 if (GetTarget().GetNonStopModeEnabled())
751 HandleStopReplySequence();
753 Target &target = GetTarget();
754 if (!target.GetArchitecture().IsValid())
756 if (m_gdb_comm.GetProcessArchitecture().IsValid())
758 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
762 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
766 const StateType state = SetThreadStopInfo (response);
767 if (state != eStateInvalid)
769 SetPrivateState (state);
772 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
775 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
779 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");
783 && !GetTarget().GetArchitecture().IsValid()
784 && m_gdb_comm.GetHostArchitecture().IsValid())
786 // Prefer the *process'* architecture over that of the *host*, if available.
787 if (m_gdb_comm.GetProcessArchitecture().IsValid())
788 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
790 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
794 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
798 PlatformSP platform_sp = GetTarget().GetPlatform();
799 if (platform_sp && platform_sp->IsConnected())
800 SetUnixSignals(platform_sp->GetUnixSignals());
802 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
809 ProcessGDBRemote::WillLaunchOrAttach ()
812 m_stdio_communication.Clear ();
816 //----------------------------------------------------------------------
818 //----------------------------------------------------------------------
820 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
822 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
826 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
828 uint32_t launch_flags = launch_info.GetFlags().Get();
829 FileSpec stdin_file_spec{};
830 FileSpec stdout_file_spec{};
831 FileSpec stderr_file_spec{};
832 FileSpec working_dir = launch_info.GetWorkingDirectory();
834 const FileAction *file_action;
835 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
838 if (file_action->GetAction() == FileAction::eFileActionOpen)
839 stdin_file_spec = file_action->GetFileSpec();
841 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
844 if (file_action->GetAction() == FileAction::eFileActionOpen)
845 stdout_file_spec = file_action->GetFileSpec();
847 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
850 if (file_action->GetAction() == FileAction::eFileActionOpen)
851 stderr_file_spec = file_action->GetFileSpec();
856 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
857 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
859 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
860 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
861 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
863 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
866 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
867 if (stdin_file_spec || disable_stdio)
869 // the inferior will be reading stdin from the specified file
870 // or stdio is completely disabled
871 m_stdin_forward = false;
875 m_stdin_forward = true;
878 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
879 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
880 // ::LogSetLogFile ("/dev/stdout");
882 ObjectFile * object_file = exe_module->GetObjectFile();
885 error = EstablishConnectionIfNeeded (launch_info);
888 lldb_utility::PseudoTerminal pty;
889 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
891 PlatformSP platform_sp (GetTarget().GetPlatform());
894 // set to /dev/null unless redirected to a file above
895 if (!stdin_file_spec)
896 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
897 if (!stdout_file_spec)
898 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
899 if (!stderr_file_spec)
900 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
902 else if (platform_sp && platform_sp->IsHost())
904 // If the debugserver is local and we aren't disabling STDIO, lets use
905 // a pseudo terminal to instead of relying on the 'O' packets for stdio
906 // since 'O' packets can really slow down debugging if the inferior
907 // does a lot of output.
908 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
909 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
911 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
913 if (!stdin_file_spec)
914 stdin_file_spec = slave_name;
916 if (!stdout_file_spec)
917 stdout_file_spec = slave_name;
919 if (!stderr_file_spec)
920 stderr_file_spec = slave_name;
923 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
925 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
926 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
927 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
931 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
933 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
934 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
935 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
938 m_gdb_comm.SetSTDIN(stdin_file_spec);
939 if (stdout_file_spec)
940 m_gdb_comm.SetSTDOUT(stdout_file_spec);
941 if (stderr_file_spec)
942 m_gdb_comm.SetSTDERR(stderr_file_spec);
944 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
945 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
947 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
949 const char * launch_event_data = launch_info.GetLaunchEventData();
950 if (launch_event_data != NULL && *launch_event_data != '\0')
951 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
955 m_gdb_comm.SetWorkingDir (working_dir);
958 // Send the environment and the program + arguments after we connect
959 const Args &environment = launch_info.GetEnvironmentEntries();
960 if (environment.GetArgumentCount())
962 size_t num_environment_entries = environment.GetArgumentCount();
963 for (size_t i=0; i<num_environment_entries; ++i)
965 const char *env_entry = environment.GetArgumentAtIndex(i);
966 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
972 // Scope for the scoped timeout object
973 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
975 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
976 if (arg_packet_err == 0)
978 std::string error_str;
979 if (m_gdb_comm.GetLaunchSuccess (error_str))
981 SetID (m_gdb_comm.GetCurrentProcessID ());
985 error.SetErrorString (error_str.c_str());
990 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
994 if (GetID() == LLDB_INVALID_PROCESS_ID)
997 log->Printf("failed to connect to debugserver: %s", error.AsCString());
998 KillDebugserverProcess ();
1002 StringExtractorGDBRemote response;
1003 if (m_gdb_comm.GetStopReply(response))
1005 SetLastStopPacket(response);
1006 // '?' Packets must be handled differently in non-stop mode
1007 if (GetTarget().GetNonStopModeEnabled())
1008 HandleStopReplySequence();
1010 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1012 if (process_arch.IsValid())
1014 GetTarget().MergeArchitecture(process_arch);
1018 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1019 if (host_arch.IsValid())
1020 GetTarget().MergeArchitecture(host_arch);
1023 SetPrivateState (SetThreadStopInfo (response));
1027 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
1028 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
1035 log->Printf("failed to connect to debugserver: %s", error.AsCString());
1040 // Set our user ID to an invalid process ID.
1041 SetID(LLDB_INVALID_PROCESS_ID);
1042 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1043 exe_module->GetFileSpec().GetFilename().AsCString(),
1044 exe_module->GetArchitecture().GetArchitectureName());
1052 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
1055 // Only connect if we have a valid connect URL
1056 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1058 if (connect_url && connect_url[0])
1061 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
1062 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1065 const uint32_t max_retry_count = 50;
1066 uint32_t retry_count = 0;
1067 while (!m_gdb_comm.IsConnected())
1069 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1071 m_gdb_comm.SetConnection (conn_ap.release());
1074 else if (error.WasInterrupted())
1076 // If we were interrupted, don't keep retrying.
1082 if (retry_count >= max_retry_count)
1090 if (!m_gdb_comm.IsConnected())
1092 if (error.Success())
1093 error.SetErrorString("not connected to remote gdb server");
1098 // Start the communications read thread so all incoming data can be
1099 // parsed into packets and queued as they arrive.
1100 if (GetTarget().GetNonStopModeEnabled())
1101 m_gdb_comm.StartReadThread();
1103 // We always seem to be able to open a connection to a local port
1104 // so we need to make sure we can then send data to it. If we can't
1105 // then we aren't actually connected to anything, so try and do the
1106 // handshake with the remote GDB server and make sure that goes
1108 if (!m_gdb_comm.HandshakeWithServer (&error))
1110 m_gdb_comm.Disconnect();
1111 if (error.Success())
1112 error.SetErrorString("not connected to remote gdb server");
1116 // Send $QNonStop:1 packet on startup if required
1117 if (GetTarget().GetNonStopModeEnabled())
1118 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
1120 m_gdb_comm.GetEchoSupported ();
1121 m_gdb_comm.GetThreadSuffixSupported ();
1122 m_gdb_comm.GetListThreadsInStopReplySupported ();
1123 m_gdb_comm.GetHostInfo ();
1124 m_gdb_comm.GetVContSupported ('c');
1125 m_gdb_comm.GetVAttachOrWaitSupported();
1127 // Ask the remote server for the default thread id
1128 if (GetTarget().GetNonStopModeEnabled())
1129 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1132 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1133 for (size_t idx = 0; idx < num_cmds; idx++)
1135 StringExtractorGDBRemote response;
1136 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1142 ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
1144 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1146 log->Printf ("ProcessGDBRemote::DidLaunch()");
1147 if (GetID() != LLDB_INVALID_PROCESS_ID)
1149 BuildDynamicRegisterInfo (false);
1151 // See if the GDB server supports the qHostInfo information
1154 // See if the GDB server supports the qProcessInfo packet, if so
1155 // prefer that over the Host information as it will be more specific
1158 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1159 if (remote_process_arch.IsValid())
1161 process_arch = remote_process_arch;
1163 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1165 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1166 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1170 process_arch = m_gdb_comm.GetHostArchitecture();
1172 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1174 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1175 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1178 if (process_arch.IsValid())
1180 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1181 if (target_arch.IsValid())
1184 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1186 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1187 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1189 // If the remote host is ARM and we have apple as the vendor, then
1190 // ARM executables and shared libraries can have mixed ARM architectures.
1191 // You can have an armv6 executable, and if the host is armv7, then the
1192 // system will load the best possible architecture for all shared libraries
1193 // it has, so we really need to take the remote host architecture as our
1194 // defacto architecture in this case.
1196 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1197 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1199 GetTarget().SetArchitecture (process_arch);
1201 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1203 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1204 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1208 // Fill in what is missing in the triple
1209 const llvm::Triple &remote_triple = process_arch.GetTriple();
1210 llvm::Triple new_target_triple = target_arch.GetTriple();
1211 if (new_target_triple.getVendorName().size() == 0)
1213 new_target_triple.setVendor (remote_triple.getVendor());
1215 if (new_target_triple.getOSName().size() == 0)
1217 new_target_triple.setOS (remote_triple.getOS());
1219 if (new_target_triple.getEnvironmentName().size() == 0)
1220 new_target_triple.setEnvironment (remote_triple.getEnvironment());
1223 ArchSpec new_target_arch = target_arch;
1224 new_target_arch.SetTriple(new_target_triple);
1225 GetTarget().SetArchitecture(new_target_arch);
1230 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1232 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1233 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1237 // The target doesn't have a valid architecture yet, set it from
1238 // the architecture we got from the remote GDB server
1239 GetTarget().SetArchitecture (process_arch);
1246 ProcessGDBRemote::DidLaunch ()
1248 ArchSpec process_arch;
1249 DidLaunchOrAttach (process_arch);
1253 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1255 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1259 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1261 // Clear out and clean up from any current state
1263 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1265 error = EstablishConnectionIfNeeded (attach_info);
1266 if (error.Success())
1268 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1271 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1273 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1276 SetExitStatus (-1, error.AsCString());
1283 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1286 // Clear out and clean up from any current state
1289 if (process_name && process_name[0])
1291 error = EstablishConnectionIfNeeded (attach_info);
1292 if (error.Success())
1294 StreamString packet;
1296 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1298 if (attach_info.GetWaitForLaunch())
1300 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1302 packet.PutCString ("vAttachWait");
1306 if (attach_info.GetIgnoreExisting())
1307 packet.PutCString("vAttachWait");
1309 packet.PutCString ("vAttachOrWait");
1313 packet.PutCString("vAttachName");
1314 packet.PutChar(';');
1315 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
1317 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1321 SetExitStatus (-1, error.AsCString());
1327 ProcessGDBRemote::DidExit ()
1329 // When we exit, disconnect from the GDB server communications
1330 m_gdb_comm.Disconnect();
1334 ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
1336 // If you can figure out what the architecture is, fill it in here.
1337 process_arch.Clear();
1338 DidLaunchOrAttach (process_arch);
1343 ProcessGDBRemote::WillResume ()
1345 m_continue_c_tids.clear();
1346 m_continue_C_tids.clear();
1347 m_continue_s_tids.clear();
1348 m_continue_S_tids.clear();
1349 m_jstopinfo_sp.reset();
1350 m_jthreadsinfo_sp.reset();
1355 ProcessGDBRemote::DoResume ()
1358 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1360 log->Printf ("ProcessGDBRemote::Resume()");
1362 Listener listener ("gdb-remote.resume-packet-sent");
1363 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1365 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1367 const size_t num_threads = GetThreadList().GetSize();
1369 StreamString continue_packet;
1370 bool continue_packet_error = false;
1371 if (m_gdb_comm.HasAnyVContSupport ())
1373 if (!GetTarget().GetNonStopModeEnabled() &&
1374 (m_continue_c_tids.size() == num_threads ||
1375 (m_continue_c_tids.empty() &&
1376 m_continue_C_tids.empty() &&
1377 m_continue_s_tids.empty() &&
1378 m_continue_S_tids.empty())))
1380 // All threads are continuing, just send a "c" packet
1381 continue_packet.PutCString ("c");
1385 continue_packet.PutCString ("vCont");
1387 if (!m_continue_c_tids.empty())
1389 if (m_gdb_comm.GetVContSupported ('c'))
1391 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)
1392 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1395 continue_packet_error = true;
1398 if (!continue_packet_error && !m_continue_C_tids.empty())
1400 if (m_gdb_comm.GetVContSupported ('C'))
1402 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)
1403 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1406 continue_packet_error = true;
1409 if (!continue_packet_error && !m_continue_s_tids.empty())
1411 if (m_gdb_comm.GetVContSupported ('s'))
1413 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)
1414 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1417 continue_packet_error = true;
1420 if (!continue_packet_error && !m_continue_S_tids.empty())
1422 if (m_gdb_comm.GetVContSupported ('S'))
1424 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)
1425 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1428 continue_packet_error = true;
1431 if (continue_packet_error)
1432 continue_packet.GetString().clear();
1436 continue_packet_error = true;
1438 if (continue_packet_error)
1440 // Either no vCont support, or we tried to use part of the vCont
1441 // packet that wasn't supported by the remote GDB server.
1442 // We need to try and make a simple packet that can do our continue
1443 const size_t num_continue_c_tids = m_continue_c_tids.size();
1444 const size_t num_continue_C_tids = m_continue_C_tids.size();
1445 const size_t num_continue_s_tids = m_continue_s_tids.size();
1446 const size_t num_continue_S_tids = m_continue_S_tids.size();
1447 if (num_continue_c_tids > 0)
1449 if (num_continue_c_tids == num_threads)
1451 // All threads are resuming...
1452 m_gdb_comm.SetCurrentThreadForRun (-1);
1453 continue_packet.PutChar ('c');
1454 continue_packet_error = false;
1456 else if (num_continue_c_tids == 1 &&
1457 num_continue_C_tids == 0 &&
1458 num_continue_s_tids == 0 &&
1459 num_continue_S_tids == 0 )
1461 // Only one thread is continuing
1462 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1463 continue_packet.PutChar ('c');
1464 continue_packet_error = false;
1468 if (continue_packet_error && num_continue_C_tids > 0)
1470 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1471 num_continue_C_tids > 0 &&
1472 num_continue_s_tids == 0 &&
1473 num_continue_S_tids == 0 )
1475 const int continue_signo = m_continue_C_tids.front().second;
1476 // Only one thread is continuing
1477 if (num_continue_C_tids > 1)
1479 // More that one thread with a signal, yet we don't have
1480 // vCont support and we are being asked to resume each
1481 // thread with a signal, we need to make sure they are
1482 // all the same signal, or we can't issue the continue
1483 // accurately with the current support...
1484 if (num_continue_C_tids > 1)
1486 continue_packet_error = false;
1487 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1489 if (m_continue_C_tids[i].second != continue_signo)
1490 continue_packet_error = true;
1493 if (!continue_packet_error)
1494 m_gdb_comm.SetCurrentThreadForRun (-1);
1498 // Set the continue thread ID
1499 continue_packet_error = false;
1500 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1502 if (!continue_packet_error)
1504 // Add threads continuing with the same signo...
1505 continue_packet.Printf("C%2.2x", continue_signo);
1510 if (continue_packet_error && num_continue_s_tids > 0)
1512 if (num_continue_s_tids == num_threads)
1514 // All threads are resuming...
1515 m_gdb_comm.SetCurrentThreadForRun (-1);
1517 // If in Non-Stop-Mode use vCont when stepping
1518 if (GetTarget().GetNonStopModeEnabled())
1520 if (m_gdb_comm.GetVContSupported('s'))
1521 continue_packet.PutCString("vCont;s");
1523 continue_packet.PutChar('s');
1526 continue_packet.PutChar('s');
1528 continue_packet_error = false;
1530 else if (num_continue_c_tids == 0 &&
1531 num_continue_C_tids == 0 &&
1532 num_continue_s_tids == 1 &&
1533 num_continue_S_tids == 0 )
1535 // Only one thread is stepping
1536 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1537 continue_packet.PutChar ('s');
1538 continue_packet_error = false;
1542 if (!continue_packet_error && num_continue_S_tids > 0)
1544 if (num_continue_S_tids == num_threads)
1546 const int step_signo = m_continue_S_tids.front().second;
1547 // Are all threads trying to step with the same signal?
1548 continue_packet_error = false;
1549 if (num_continue_S_tids > 1)
1551 for (size_t i=1; i<num_threads; ++i)
1553 if (m_continue_S_tids[i].second != step_signo)
1554 continue_packet_error = true;
1557 if (!continue_packet_error)
1559 // Add threads stepping with the same signo...
1560 m_gdb_comm.SetCurrentThreadForRun (-1);
1561 continue_packet.Printf("S%2.2x", step_signo);
1564 else if (num_continue_c_tids == 0 &&
1565 num_continue_C_tids == 0 &&
1566 num_continue_s_tids == 0 &&
1567 num_continue_S_tids == 1 )
1569 // Only one thread is stepping with signal
1570 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1571 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1572 continue_packet_error = false;
1577 if (continue_packet_error)
1579 error.SetErrorString ("can't make continue packet for this resume");
1585 timeout = TimeValue::Now();
1586 timeout.OffsetWithSeconds (5);
1587 if (!m_async_thread.IsJoinable())
1589 error.SetErrorString ("Trying to resume but the async thread is dead.");
1591 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1595 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1597 if (listener.WaitForEvent (&timeout, event_sp) == false)
1599 error.SetErrorString("Resume timed out.");
1601 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1603 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1605 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1607 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1617 ProcessGDBRemote::HandleStopReplySequence ()
1622 StringExtractorGDBRemote response;
1623 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1625 // OK represents end of signal list
1626 if (response.IsOKResponse())
1629 // If not OK or a normal packet we have a problem
1630 if (!response.IsNormalResponse())
1633 SetLastStopPacket(response);
1638 ProcessGDBRemote::ClearThreadIDList ()
1640 Mutex::Locker locker(m_thread_list_real.GetMutex());
1641 m_thread_ids.clear();
1642 m_thread_pcs.clear();
1646 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1648 m_thread_ids.clear();
1649 m_thread_pcs.clear();
1652 while ((comma_pos = value.find(',')) != std::string::npos)
1654 value[comma_pos] = '\0';
1655 // thread in big endian hex
1656 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1657 if (tid != LLDB_INVALID_THREAD_ID)
1658 m_thread_ids.push_back (tid);
1659 value.erase(0, comma_pos + 1);
1661 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1662 if (tid != LLDB_INVALID_THREAD_ID)
1663 m_thread_ids.push_back (tid);
1664 return m_thread_ids.size();
1668 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1670 m_thread_pcs.clear();
1673 while ((comma_pos = value.find(',')) != std::string::npos)
1675 value[comma_pos] = '\0';
1676 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1677 if (pc != LLDB_INVALID_ADDRESS)
1678 m_thread_pcs.push_back (pc);
1679 value.erase(0, comma_pos + 1);
1681 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1682 if (pc != LLDB_INVALID_THREAD_ID)
1683 m_thread_pcs.push_back (pc);
1684 return m_thread_pcs.size();
1688 ProcessGDBRemote::UpdateThreadIDList ()
1690 Mutex::Locker locker(m_thread_list_real.GetMutex());
1692 if (m_jthreadsinfo_sp)
1694 // If we have the JSON threads info, we can get the thread list from that
1695 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1696 if (thread_infos && thread_infos->GetSize() > 0)
1698 m_thread_ids.clear();
1699 m_thread_pcs.clear();
1700 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1701 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1704 // Set the thread stop info from the JSON dictionary
1705 SetThreadStopInfo (thread_dict);
1706 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1707 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1708 m_thread_ids.push_back(tid);
1710 return true; // Keep iterating through all thread_info objects
1713 if (!m_thread_ids.empty())
1718 // See if we can get the thread IDs from the current stop reply packets
1719 // that might contain a "threads" key/value pair
1721 // Lock the thread stack while we access it
1722 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1723 Mutex::Locker stop_stack_lock;
1724 if (stop_stack_lock.TryLock(m_last_stop_packet_mutex))
1726 // Get the number of stop packets on the stack
1727 int nItems = m_stop_packet_stack.size();
1728 // Iterate over them
1729 for (int i = 0; i < nItems; i++)
1731 // Get the thread stop info
1732 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1733 const std::string &stop_info_str = stop_info.GetStringRef();
1735 m_thread_pcs.clear();
1736 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1737 if (thread_pcs_pos != std::string::npos)
1739 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1740 const size_t end = stop_info_str.find(';', start);
1741 if (end != std::string::npos)
1743 std::string value = stop_info_str.substr(start, end - start);
1744 UpdateThreadPCsFromStopReplyThreadsValue(value);
1748 const size_t threads_pos = stop_info_str.find(";threads:");
1749 if (threads_pos != std::string::npos)
1751 const size_t start = threads_pos + strlen(";threads:");
1752 const size_t end = stop_info_str.find(';', start);
1753 if (end != std::string::npos)
1755 std::string value = stop_info_str.substr(start, end - start);
1756 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1764 bool sequence_mutex_unavailable = false;
1765 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1766 if (sequence_mutex_unavailable)
1768 return false; // We just didn't get the list
1774 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1776 // locker will keep a mutex locked until it goes out of scope
1777 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1778 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1779 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1781 size_t num_thread_ids = m_thread_ids.size();
1782 // The "m_thread_ids" thread ID list should always be updated after each stop
1783 // reply packet, but in case it isn't, update it here.
1784 if (num_thread_ids == 0)
1786 if (!UpdateThreadIDList ())
1788 num_thread_ids = m_thread_ids.size();
1791 ThreadList old_thread_list_copy(old_thread_list);
1792 if (num_thread_ids > 0)
1794 for (size_t i=0; i<num_thread_ids; ++i)
1796 tid_t tid = m_thread_ids[i];
1797 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1800 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1801 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1803 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1804 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1805 thread_sp->GetID());
1809 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1811 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1812 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1813 thread_sp->GetID());
1815 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
1816 // of the register read/write packets in gdb-remote protocol.
1817 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1818 // they are a performance improvement over fetching thread register values individually, the
1819 // method we will fall back to if needed.
1820 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1822 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1823 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1826 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
1827 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1828 if (pc_regnum != LLDB_INVALID_REGNUM)
1830 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1834 new_thread_list.AddThread(thread_sp);
1838 // Whatever that is left in old_thread_list_copy are not
1839 // present in new_thread_list. Remove non-existent threads from internal id table.
1840 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1841 for (size_t i=0; i<old_num_thread_ids; i++)
1843 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1846 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1847 m_thread_id_to_index_id_map.erase(old_thread_id);
1856 ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
1858 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1859 if (thread_infos_sp)
1861 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1865 const size_t n = thread_infos->GetSize();
1866 for (size_t i=0; i<n; ++i)
1868 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1871 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1873 if (tid == thread->GetID())
1874 return (bool)SetThreadStopInfo(thread_dict);
1884 ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1886 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1887 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1890 // See if we got thread stop info for any threads valid stop info reasons threads
1891 // via the "jstopinfo" packet stop reply packet key/value pair?
1894 // If we have "jstopinfo" then we have stop descriptions for all threads
1895 // that have stop reasons, and if there is no entry for a thread, then
1896 // it has no stop reason.
1897 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1898 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1900 thread->SetStopInfo (StopInfoSP());
1905 // Fall back to using the qThreadStopInfo packet
1906 StringExtractorGDBRemote stop_packet;
1907 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1908 return SetThreadStopInfo (stop_packet) == eStateStopped;
1914 ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1915 ExpeditedRegisterMap &expedited_register_map,
1917 const std::string &thread_name,
1918 const std::string &reason,
1919 const std::string &description,
1921 const std::vector<addr_t> &exc_data,
1922 addr_t thread_dispatch_qaddr,
1923 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1924 LazyBool associated_with_dispatch_queue,
1925 addr_t dispatch_queue_t,
1926 std::string &queue_name,
1927 QueueKind queue_kind,
1928 uint64_t queue_serial)
1931 if (tid != LLDB_INVALID_THREAD_ID)
1933 // Scope for "locker" below
1935 // m_thread_list_real does have its own mutex, but we need to
1936 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1937 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1938 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1939 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1943 // Create the thread if we need to
1944 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1945 m_thread_list_real.AddThread(thread_sp);
1951 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1952 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1954 for (const auto &pair : expedited_register_map)
1956 StringExtractor reg_value_extractor;
1957 reg_value_extractor.GetStringRef() = pair.second;
1958 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1961 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1963 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1964 // Check if the GDB server was able to provide the queue name, kind and serial number
1965 if (queue_vars_valid)
1966 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial, dispatch_queue_t, associated_with_dispatch_queue);
1968 gdb_thread->ClearQueueInfo();
1970 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
1972 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1973 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
1975 // Make sure we update our thread stop reason just once
1976 if (!thread_sp->StopInfoIsUpToDate())
1978 thread_sp->SetStopInfo (StopInfoSP());
1979 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
1980 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1981 if (memory_thread_sp)
1982 thread_sp = memory_thread_sp;
1986 const size_t exc_data_size = exc_data.size();
1988 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1991 exc_data_size >= 1 ? exc_data[0] : 0,
1992 exc_data_size >= 2 ? exc_data[1] : 0,
1993 exc_data_size >= 3 ? exc_data[2] : 0));
1997 bool handled = false;
1998 bool did_exec = false;
1999 if (!reason.empty())
2001 if (reason.compare("trace") == 0)
2003 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2006 else if (reason.compare("breakpoint") == 0)
2008 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2009 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2012 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2013 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2014 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2016 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2018 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2022 StopInfoSP invalid_stop_info_sp;
2023 thread_sp->SetStopInfo (invalid_stop_info_sp);
2027 else if (reason.compare("trap") == 0)
2029 // Let the trap just use the standard signal stop reason below...
2031 else if (reason.compare("watchpoint") == 0)
2033 StringExtractor desc_extractor(description.c_str());
2034 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2035 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
2036 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2037 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2038 if (wp_addr != LLDB_INVALID_ADDRESS)
2041 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
2042 if (core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last)
2043 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2045 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2048 wp_sp->SetHardwareIndex(wp_index);
2049 watch_id = wp_sp->GetID();
2052 if (watch_id == LLDB_INVALID_WATCH_ID)
2054 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2055 if (log) log->Printf ("failed to find watchpoint");
2057 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
2060 else if (reason.compare("exception") == 0)
2062 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2065 else if (reason.compare("exec") == 0)
2068 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2073 if (!handled && signo && did_exec == false)
2075 if (signo == SIGTRAP)
2077 // Currently we are going to assume SIGTRAP means we are either
2078 // hitting a breakpoint or hardware single stepping.
2080 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2081 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2085 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2086 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2087 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2088 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2090 if(m_breakpoint_pc_offset != 0)
2091 thread_sp->GetRegisterContext()->SetPC(pc);
2092 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2096 StopInfoSP invalid_stop_info_sp;
2097 thread_sp->SetStopInfo (invalid_stop_info_sp);
2102 // If we were stepping then assume the stop was the result of the trace. If we were
2103 // not stepping then report the SIGTRAP.
2104 // FIXME: We are still missing the case where we single step over a trap instruction.
2105 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2106 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2108 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
2112 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2115 if (!description.empty())
2117 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2120 const char *stop_info_desc = stop_info_sp->GetDescription();
2121 if (!stop_info_desc || !stop_info_desc[0])
2122 stop_info_sp->SetDescription (description.c_str());
2126 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
2137 ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2139 static ConstString g_key_tid("tid");
2140 static ConstString g_key_name("name");
2141 static ConstString g_key_reason("reason");
2142 static ConstString g_key_metype("metype");
2143 static ConstString g_key_medata("medata");
2144 static ConstString g_key_qaddr("qaddr");
2145 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2146 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
2147 static ConstString g_key_queue_name("qname");
2148 static ConstString g_key_queue_kind("qkind");
2149 static ConstString g_key_queue_serial_number("qserialnum");
2150 static ConstString g_key_registers("registers");
2151 static ConstString g_key_memory("memory");
2152 static ConstString g_key_address("address");
2153 static ConstString g_key_bytes("bytes");
2154 static ConstString g_key_description("description");
2155 static ConstString g_key_signal("signal");
2157 // Stop with signal and thread info
2158 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2161 std::string thread_name;
2163 std::string description;
2164 uint32_t exc_type = 0;
2165 std::vector<addr_t> exc_data;
2166 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2167 ExpeditedRegisterMap expedited_register_map;
2168 bool queue_vars_valid = false;
2169 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2170 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2171 std::string queue_name;
2172 QueueKind queue_kind = eQueueKindUnknown;
2173 uint64_t queue_serial_number = 0;
2174 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2176 thread_dict->ForEach([this,
2178 &expedited_register_map,
2185 &thread_dispatch_qaddr,
2187 &associated_with_dispatch_queue,
2191 &queue_serial_number]
2192 (ConstString key, StructuredData::Object* object) -> bool
2194 if (key == g_key_tid)
2196 // thread in big endian hex
2197 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2199 else if (key == g_key_metype)
2201 // exception type in big endian hex
2202 exc_type = object->GetIntegerValue(0);
2204 else if (key == g_key_medata)
2206 // exception data in big endian hex
2207 StructuredData::Array *array = object->GetAsArray();
2210 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2211 exc_data.push_back(object->GetIntegerValue());
2212 return true; // Keep iterating through all array items
2216 else if (key == g_key_name)
2218 thread_name = object->GetStringValue();
2220 else if (key == g_key_qaddr)
2222 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2224 else if (key == g_key_queue_name)
2226 queue_vars_valid = true;
2227 queue_name = object->GetStringValue();
2229 else if (key == g_key_queue_kind)
2231 std::string queue_kind_str = object->GetStringValue();
2232 if (queue_kind_str == "serial")
2234 queue_vars_valid = true;
2235 queue_kind = eQueueKindSerial;
2237 else if (queue_kind_str == "concurrent")
2239 queue_vars_valid = true;
2240 queue_kind = eQueueKindConcurrent;
2243 else if (key == g_key_queue_serial_number)
2245 queue_serial_number = object->GetIntegerValue(0);
2246 if (queue_serial_number != 0)
2247 queue_vars_valid = true;
2249 else if (key == g_key_dispatch_queue_t)
2251 dispatch_queue_t = object->GetIntegerValue(0);
2252 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2253 queue_vars_valid = true;
2255 else if (key == g_key_associated_with_dispatch_queue)
2257 queue_vars_valid = true;
2258 bool associated = object->GetBooleanValue ();
2260 associated_with_dispatch_queue = eLazyBoolYes;
2262 associated_with_dispatch_queue = eLazyBoolNo;
2264 else if (key == g_key_reason)
2266 reason = object->GetStringValue();
2268 else if (key == g_key_description)
2270 description = object->GetStringValue();
2272 else if (key == g_key_registers)
2274 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2278 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2279 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2280 if (reg != UINT32_MAX)
2281 expedited_register_map[reg] = object->GetStringValue();
2282 return true; // Keep iterating through all array items
2286 else if (key == g_key_memory)
2288 StructuredData::Array *array = object->GetAsArray();
2291 array->ForEach([this](StructuredData::Object* object) -> bool {
2292 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2295 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2296 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2298 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2300 StringExtractor bytes;
2301 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2303 bytes.SetFilePos(0);
2305 const size_t byte_size = bytes.GetStringRef().size()/2;
2306 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2307 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2308 if (bytes_copied == byte_size)
2309 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2314 return true; // Keep iterating through all array items
2319 else if (key == g_key_signal)
2320 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2321 return true; // Keep iterating through all dictionary key/value pairs
2324 return SetThreadStopInfo (tid,
2325 expedited_register_map,
2332 thread_dispatch_qaddr,
2334 associated_with_dispatch_queue,
2338 queue_serial_number);
2342 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2344 stop_packet.SetFilePos (0);
2345 const char stop_type = stop_packet.GetChar();
2351 // This is a bit of a hack, but is is required. If we did exec, we
2352 // need to clear our thread lists and also know to rebuild our dynamic
2353 // register info before we lookup and threads and populate the expedited
2354 // register values so we need to know this right away so we can cleanup
2355 // and update our registers.
2356 const uint32_t stop_id = GetStopID();
2359 // Our first stop, make sure we have a process ID, and also make
2360 // sure we know about our registers
2361 if (GetID() == LLDB_INVALID_PROCESS_ID)
2363 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
2364 if (pid != LLDB_INVALID_PROCESS_ID)
2367 BuildDynamicRegisterInfo (true);
2369 // Stop with signal and thread info
2370 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2371 const uint8_t signo = stop_packet.GetHexU8();
2374 std::string thread_name;
2376 std::string description;
2377 uint32_t exc_type = 0;
2378 std::vector<addr_t> exc_data;
2379 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2380 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2381 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2382 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2383 std::string queue_name;
2384 QueueKind queue_kind = eQueueKindUnknown;
2385 uint64_t queue_serial_number = 0;
2386 ExpeditedRegisterMap expedited_register_map;
2387 while (stop_packet.GetNameColonValue(key, value))
2389 if (key.compare("metype") == 0)
2391 // exception type in big endian hex
2392 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2394 else if (key.compare("medata") == 0)
2396 // exception data in big endian hex
2397 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
2399 else if (key.compare("thread") == 0)
2401 // thread in big endian hex
2402 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2404 else if (key.compare("threads") == 0)
2406 Mutex::Locker locker(m_thread_list_real.GetMutex());
2407 m_thread_ids.clear();
2408 // A comma separated list of all threads in the current
2409 // process that includes the thread for this stop reply
2413 while ((comma_pos = value.find(',')) != std::string::npos)
2415 value[comma_pos] = '\0';
2416 // thread in big endian hex
2417 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2418 if (tid != LLDB_INVALID_THREAD_ID)
2419 m_thread_ids.push_back (tid);
2420 value.erase(0, comma_pos + 1);
2422 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2423 if (tid != LLDB_INVALID_THREAD_ID)
2424 m_thread_ids.push_back (tid);
2426 else if (key.compare("thread-pcs") == 0)
2428 m_thread_pcs.clear();
2429 // A comma separated list of all threads in the current
2430 // process that includes the thread for this stop reply
2434 while ((comma_pos = value.find(',')) != std::string::npos)
2436 value[comma_pos] = '\0';
2437 // thread in big endian hex
2438 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2439 if (pc != LLDB_INVALID_ADDRESS)
2440 m_thread_pcs.push_back (pc);
2441 value.erase(0, comma_pos + 1);
2443 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2444 if (pc != LLDB_INVALID_ADDRESS)
2445 m_thread_pcs.push_back (pc);
2447 else if (key.compare("jstopinfo") == 0)
2449 StringExtractor json_extractor;
2450 // Swap "value" over into "name_extractor"
2451 json_extractor.GetStringRef().swap(value);
2452 // Now convert the HEX bytes into a string value
2453 json_extractor.GetHexByteString (value);
2455 // This JSON contains thread IDs and thread stop info for all threads.
2456 // It doesn't contain expedited registers, memory or queue info.
2457 m_jstopinfo_sp = StructuredData::ParseJSON (value);
2459 else if (key.compare("hexname") == 0)
2461 StringExtractor name_extractor;
2462 // Swap "value" over into "name_extractor"
2463 name_extractor.GetStringRef().swap(value);
2464 // Now convert the HEX bytes into a string value
2465 name_extractor.GetHexByteString (value);
2466 thread_name.swap (value);
2468 else if (key.compare("name") == 0)
2470 thread_name.swap (value);
2472 else if (key.compare("qaddr") == 0)
2474 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2476 else if (key.compare("dispatch_queue_t") == 0)
2478 queue_vars_valid = true;
2479 dispatch_queue_t = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2481 else if (key.compare("qname") == 0)
2483 queue_vars_valid = true;
2484 StringExtractor name_extractor;
2485 // Swap "value" over into "name_extractor"
2486 name_extractor.GetStringRef().swap(value);
2487 // Now convert the HEX bytes into a string value
2488 name_extractor.GetHexByteString (value);
2489 queue_name.swap (value);
2491 else if (key.compare("qkind") == 0)
2493 if (value == "serial")
2495 queue_vars_valid = true;
2496 queue_kind = eQueueKindSerial;
2498 else if (value == "concurrent")
2500 queue_vars_valid = true;
2501 queue_kind = eQueueKindConcurrent;
2504 else if (key.compare("qserialnum") == 0)
2506 queue_serial_number = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2507 if (queue_serial_number != 0)
2508 queue_vars_valid = true;
2510 else if (key.compare("reason") == 0)
2514 else if (key.compare("description") == 0)
2516 StringExtractor desc_extractor;
2517 // Swap "value" over into "name_extractor"
2518 desc_extractor.GetStringRef().swap(value);
2519 // Now convert the HEX bytes into a string value
2520 desc_extractor.GetHexByteString (value);
2521 description.swap(value);
2523 else if (key.compare("memory") == 0)
2525 // Expedited memory. GDB servers can choose to send back expedited memory
2526 // that can populate the L1 memory cache in the process so that things like
2527 // the frame pointer backchain can be expedited. This will help stack
2528 // backtracing be more efficient by not having to send as many memory read
2529 // requests down the remote GDB server.
2531 // Key/value pair format: memory:<addr>=<bytes>;
2532 // <addr> is a number whose base will be interpreted by the prefix:
2533 // "0x[0-9a-fA-F]+" for hex
2534 // "0[0-7]+" for octal
2535 // "[1-9]+" for decimal
2536 // <bytes> is native endian ASCII hex bytes just like the register values
2537 llvm::StringRef value_ref(value);
2538 std::pair<llvm::StringRef, llvm::StringRef> pair;
2539 pair = value_ref.split('=');
2540 if (!pair.first.empty() && !pair.second.empty())
2542 std::string addr_str(pair.first.str());
2543 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2544 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2546 StringExtractor bytes;
2547 bytes.GetStringRef() = pair.second.str();
2548 const size_t byte_size = bytes.GetStringRef().size()/2;
2549 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2550 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2551 if (bytes_copied == byte_size)
2552 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2556 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2558 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2559 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2560 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2561 uint32_t wp_index = LLDB_INVALID_INDEX32;
2564 wp_index = wp_sp->GetHardwareIndex();
2566 reason = "watchpoint";
2568 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2569 description = ostr.GetString().c_str();
2571 else if (key.compare("library") == 0)
2575 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2577 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2578 if (reg != UINT32_MAX)
2579 expedited_register_map[reg] = std::move(value);
2583 if (tid == LLDB_INVALID_THREAD_ID)
2585 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2586 // thread information. So update the thread list and choose the first one.
2587 UpdateThreadIDList ();
2589 if (!m_thread_ids.empty ())
2591 tid = m_thread_ids.front ();
2595 ThreadSP thread_sp = SetThreadStopInfo (tid,
2596 expedited_register_map,
2603 thread_dispatch_qaddr,
2605 associated_with_dispatch_queue,
2609 queue_serial_number);
2611 return eStateStopped;
2618 return eStateExited;
2623 return eStateInvalid;
2627 ProcessGDBRemote::RefreshStateAfterStop ()
2629 Mutex::Locker locker(m_thread_list_real.GetMutex());
2630 m_thread_ids.clear();
2631 m_thread_pcs.clear();
2632 // Set the thread stop info. It might have a "threads" key whose value is
2633 // a list of all thread IDs in the current process, so m_thread_ids might
2636 // Scope for the lock
2638 // Lock the thread stack while we access it
2639 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2640 // Get the number of stop packets on the stack
2641 int nItems = m_stop_packet_stack.size();
2642 // Iterate over them
2643 for (int i = 0; i < nItems; i++)
2645 // Get the thread stop info
2646 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2647 // Process thread stop info
2648 SetThreadStopInfo(stop_info);
2650 // Clear the thread stop stack
2651 m_stop_packet_stack.clear();
2654 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2655 if (m_thread_ids.empty())
2657 // No, we need to fetch the thread list manually
2658 UpdateThreadIDList();
2661 // If we have queried for a default thread id
2662 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2664 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2665 m_initial_tid = LLDB_INVALID_THREAD_ID;
2668 // Let all threads recover from stopping and do any clean up based
2669 // on the previous thread state (if any).
2670 m_thread_list_real.RefreshStateAfterStop();
2675 ProcessGDBRemote::DoHalt (bool &caused_stop)
2679 bool timed_out = false;
2680 Mutex::Locker locker;
2682 if (m_public_state.GetValue() == eStateAttaching)
2684 // We are being asked to halt during an attach. We need to just close
2685 // our file handle and debugserver will go away, and we can be done...
2686 m_gdb_comm.Disconnect();
2690 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
2693 error.SetErrorString("timed out sending interrupt packet");
2695 error.SetErrorString("unknown error sending interrupt packet");
2698 caused_stop = m_gdb_comm.GetInterruptWasSent ();
2704 ProcessGDBRemote::DoDetach(bool keep_stopped)
2707 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2709 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2711 error = m_gdb_comm.Detach (keep_stopped);
2714 if (error.Success())
2715 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2717 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
2720 if (!error.Success())
2723 // Sleep for one second to let the process get all detached...
2726 SetPrivateState (eStateDetached);
2727 ResumePrivateStateThread();
2729 //KillDebugserverProcess ();
2735 ProcessGDBRemote::DoDestroy ()
2738 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2740 log->Printf ("ProcessGDBRemote::DoDestroy()");
2742 #if 0 // XXX Currently no iOS target support on FreeBSD
2743 // There is a bug in older iOS debugservers where they don't shut down the process
2744 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2745 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2746 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2747 // destroy it again.
2749 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2750 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2751 // the debugservers with this bug are equal. There really should be a better way to test this!
2753 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2754 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2755 // just do the straight-forward kill.
2757 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2758 // necessary (or helpful) to do any of this.
2760 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2762 PlatformSP platform_sp = GetTarget().GetPlatform();
2764 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2766 && platform_sp->GetName()
2767 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
2769 if (m_destroy_tried_resuming)
2772 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
2776 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2777 // but we really need it to happen here and it doesn't matter if we do it twice.
2778 m_thread_list.DiscardThreadPlans();
2779 DisableAllBreakpointSites();
2781 bool stop_looks_like_crash = false;
2782 ThreadList &threads = GetThreadList();
2785 Mutex::Locker locker(threads.GetMutex());
2787 size_t num_threads = threads.GetSize();
2788 for (size_t i = 0; i < num_threads; i++)
2790 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2791 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2792 StopReason reason = eStopReasonInvalid;
2794 reason = stop_info_sp->GetStopReason();
2795 if (reason == eStopReasonBreakpoint
2796 || reason == eStopReasonException)
2799 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2800 thread_sp->GetProtocolID(),
2801 stop_info_sp->GetDescription());
2802 stop_looks_like_crash = true;
2808 if (stop_looks_like_crash)
2811 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2812 m_destroy_tried_resuming = true;
2814 // If we are going to run again before killing, it would be good to suspend all the threads
2815 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2816 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2817 // have to run the risk of letting those threads proceed a bit.
2820 Mutex::Locker locker(threads.GetMutex());
2822 size_t num_threads = threads.GetSize();
2823 for (size_t i = 0; i < num_threads; i++)
2825 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2826 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2827 StopReason reason = eStopReasonInvalid;
2829 reason = stop_info_sp->GetStopReason();
2830 if (reason != eStopReasonBreakpoint
2831 && reason != eStopReasonException)
2834 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2835 thread_sp->GetProtocolID());
2836 thread_sp->SetResumeState(eStateSuspended);
2841 return Destroy(false);
2848 // Interrupt if our inferior is running...
2849 int exit_status = SIGABRT;
2850 std::string exit_string;
2852 if (m_gdb_comm.IsConnected())
2854 if (m_public_state.GetValue() != eStateAttaching)
2856 StringExtractorGDBRemote response;
2857 bool send_async = true;
2858 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
2860 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2862 char packet_cmd = response.GetChar(0);
2864 if (packet_cmd == 'W' || packet_cmd == 'X')
2866 #if defined(__APPLE__)
2867 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2868 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2869 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2870 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2871 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2872 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2873 // Anyway, so call waitpid here to finally reap it.
2874 PlatformSP platform_sp(GetTarget().GetPlatform());
2875 if (platform_sp && platform_sp->IsHost())
2879 reap_pid = waitpid (GetID(), &status, WNOHANG);
2881 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2884 SetLastStopPacket (response);
2885 ClearThreadIDList ();
2886 exit_status = response.GetHexU8();
2891 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2892 exit_string.assign("got unexpected response to k packet: ");
2893 exit_string.append(response.GetStringRef());
2899 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2900 exit_string.assign("failed to send the k packet");
2906 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
2907 exit_string.assign ("killed or interrupted while attaching.");
2912 // If we missed setting the exit status on the way out, do it here.
2913 // NB set exit status can be called multiple times, the first one sets the status.
2914 exit_string.assign("destroying when not connected to debugserver");
2917 SetExitStatus(exit_status, exit_string.c_str());
2920 KillDebugserverProcess ();
2925 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2927 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2930 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2932 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2934 m_thread_list_real.Clear();
2935 m_thread_list.Clear();
2936 BuildDynamicRegisterInfo (true);
2937 m_gdb_comm.ResetDiscoverableSettings (did_exec);
2942 // Lock the thread stack while we access it
2943 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2945 // We are are not using non-stop mode, there can only be one last stop
2946 // reply packet, so clear the list.
2947 if (GetTarget().GetNonStopModeEnabled() == false)
2948 m_stop_packet_stack.clear();
2950 // Add this stop packet to the stop packet stack
2951 // This stack will get popped and examined when we switch to the
2953 m_stop_packet_stack.push_back(response);
2958 ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2960 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2963 //------------------------------------------------------------------
2965 //------------------------------------------------------------------
2968 ProcessGDBRemote::IsAlive ()
2970 return m_gdb_comm.IsConnected() && Process::IsAlive();
2974 ProcessGDBRemote::GetImageInfoAddress()
2976 // request the link map address via the $qShlibInfoAddr packet
2977 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2979 // the loaded module list can also provides a link map address
2980 if (addr == LLDB_INVALID_ADDRESS)
2982 LoadedModuleInfoList list;
2983 if (GetLoadedModuleList (list).Success())
2984 addr = list.m_link_map;
2991 ProcessGDBRemote::WillPublicStop ()
2993 // See if the GDB remote client supports the JSON threads info.
2994 // If so, we gather stop info for all threads, expedited registers,
2995 // expedited memory, runtime queue information (iOS and MacOSX only),
2996 // and more. Expediting memory will help stack backtracing be much
2997 // faster. Expediting registers will make sure we don't have to read
2998 // the thread registers for GPRs.
2999 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3001 if (m_jthreadsinfo_sp)
3003 // Now set the stop info for each thread and also expedite any registers
3004 // and memory that was in the jThreadsInfo response.
3005 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3008 const size_t n = thread_infos->GetSize();
3009 for (size_t i=0; i<n; ++i)
3011 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3013 SetThreadStopInfo(thread_dict);
3019 //------------------------------------------------------------------
3021 //------------------------------------------------------------------
3023 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3025 GetMaxMemorySize ();
3026 if (size > m_max_memory_size)
3028 // Keep memory read sizes down to a sane limit. This function will be
3029 // called multiple times in order to complete the task by
3030 // lldb_private::Process so it is ok to do this.
3031 size = m_max_memory_size;
3036 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
3037 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3038 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
3039 assert (packet_len + 1 < (int)sizeof(packet));
3040 StringExtractorGDBRemote response;
3041 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
3043 if (response.IsNormalResponse())
3046 if (binary_memory_read)
3048 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3049 // 0x7d character escaping that was present in the packet
3051 size_t data_received_size = response.GetBytesLeft();
3052 if (data_received_size > size)
3054 // Don't write past the end of BUF if the remote debug server gave us too
3055 // much data for some reason.
3056 data_received_size = size;
3058 memcpy (buf, response.GetStringRef().data(), data_received_size);
3059 return data_received_size;
3063 return response.GetHexBytes(buf, size, '\xdd');
3066 else if (response.IsErrorResponse())
3067 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
3068 else if (response.IsUnsupportedResponse())
3069 error.SetErrorStringWithFormat("GDB server does not support reading memory");
3071 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
3075 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
3081 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3083 GetMaxMemorySize ();
3084 if (size > m_max_memory_size)
3086 // Keep memory read sizes down to a sane limit. This function will be
3087 // called multiple times in order to complete the task by
3088 // lldb_private::Process so it is ok to do this.
3089 size = m_max_memory_size;
3092 StreamString packet;
3093 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3094 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
3095 StringExtractorGDBRemote response;
3096 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
3098 if (response.IsOKResponse())
3103 else if (response.IsErrorResponse())
3104 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
3105 else if (response.IsUnsupportedResponse())
3106 error.SetErrorStringWithFormat("GDB server does not support writing memory");
3108 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
3112 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
3118 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3120 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
3121 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3123 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3126 case eLazyBoolCalculate:
3128 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3129 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3130 return allocated_addr;
3133 // Call mmap() to create memory in the inferior..
3135 if (permissions & lldb::ePermissionsReadable)
3136 prot |= eMmapProtRead;
3137 if (permissions & lldb::ePermissionsWritable)
3138 prot |= eMmapProtWrite;
3139 if (permissions & lldb::ePermissionsExecutable)
3140 prot |= eMmapProtExec;
3142 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3143 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3144 m_addr_to_mmap_size[allocated_addr] = size;
3147 allocated_addr = LLDB_INVALID_ADDRESS;
3149 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3154 if (allocated_addr == LLDB_INVALID_ADDRESS)
3155 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
3158 return allocated_addr;
3162 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3163 MemoryRegionInfo ®ion_info)
3166 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3171 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3174 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3179 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3181 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
3186 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3189 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3193 case eLazyBoolCalculate:
3194 // We should never be deallocating memory without allocating memory
3195 // first so we should never get eLazyBoolCalculate
3196 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3200 if (!m_gdb_comm.DeallocateMemory (addr))
3201 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
3205 // Call munmap() to deallocate memory in the inferior..
3207 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3208 if (pos != m_addr_to_mmap_size.end() &&
3209 InferiorCallMunmap(this, addr, pos->second))
3210 m_addr_to_mmap_size.erase (pos);
3212 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
3221 //------------------------------------------------------------------
3223 //------------------------------------------------------------------
3225 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3227 if (m_stdio_communication.IsConnected())
3229 ConnectionStatus status;
3230 m_stdio_communication.Write(src, src_len, status, NULL);
3232 else if (m_stdin_forward)
3234 m_gdb_comm.SendStdinNotification(src, src_len);
3240 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
3243 assert(bp_site != NULL);
3246 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3247 user_id_t site_id = bp_site->GetID();
3249 // Get the breakpoint address
3250 const addr_t addr = bp_site->GetLoadAddress();
3252 // Log that a breakpoint was requested
3254 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3256 // Breakpoint already exists and is enabled
3257 if (bp_site->IsEnabled())
3260 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
3264 // Get the software breakpoint trap opcode size
3265 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3267 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3268 // is supported by the remote stub. These are set to true by default, and later set to false
3269 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3270 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3271 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3272 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3273 // skip over software breakpoints.
3274 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3276 // Try to send off a software breakpoint packet ($Z0)
3277 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
3279 // The breakpoint was placed successfully
3280 bp_site->SetEnabled(true);
3281 bp_site->SetType(BreakpointSite::eExternal);
3285 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3286 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3287 // or if we have learned that this breakpoint type is unsupported. To do this, we
3288 // must test the support boolean for this breakpoint type to see if it now indicates that
3289 // this breakpoint type is unsupported. If they are still supported then we should return
3290 // with the error code. If they are now unsupported, then we would like to fall through
3291 // and try another form of breakpoint.
3292 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3295 // We reach here when software breakpoints have been found to be unsupported. For future
3296 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3297 // known not to be supported.
3299 log->Printf("Software breakpoints are unsupported");
3301 // So we will fall through and try a hardware breakpoint
3304 // The process of setting a hardware breakpoint is much the same as above. We check the
3305 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3306 // will try to set this breakpoint with a hardware breakpoint.
3307 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3309 // Try to send off a hardware breakpoint packet ($Z1)
3310 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
3312 // The breakpoint was placed successfully
3313 bp_site->SetEnabled(true);
3314 bp_site->SetType(BreakpointSite::eHardware);
3318 // Check if the error was something other then an unsupported breakpoint type
3319 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3321 // Unable to set this hardware breakpoint
3322 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3326 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
3328 log->Printf("Hardware breakpoints are unsupported");
3330 // Finally we will falling through to a #trap style breakpoint
3333 // Don't fall through when hardware breakpoints were specifically requested
3334 if (bp_site->HardwareRequired())
3336 error.SetErrorString("hardware breakpoints are not supported");
3340 // As a last resort we want to place a manual breakpoint. An instruction
3341 // is placed into the process memory using memory write packets.
3342 return EnableSoftwareBreakpoint(bp_site);
3346 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
3349 assert (bp_site != NULL);
3350 addr_t addr = bp_site->GetLoadAddress();
3351 user_id_t site_id = bp_site->GetID();
3352 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3354 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
3356 if (bp_site->IsEnabled())
3358 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3360 BreakpointSite::Type bp_type = bp_site->GetType();
3363 case BreakpointSite::eSoftware:
3364 error = DisableSoftwareBreakpoint (bp_site);
3367 case BreakpointSite::eHardware:
3368 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
3369 error.SetErrorToGenericError();
3372 case BreakpointSite::eExternal:
3374 GDBStoppointType stoppoint_type;
3375 if (bp_site->IsHardware())
3376 stoppoint_type = eBreakpointHardware;
3378 stoppoint_type = eBreakpointSoftware;
3380 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
3381 error.SetErrorToGenericError();
3385 if (error.Success())
3386 bp_site->SetEnabled(false);
3391 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
3395 if (error.Success())
3396 error.SetErrorToGenericError();
3400 // Pre-requisite: wp != NULL.
3401 static GDBStoppointType
3402 GetGDBStoppointType (Watchpoint *wp)
3405 bool watch_read = wp->WatchpointRead();
3406 bool watch_write = wp->WatchpointWrite();
3408 // watch_read and watch_write cannot both be false.
3409 assert(watch_read || watch_write);
3410 if (watch_read && watch_write)
3411 return eWatchpointReadWrite;
3412 else if (watch_read)
3413 return eWatchpointRead;
3414 else // Must be watch_write, then.
3415 return eWatchpointWrite;
3419 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
3424 user_id_t watchID = wp->GetID();
3425 addr_t addr = wp->GetLoadAddress();
3426 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3428 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
3429 if (wp->IsEnabled())
3432 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
3436 GDBStoppointType type = GetGDBStoppointType(wp);
3437 // Pass down an appropriate z/Z packet...
3438 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
3440 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3442 wp->SetEnabled(true, notify);
3446 error.SetErrorString("sending gdb watchpoint packet failed");
3449 error.SetErrorString("watchpoints not supported");
3453 error.SetErrorString("Watchpoint argument was NULL.");
3455 if (error.Success())
3456 error.SetErrorToGenericError();
3461 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
3466 user_id_t watchID = wp->GetID();
3468 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3470 addr_t addr = wp->GetLoadAddress();
3473 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
3475 if (!wp->IsEnabled())
3478 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
3479 // See also 'class WatchpointSentry' within StopInfo.cpp.
3480 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3481 // the watchpoint object to intelligently process this action.
3482 wp->SetEnabled(false, notify);
3486 if (wp->IsHardware())
3488 GDBStoppointType type = GetGDBStoppointType(wp);
3489 // Pass down an appropriate z/Z packet...
3490 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3492 wp->SetEnabled(false, notify);
3496 error.SetErrorString("sending gdb watchpoint packet failed");
3498 // TODO: clear software watchpoints if we implement them
3502 error.SetErrorString("Watchpoint argument was NULL.");
3504 if (error.Success())
3505 error.SetErrorToGenericError();
3510 ProcessGDBRemote::Clear()
3513 m_thread_list_real.Clear();
3514 m_thread_list.Clear();
3518 ProcessGDBRemote::DoSignal (int signo)
3521 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3523 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3525 if (!m_gdb_comm.SendAsyncSignal (signo))
3526 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3531 ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3533 // Make sure we aren't already connected?
3534 if (m_gdb_comm.IsConnected())
3537 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3538 if (platform_sp && !platform_sp->IsHost ())
3539 return Error("Lost debug server connection");
3541 auto error = LaunchAndConnectToDebugserver (process_info);
3544 const char *error_string = error.AsCString();
3545 if (error_string == nullptr)
3546 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3552 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
3555 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3557 // If we locate debugserver, keep that located version around
3558 static FileSpec g_debugserver_file_spec;
3560 ProcessLaunchInfo debugserver_launch_info;
3561 // Make debugserver run in its own session so signals generated by
3562 // special terminal key sequences (^C) don't affect debugserver.
3563 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3565 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3566 debugserver_launch_info.SetUserID(process_info.GetUserID());
3568 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
3569 // On iOS, still do a local connection using a random port
3570 const char *hostname = "127.0.0.1";
3571 uint16_t port = get_random_port ();
3573 // Set hostname being NULL to do the reverse connect where debugserver
3574 // will bind to port zero and it will communicate back to us the port
3575 // that we will connect to
3576 const char *hostname = nullptr;
3580 StreamString url_str;
3581 const char* url = nullptr;
3582 if (hostname != nullptr)
3584 url_str.Printf("%s:%u", hostname, port);
3585 url = url_str.GetData();
3588 error = m_gdb_comm.StartDebugserverProcess (url,
3589 GetTarget().GetPlatform().get(),
3590 debugserver_launch_info,
3593 if (error.Success ())
3594 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3596 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3598 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3599 StartAsyncThread ();
3603 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3606 log->Printf("failed to start debugserver process: %s", error.AsCString());
3610 if (m_gdb_comm.IsConnected())
3612 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3613 ConnectToDebugserver (NULL);
3617 StreamString connect_url;
3618 connect_url.Printf("connect://%s:%u", hostname, port);
3619 error = ConnectToDebugserver (connect_url.GetString().c_str());
3627 ProcessGDBRemote::MonitorDebugserverProcess
3629 void *callback_baton,
3630 lldb::pid_t debugserver_pid,
3631 bool exited, // True if the process did exit
3632 int signo, // Zero for no signal
3633 int exit_status // Exit value of process if signal is zero
3636 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3637 // and might not exist anymore, so we need to carefully try to get the
3638 // target for this process first since we have a race condition when
3639 // we are done running between getting the notice that the inferior
3640 // process has died and the debugserver that was debugging this process.
3641 // In our test suite, we are also continually running process after
3642 // process, so we must be very careful to make sure:
3643 // 1 - process object hasn't been deleted already
3644 // 2 - that a new process object hasn't been recreated in its place
3646 // "debugserver_pid" argument passed in is the process ID for
3647 // debugserver that we are tracking...
3648 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3650 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
3652 // Get a shared pointer to the target that has a matching process pointer.
3653 // This target could be gone, or the target could already have a new process
3654 // object inside of it
3655 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3658 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
3662 // We found a process in a target that matches, but another thread
3663 // might be in the process of launching a new process that will
3664 // soon replace it, so get a shared pointer to the process so we
3665 // can keep it alive.
3666 ProcessSP process_sp (target_sp->GetProcessSP());
3667 // Now we have a shared pointer to the process that can't go away on us
3668 // so we now make sure it was the same as the one passed in, and also make
3669 // sure that our previous "process *" didn't get deleted and have a new
3670 // "process *" created in its place with the same pointer. To verify this
3671 // we make sure the process has our debugserver process ID. If we pass all
3672 // of these tests, then we are sure that this process is the one we were
3674 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
3676 // Sleep for a half a second to make sure our inferior process has
3677 // time to set its exit status before we set it incorrectly when
3678 // both the debugserver and the inferior process shut down.
3680 // If our process hasn't yet exited, debugserver might have died.
3681 // If the process did exit, the we are reaping it.
3682 const StateType state = process->GetState();
3684 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3685 state != eStateInvalid &&
3686 state != eStateUnloaded &&
3687 state != eStateExited &&
3688 state != eStateDetached)
3690 char error_str[1024];
3693 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
3695 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3697 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3701 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3704 process->SetExitStatus (-1, error_str);
3706 // Debugserver has exited we need to let our ProcessGDBRemote
3707 // know that it no longer has a debugserver instance
3708 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3715 ProcessGDBRemote::KillDebugserverProcess ()
3717 m_gdb_comm.Disconnect();
3718 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3720 Host::Kill (m_debugserver_pid, SIGINT);
3721 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3726 ProcessGDBRemote::Initialize()
3728 static std::once_flag g_once_flag;
3730 std::call_once(g_once_flag, []()
3732 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3733 GetPluginDescriptionStatic(),
3735 DebuggerInitialize);
3740 ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
3742 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3744 const bool is_global_setting = true;
3745 PluginManager::CreateSettingForProcessPlugin (debugger,
3746 GetGlobalPluginProperties()->GetValueProperties(),
3747 ConstString ("Properties for the gdb-remote process plug-in."),
3753 ProcessGDBRemote::StartAsyncThread ()
3755 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3758 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3760 Mutex::Locker start_locker(m_async_thread_state_mutex);
3761 if (!m_async_thread.IsJoinable())
3763 // Create a thread that watches our internal state and controls which
3764 // events make it to clients (into the DCProcess event queue).
3766 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
3769 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
3771 return m_async_thread.IsJoinable();
3775 ProcessGDBRemote::StopAsyncThread ()
3777 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3780 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3782 Mutex::Locker start_locker(m_async_thread_state_mutex);
3783 if (m_async_thread.IsJoinable())
3785 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3787 // This will shut down the async thread.
3788 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3790 // Stop the stdio thread
3791 m_async_thread.Join(nullptr);
3792 m_async_thread.Reset();
3795 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
3799 ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3801 // get the packet at a string
3802 const std::string &pkt = packet.GetStringRef();
3804 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3806 // pass as a thread stop info packet
3807 SetLastStopPacket(stop_info);
3809 // check for more stop reasons
3810 HandleStopReplySequence();
3812 // if the process is stopped then we need to fake a resume
3813 // so that we can stop properly with the new break. This
3814 // is possible due to SetPrivateState() broadcasting the
3815 // state change as a side effect.
3816 if (GetPrivateState() == lldb::StateType::eStateStopped)
3818 SetPrivateState(lldb::StateType::eStateRunning);
3821 // since we have some stopped packets we can halt the process
3822 SetPrivateState(lldb::StateType::eStateStopped);
3828 ProcessGDBRemote::AsyncThread (void *arg)
3830 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3832 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3834 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
3841 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3842 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
3844 const uint32_t event_type = event_sp->GetType();
3845 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
3848 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3852 case eBroadcastBitAsyncContinue:
3854 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3856 if (continue_packet)
3858 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3859 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3861 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3863 if (::strstr (continue_cstr, "vAttach") == NULL)
3864 process->SetPrivateState(eStateRunning);
3865 StringExtractorGDBRemote response;
3867 // If in Non-Stop-Mode
3868 if (process->GetTarget().GetNonStopModeEnabled())
3870 // send the vCont packet
3871 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3873 // Something went wrong
3878 // If in All-Stop-Mode
3881 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3883 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3884 // The thread ID list might be contained within the "response", or the stop reply packet that
3885 // caused the stop. So clear it now before we give the stop reply packet to the process
3886 // using the process->SetLastStopPacket()...
3887 process->ClearThreadIDList ();
3893 case eStateSuspended:
3894 process->SetLastStopPacket (response);
3895 process->SetPrivateState (stop_state);
3900 process->SetLastStopPacket (response);
3901 process->ClearThreadIDList();
3902 response.SetFilePos(1);
3904 int exit_status = response.GetHexU8();
3905 const char *desc_cstr = NULL;
3906 StringExtractor extractor;
3907 std::string desc_string;
3908 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3910 std::string desc_token;
3911 while (response.GetNameColonValue (desc_token, desc_string))
3913 if (desc_token == "description")
3915 extractor.GetStringRef().swap(desc_string);
3916 extractor.SetFilePos(0);
3917 extractor.GetHexByteString (desc_string);
3918 desc_cstr = desc_string.c_str();
3922 process->SetExitStatus(exit_status, desc_cstr);
3928 // Check to see if we were trying to attach and if we got back
3929 // the "E87" error code from debugserver -- this indicates that
3930 // the process is not debuggable. Return a slightly more helpful
3931 // error message about why the attach failed.
3932 if (::strstr (continue_cstr, "vAttach") != NULL
3933 && response.GetError() == 0x87)
3935 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3937 // E01 code from vAttach means that the attach failed
3938 if (::strstr (continue_cstr, "vAttach") != NULL
3939 && response.GetError() == 0x1)
3941 process->SetExitStatus(-1, "unable to attach");
3945 process->SetExitStatus(-1, "lost connection");
3951 process->SetPrivateState (stop_state);
3953 } // switch(stop_state)
3954 } // else // if in All-stop-mode
3955 } // if (continue_packet)
3956 } // case eBroadcastBitAysncContinue
3959 case eBroadcastBitAsyncThreadShouldExit:
3961 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3967 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3972 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3976 case Communication::eBroadcastBitReadThreadDidExit:
3977 process->SetExitStatus (-1, "lost connection");
3981 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3983 lldb_private::Event *event = event_sp.get();
3984 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3985 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3986 // Hand this over to the process to handle
3987 process->HandleNotifyPacket(notify);
3993 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4002 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4008 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
4014 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4016 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4017 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4018 // if (m_local_debugserver)
4020 // return Host::ListProcessesMatchingName (name, matches, pids);
4024 // // FIXME: Implement talking to the remote debugserver.
4031 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
4032 StoppointCallbackContext *context,
4033 lldb::user_id_t break_id,
4034 lldb::user_id_t break_loc_id)
4036 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
4037 // run so I can stop it if that's what I want to do.
4038 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
4040 log->Printf("Hit New Thread Notification breakpoint.");
4046 ProcessGDBRemote::StartNoticingNewThreads()
4048 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
4049 if (m_thread_create_bp_sp)
4051 if (log && log->GetVerbose())
4052 log->Printf("Enabled noticing new thread breakpoint.");
4053 m_thread_create_bp_sp->SetEnabled(true);
4057 PlatformSP platform_sp (GetTarget().GetPlatform());
4060 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
4061 if (m_thread_create_bp_sp)
4063 if (log && log->GetVerbose())
4064 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4065 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
4070 log->Printf("Failed to create new thread notification breakpoint.");
4074 return m_thread_create_bp_sp.get() != NULL;
4078 ProcessGDBRemote::StopNoticingNewThreads()
4080 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
4081 if (log && log->GetVerbose())
4082 log->Printf ("Disabling new thread notification breakpoint.");
4084 if (m_thread_create_bp_sp)
4085 m_thread_create_bp_sp->SetEnabled(false);
4091 ProcessGDBRemote::GetDynamicLoader ()
4093 if (m_dyld_ap.get() == NULL)
4094 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
4095 return m_dyld_ap.get();
4099 ProcessGDBRemote::SendEventData(const char *data)
4106 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4107 if (return_value != 0)
4110 error.SetErrorString("Sending events is not supported for this process.");
4112 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4118 ProcessGDBRemote::GetAuxvData()
4121 if (m_gdb_comm.GetQXferAuxvReadSupported())
4123 std::string response_string;
4124 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4125 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4130 StructuredData::ObjectSP
4131 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4133 StructuredData::ObjectSP object_sp;
4135 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4137 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4138 SystemRuntime *runtime = GetSystemRuntime();
4141 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4143 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4145 StreamString packet;
4146 packet << "jThreadExtendedInfo:";
4147 args_dict->Dump (packet);
4149 // FIXME the final character of a JSON dictionary, '}', is the escape
4150 // character in gdb-remote binary mode. lldb currently doesn't escape
4151 // these characters in its packet output -- so we add the quoted version
4152 // of the } character here manually in case we talk to a debugserver which
4153 // un-escapes the characters at packet read time.
4154 packet << (char) (0x7d ^ 0x20);
4156 StringExtractorGDBRemote response;
4157 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4159 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4160 if (response_type == StringExtractorGDBRemote::eResponse)
4162 if (!response.Empty())
4164 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4172 StructuredData::ObjectSP
4173 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4175 StructuredData::ObjectSP object_sp;
4177 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4179 // Scope for the scoped timeout object
4180 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4182 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4183 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4184 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4186 StreamString packet;
4187 packet << "jGetLoadedDynamicLibrariesInfos:";
4188 args_dict->Dump (packet);
4190 // FIXME the final character of a JSON dictionary, '}', is the escape
4191 // character in gdb-remote binary mode. lldb currently doesn't escape
4192 // these characters in its packet output -- so we add the quoted version
4193 // of the } character here manually in case we talk to a debugserver which
4194 // un-escapes the characters at packet read time.
4195 packet << (char) (0x7d ^ 0x20);
4197 StringExtractorGDBRemote response;
4198 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4200 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4201 if (response_type == StringExtractorGDBRemote::eResponse)
4203 if (!response.Empty())
4205 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4213 // Establish the largest memory read/write payloads we should use.
4214 // If the remote stub has a max packet size, stay under that size.
4216 // If the remote stub's max packet size is crazy large, use a
4217 // reasonable largeish default.
4219 // If the remote stub doesn't advertise a max packet size, use a
4220 // conservative default.
4223 ProcessGDBRemote::GetMaxMemorySize()
4225 const uint64_t reasonable_largeish_default = 128 * 1024;
4226 const uint64_t conservative_default = 512;
4228 if (m_max_memory_size == 0)
4230 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4231 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4233 // Save the stub's claimed maximum packet size
4234 m_remote_stub_max_memory_size = stub_max_size;
4236 // Even if the stub says it can support ginormous packets,
4237 // don't exceed our reasonable largeish default packet size.
4238 if (stub_max_size > reasonable_largeish_default)
4240 stub_max_size = reasonable_largeish_default;
4243 m_max_memory_size = stub_max_size;
4247 m_max_memory_size = conservative_default;
4253 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4255 if (user_specified_max != 0)
4257 GetMaxMemorySize ();
4259 if (m_remote_stub_max_memory_size != 0)
4261 if (m_remote_stub_max_memory_size < user_specified_max)
4263 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4264 // as the remote stub says we can go.
4268 m_max_memory_size = user_specified_max; // user's packet size is good
4273 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4279 ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4280 const ArchSpec& arch,
4281 ModuleSpec &module_spec)
4283 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4285 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4288 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4289 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4290 arch.GetTriple ().getTriple ().c_str ());
4296 StreamString stream;
4297 module_spec.Dump (stream);
4298 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4299 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4300 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4307 ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4311 if (m_gdb_comm.GetOSVersion(major, minor, update))
4313 // We failed to get the host OS version, defer to the base
4314 // implementation to correctly invalidate the arguments.
4315 return Process::GetHostOSVersion(major, minor, update);
4320 typedef std::vector<std::string> stringVec;
4322 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4323 struct RegisterSetInfo
4328 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4330 struct GdbServerTargetInfo
4335 RegisterSetMap reg_set_map;
4336 XMLNode feature_node;
4340 ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
4345 uint32_t cur_reg_num = 0;
4346 uint32_t reg_offset = 0;
4348 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &cur_reg_num, ®_offset, &abi_sp](const XMLNode ®_node) -> bool {
4349 std::string gdb_group;
4350 std::string gdb_type;
4351 ConstString reg_name;
4352 ConstString alt_name;
4353 ConstString set_name;
4354 std::vector<uint32_t> value_regs;
4355 std::vector<uint32_t> invalidate_regs;
4356 bool encoding_set = false;
4357 bool format_set = false;
4358 RegisterInfo reg_info = { NULL, // Name
4361 reg_offset, // offset
4362 eEncodingUint, // encoding
4363 eFormatHex, // format
4365 LLDB_INVALID_REGNUM, // eh_frame reg num
4366 LLDB_INVALID_REGNUM, // DWARF reg num
4367 LLDB_INVALID_REGNUM, // generic reg num
4368 cur_reg_num, // process plugin reg num
4369 cur_reg_num // native register number
4375 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, ®_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, ®_info, &cur_reg_num, ®_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4378 reg_name.SetString(value);
4380 else if (name == "bitsize")
4382 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4384 else if (name == "type")
4386 gdb_type = value.str();
4388 else if (name == "group")
4390 gdb_group = value.str();
4392 else if (name == "regnum")
4394 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4395 if (regnum != LLDB_INVALID_REGNUM)
4397 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4400 else if (name == "offset")
4402 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4404 else if (name == "altname")
4406 alt_name.SetString(value);
4408 else if (name == "encoding")
4410 encoding_set = true;
4411 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4413 else if (name == "format")
4416 Format format = eFormatInvalid;
4417 if (Args::StringToFormat (value.data(), format, NULL).Success())
4418 reg_info.format = format;
4419 else if (value == "vector-sint8")
4420 reg_info.format = eFormatVectorOfSInt8;
4421 else if (value == "vector-uint8")
4422 reg_info.format = eFormatVectorOfUInt8;
4423 else if (value == "vector-sint16")
4424 reg_info.format = eFormatVectorOfSInt16;
4425 else if (value == "vector-uint16")
4426 reg_info.format = eFormatVectorOfUInt16;
4427 else if (value == "vector-sint32")
4428 reg_info.format = eFormatVectorOfSInt32;
4429 else if (value == "vector-uint32")
4430 reg_info.format = eFormatVectorOfUInt32;
4431 else if (value == "vector-float32")
4432 reg_info.format = eFormatVectorOfFloat32;
4433 else if (value == "vector-uint128")
4434 reg_info.format = eFormatVectorOfUInt128;
4436 else if (name == "group_id")
4438 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4439 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4440 if (pos != target_info.reg_set_map.end())
4441 set_name = pos->second.name;
4443 else if (name == "gcc_regnum" || name == "ehframe_regnum")
4445 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4447 else if (name == "dwarf_regnum")
4449 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4451 else if (name == "generic")
4453 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4455 else if (name == "value_regnums")
4457 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4459 else if (name == "invalidate_regnums")
4461 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4465 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4467 return true; // Keep iterating through all attributes
4470 if (!gdb_type.empty() && !(encoding_set || format_set))
4472 if (gdb_type.find("int") == 0)
4474 reg_info.format = eFormatHex;
4475 reg_info.encoding = eEncodingUint;
4477 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4479 reg_info.format = eFormatAddressInfo;
4480 reg_info.encoding = eEncodingUint;
4482 else if (gdb_type == "i387_ext" || gdb_type == "float")
4484 reg_info.format = eFormatFloat;
4485 reg_info.encoding = eEncodingIEEE754;
4489 // Only update the register set name if we didn't get a "reg_set" attribute.
4490 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4491 if (!set_name && !gdb_group.empty())
4492 set_name.SetCString(gdb_group.c_str());
4494 reg_info.byte_offset = reg_offset;
4495 assert (reg_info.byte_size != 0);
4496 reg_offset += reg_info.byte_size;
4497 if (!value_regs.empty())
4499 value_regs.push_back(LLDB_INVALID_REGNUM);
4500 reg_info.value_regs = value_regs.data();
4502 if (!invalidate_regs.empty())
4504 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4505 reg_info.invalidate_regs = invalidate_regs.data();
4509 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
4510 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4512 return true; // Keep iterating through all "reg" elements
4520 // query the target of gdb-remote for extended target information
4521 // return: 'true' on success
4522 // 'false' on failure
4524 ProcessGDBRemote::GetGDBServerRegisterInfo ()
4526 // Make sure LLDB has an XML parser it can use first
4527 if (!XMLDocument::XMLEnabled())
4530 // redirect libxml2's error handler since the default prints to stdout
4532 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4534 // check that we have extended feature read support
4535 if ( !comm.GetQXferFeaturesReadSupported( ) )
4538 // request the target xml file
4540 lldb_private::Error lldberr;
4541 if (!comm.ReadExtFeature(ConstString("features"),
4542 ConstString("target.xml"),
4550 XMLDocument xml_document;
4552 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
4554 GdbServerTargetInfo target_info;
4556 XMLNode target_node = xml_document.GetRootElement("target");
4559 XMLNode feature_node;
4560 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4562 llvm::StringRef name = node.GetName();
4563 if (name == "architecture")
4565 node.GetElementText(target_info.arch);
4567 else if (name == "osabi")
4569 node.GetElementText(target_info.osabi);
4571 else if (name == "xi:include" || name == "include")
4573 llvm::StringRef href = node.GetAttributeValue("href");
4575 target_info.includes.push_back(href.str());
4577 else if (name == "feature")
4579 feature_node = node;
4581 else if (name == "groups")
4583 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4584 uint32_t set_id = UINT32_MAX;
4585 RegisterSetInfo set_info;
4587 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4589 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4591 set_info.name = ConstString(value);
4592 return true; // Keep iterating through all attributes
4595 if (set_id != UINT32_MAX)
4596 target_info.reg_set_map[set_id] = set_info;
4597 return true; // Keep iterating through all "group" elements
4600 return true; // Keep iterating through all children of the target_node
4605 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
4608 for (const auto &include : target_info.includes)
4610 // request register file
4611 std::string xml_data;
4612 if (!comm.ReadExtFeature(ConstString("features"),
4613 ConstString(include),
4618 XMLDocument include_xml_document;
4619 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4620 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4621 if (include_feature_node)
4623 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
4626 this->m_register_info.Finalize(GetTarget().GetArchitecture());
4630 return m_register_info.GetNumRegisters() > 0;
4634 ProcessGDBRemote::GetLoadedModuleList (LoadedModuleInfoList & list)
4636 // Make sure LLDB has an XML parser it can use first
4637 if (!XMLDocument::XMLEnabled())
4638 return Error (0, ErrorType::eErrorTypeGeneric);
4640 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4642 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4644 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4646 // check that we have extended feature read support
4647 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4650 // request the loaded library list
4652 lldb_private::Error lldberr;
4654 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4655 return Error (0, ErrorType::eErrorTypeGeneric);
4657 // parse the xml file in memory
4659 log->Printf ("parsing: %s", raw.c_str());
4662 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4663 return Error (0, ErrorType::eErrorTypeGeneric);
4665 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4669 // main link map structure
4670 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4671 if (!main_lm.empty())
4673 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4676 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4678 LoadedModuleInfoList::LoadedModuleInfo module;
4680 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4683 module.set_name (value.str());
4684 else if (name == "lm")
4686 // the address of the link_map struct.
4687 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4689 else if (name == "l_addr")
4691 // the displacement as read from the field 'l_addr' of the link_map struct.
4692 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4693 // base address is always a displacement, not an absolute value.
4694 module.set_base_is_offset(true);
4696 else if (name == "l_ld")
4698 // the memory address of the libraries PT_DYAMIC section.
4699 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4702 return true; // Keep iterating over all properties of "library"
4708 lldb::addr_t lm=0, base=0, ld=0;
4709 bool base_is_offset;
4711 module.get_name (name);
4712 module.get_link_map (lm);
4713 module.get_base (base);
4714 module.get_base_is_offset (base_is_offset);
4715 module.get_dynamic (ld);
4717 log->Printf ("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 "[%s], ld:0x%08" PRIx64 ", name:'%s')", lm, base, (base_is_offset ? "offset" : "absolute"), ld, name.c_str());
4721 return true; // Keep iterating over all "library" elements in the root node
4725 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4726 } else if (comm.GetQXferLibrariesReadSupported ()) {
4729 // request the loaded library list
4731 lldb_private::Error lldberr;
4733 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4734 return Error (0, ErrorType::eErrorTypeGeneric);
4737 log->Printf ("parsing: %s", raw.c_str());
4740 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4741 return Error (0, ErrorType::eErrorTypeGeneric);
4743 XMLNode root_element = doc.GetRootElement("library-list");
4747 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4748 LoadedModuleInfoList::LoadedModuleInfo module;
4750 llvm::StringRef name = library.GetAttributeValue("name");
4751 module.set_name(name.str());
4753 // The base address of a given library will be the address of its
4754 // first section. Most remotes send only one section for Windows
4755 // targets for example.
4756 const XMLNode §ion = library.FindFirstChildElementWithName("section");
4757 llvm::StringRef address = section.GetAttributeValue("address");
4758 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4759 // These addresses are absolute values.
4760 module.set_base_is_offset(false);
4765 lldb::addr_t base = 0;
4766 bool base_is_offset;
4767 module.get_name (name);
4768 module.get_base (base);
4769 module.get_base_is_offset (base_is_offset);
4771 log->Printf ("found (base:0x%08" PRIx64 "[%s], name:'%s')", base, (base_is_offset ? "offset" : "absolute"), name.c_str());
4775 return true; // Keep iterating over all "library" elements in the root node
4779 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4781 return Error (0, ErrorType::eErrorTypeGeneric);
4788 ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
4790 Target &target = m_process->GetTarget();
4791 ModuleList &modules = target.GetImages();
4794 bool changed = false;
4796 ModuleSpec module_spec (file, target.GetArchitecture());
4797 if ((module_sp = modules.FindFirstModule (module_spec)))
4799 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
4801 else if ((module_sp = target.GetSharedModule (module_spec)))
4803 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
4810 ProcessGDBRemote::LoadModules (LoadedModuleInfoList &module_list)
4812 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4814 // request a list of loaded libraries from GDBServer
4815 if (GetLoadedModuleList (module_list).Fail())
4818 // get a list of all the modules
4819 ModuleList new_modules;
4821 for (LoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4823 std::string mod_name;
4824 lldb::addr_t mod_base;
4825 bool mod_base_is_offset;
4828 valid &= modInfo.get_name (mod_name);
4829 valid &= modInfo.get_base (mod_base);
4830 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
4834 // hack (cleaner way to get file name only?) (win/unix compat?)
4835 size_t marker = mod_name.rfind ('/');
4836 if (marker == std::string::npos)
4841 FileSpec file (mod_name.c_str()+marker, true);
4842 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
4844 if (module_sp.get())
4845 new_modules.Append (module_sp);
4848 if (new_modules.GetSize() > 0)
4850 Target &target = GetTarget();
4852 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4854 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4858 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4861 lldb::ModuleSP module_copy_sp = module_sp;
4862 target.SetExecutableModule (module_copy_sp, false);
4866 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4867 loaded_modules.AppendIfNeeded (new_modules);
4868 m_process->GetTarget().ModulesDidLoad (new_modules);
4871 return new_modules.GetSize();
4876 ProcessGDBRemote::LoadModules ()
4878 LoadedModuleInfoList module_list;
4879 return LoadModules (module_list);
4883 ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4886 load_addr = LLDB_INVALID_ADDRESS;
4888 std::string file_path = file.GetPath(false);
4889 if (file_path.empty ())
4890 return Error("Empty file name specified");
4892 StreamString packet;
4893 packet.PutCString("qFileLoadAddress:");
4894 packet.PutCStringAsRawHex8(file_path.c_str());
4896 StringExtractorGDBRemote response;
4897 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4898 return Error("Sending qFileLoadAddress packet failed");
4900 if (response.IsErrorResponse())
4902 if (response.GetError() == 1)
4904 // The file is not loaded into the inferior
4906 load_addr = LLDB_INVALID_ADDRESS;
4910 return Error("Fetching file load address from remote server returned an error");
4913 if (response.IsNormalResponse())
4916 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4920 return Error("Unknown error happened during sending the load address packet");
4925 ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4927 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4928 Process::ModulesDidLoad (module_list);
4930 // After loading shared libraries, we can ask our remote GDB server if
4931 // it needs any symbols.
4932 m_gdb_comm.ServeSymbolLookups(this);
4936 class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4939 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4940 CommandObjectParsed (interpreter,
4941 "process plugin packet speed-test",
4942 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4944 m_option_group (interpreter),
4945 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000),
4946 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4947 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4948 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4950 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4951 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4952 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4953 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4954 m_option_group.Finalize();
4957 ~CommandObjectProcessGDBRemoteSpeedTest ()
4963 GetOptions () override
4965 return &m_option_group;
4969 DoExecute (Args& command, CommandReturnObject &result) override
4971 const size_t argc = command.GetArgumentCount();
4974 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4977 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4978 result.SetImmediateOutputStream (output_stream_sp);
4980 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4981 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4982 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4983 const bool json = m_json.GetOptionValue().GetCurrentValue();
4984 if (output_stream_sp)
4985 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4988 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4990 result.SetStatus (eReturnStatusSuccessFinishResult);
4996 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4998 result.SetStatus (eReturnStatusFailed);
5002 OptionGroupOptions m_option_group;
5003 OptionGroupUInt64 m_num_packets;
5004 OptionGroupUInt64 m_max_send;
5005 OptionGroupUInt64 m_max_recv;
5006 OptionGroupBoolean m_json;
5010 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
5015 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
5016 CommandObjectParsed (interpreter,
5017 "process plugin packet history",
5018 "Dumps the packet history buffer. ",
5023 ~CommandObjectProcessGDBRemotePacketHistory ()
5028 DoExecute (Args& command, CommandReturnObject &result) override
5030 const size_t argc = command.GetArgumentCount();
5033 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5036 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5037 result.SetStatus (eReturnStatusSuccessFinishResult);
5043 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5045 result.SetStatus (eReturnStatusFailed);
5050 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5055 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5056 CommandObjectParsed (interpreter,
5057 "process plugin packet xfer-size",
5058 "Maximum size that lldb will try to read/write one one chunk.",
5063 ~CommandObjectProcessGDBRemotePacketXferSize ()
5068 DoExecute (Args& command, CommandReturnObject &result) override
5070 const size_t argc = command.GetArgumentCount();
5073 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5074 result.SetStatus (eReturnStatusFailed);
5078 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5081 const char *packet_size = command.GetArgumentAtIndex(0);
5083 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5084 if (errno == 0 && user_specified_max != 0)
5086 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5087 result.SetStatus (eReturnStatusSuccessFinishResult);
5091 result.SetStatus (eReturnStatusFailed);
5097 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5102 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5103 CommandObjectParsed (interpreter,
5104 "process plugin packet send",
5105 "Send a custom packet through the GDB remote protocol and print the answer. "
5106 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5111 ~CommandObjectProcessGDBRemotePacketSend ()
5116 DoExecute (Args& command, CommandReturnObject &result) override
5118 const size_t argc = command.GetArgumentCount();
5121 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5122 result.SetStatus (eReturnStatusFailed);
5126 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5129 for (size_t i=0; i<argc; ++ i)
5131 const char *packet_cstr = command.GetArgumentAtIndex(0);
5132 bool send_async = true;
5133 StringExtractorGDBRemote response;
5134 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5135 result.SetStatus (eReturnStatusSuccessFinishResult);
5136 Stream &output_strm = result.GetOutputStream();
5137 output_strm.Printf (" packet: %s\n", packet_cstr);
5138 std::string &response_str = response.GetStringRef();
5140 if (strstr(packet_cstr, "qGetProfileData") != NULL)
5142 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5145 if (response_str.empty())
5146 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5148 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5155 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5160 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5161 CommandObjectRaw (interpreter,
5162 "process plugin packet monitor",
5163 "Send a qRcmd packet through the GDB remote protocol and print the response."
5164 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
5169 ~CommandObjectProcessGDBRemotePacketMonitor ()
5174 DoExecute (const char *command, CommandReturnObject &result) override
5176 if (command == NULL || command[0] == '\0')
5178 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5179 result.SetStatus (eReturnStatusFailed);
5183 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5186 StreamString packet;
5187 packet.PutCString("qRcmd,");
5188 packet.PutBytesAsRawHex8(command, strlen(command));
5189 const char *packet_cstr = packet.GetString().c_str();
5191 bool send_async = true;
5192 StringExtractorGDBRemote response;
5193 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5194 result.SetStatus (eReturnStatusSuccessFinishResult);
5195 Stream &output_strm = result.GetOutputStream();
5196 output_strm.Printf (" packet: %s\n", packet_cstr);
5197 const std::string &response_str = response.GetStringRef();
5199 if (response_str.empty())
5200 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5202 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5208 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5213 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5214 CommandObjectMultiword (interpreter,
5215 "process plugin packet",
5216 "Commands that deal with GDB remote packets.",
5219 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5220 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
5221 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
5222 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
5223 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
5226 ~CommandObjectProcessGDBRemotePacket ()
5231 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5234 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5235 CommandObjectMultiword (interpreter,
5237 "A set of commands for operating on a ProcessGDBRemote process.",
5238 "process plugin <subcommand> [<subcommand-options>]")
5240 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5243 ~CommandObjectMultiwordProcessGDBRemote ()
5249 ProcessGDBRemote::GetPluginCommandObject()
5252 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5253 return m_command_sp.get();