LLDB  mainline
ProcessGDBRemote.cpp
Go to the documentation of this file.
1 //===-- ProcessGDBRemote.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/Config.h"
10 
11 #include <cerrno>
12 #include <cstdlib>
13 #if LLDB_ENABLE_POSIX
14 #include <netinet/in.h>
15 #include <sys/mman.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18 #endif
19 #include <sys/stat.h>
20 #if defined(__APPLE__)
21 #include <sys/sysctl.h>
22 #endif
23 #include <ctime>
24 #include <sys/types.h>
25 
27 #include "lldb/Core/Debugger.h"
28 #include "lldb/Core/Module.h"
29 #include "lldb/Core/ModuleSpec.h"
31 #include "lldb/Core/StreamFile.h"
32 #include "lldb/Core/Value.h"
35 #include "lldb/Host/FileSystem.h"
36 #include "lldb/Host/HostThread.h"
37 #include "lldb/Host/PosixApi.h"
40 #include "lldb/Host/XML.h"
52 #include "lldb/Symbol/ObjectFile.h"
53 #include "lldb/Target/ABI.h"
57 #include "lldb/Target/Target.h"
58 #include "lldb/Target/TargetList.h"
60 #include "lldb/Utility/Args.h"
61 #include "lldb/Utility/FileSpec.h"
63 #include "lldb/Utility/State.h"
65 #include "lldb/Utility/Timer.h"
66 #include <algorithm>
67 #include <csignal>
68 #include <map>
69 #include <memory>
70 #include <mutex>
71 #include <sstream>
72 #include <thread>
73 
80 #include "ProcessGDBRemote.h"
81 #include "ProcessGDBRemoteLog.h"
82 #include "ThreadGDBRemote.h"
83 #include "lldb/Host/Host.h"
85 
86 #include "llvm/ADT/ScopeExit.h"
87 #include "llvm/ADT/StringSwitch.h"
88 #include "llvm/Support/Threading.h"
89 #include "llvm/Support/raw_ostream.h"
90 
91 #define DEBUGSERVER_BASENAME "debugserver"
92 using namespace lldb;
93 using namespace lldb_private;
94 using namespace lldb_private::process_gdb_remote;
95 
97 
98 namespace lldb {
99 // Provide a function that can easily dump the packet history if we know a
100 // ProcessGDBRemote * value (which we can get from logs or from debugging). We
101 // need the function in the lldb namespace so it makes it into the final
102 // executable since the LLDB shared library only exports stuff in the lldb
103 // namespace. This allows you to attach with a debugger and call this function
104 // and get the packet history dumped to a file.
105 void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
106  auto file = FileSystem::Instance().Open(
107  FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
108  if (!file) {
109  llvm::consumeError(file.takeError());
110  return;
111  }
112  StreamFile stream(std::move(file.get()));
113  ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
114 }
115 } // namespace lldb
116 
117 namespace {
118 
119 #define LLDB_PROPERTIES_processgdbremote
120 #include "ProcessGDBRemoteProperties.inc"
121 
122 enum {
123 #define LLDB_PROPERTIES_processgdbremote
124 #include "ProcessGDBRemotePropertiesEnum.inc"
125 };
126 
127 class PluginProperties : public Properties {
128 public:
129  static ConstString GetSettingName() {
130  return ConstString(ProcessGDBRemote::GetPluginNameStatic());
131  }
132 
133  PluginProperties() : Properties() {
134  m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135  m_collection_sp->Initialize(g_processgdbremote_properties);
136  }
137 
138  ~PluginProperties() override = default;
139 
140  uint64_t GetPacketTimeout() {
141  const uint32_t idx = ePropertyPacketTimeout;
142  return m_collection_sp->GetPropertyAtIndexAsUInt64(
143  nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
144  }
145 
146  bool SetPacketTimeout(uint64_t timeout) {
147  const uint32_t idx = ePropertyPacketTimeout;
148  return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
149  }
150 
151  FileSpec GetTargetDefinitionFile() const {
152  const uint32_t idx = ePropertyTargetDefinitionFile;
153  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
154  }
155 
156  bool GetUseSVR4() const {
157  const uint32_t idx = ePropertyUseSVR4;
158  return m_collection_sp->GetPropertyAtIndexAsBoolean(
159  nullptr, idx,
160  g_processgdbremote_properties[idx].default_uint_value != 0);
161  }
162 
163  bool GetUseGPacketForReading() const {
164  const uint32_t idx = ePropertyUseGPacketForReading;
165  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
166  }
167 };
168 
169 static PluginProperties &GetGlobalPluginProperties() {
170  static PluginProperties g_settings;
171  return g_settings;
172 }
173 
174 } // namespace
175 
176 // TODO Randomly assigning a port is unsafe. We should get an unused
177 // ephemeral port from the kernel and make sure we reserve it before passing it
178 // to debugserver.
179 
180 #if defined(__APPLE__)
181 #define LOW_PORT (IPPORT_RESERVED)
182 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
183 #else
184 #define LOW_PORT (1024u)
185 #define HIGH_PORT (49151u)
186 #endif
187 
188 llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
189  return "GDB Remote protocol based debugging plug-in.";
190 }
191 
192 void ProcessGDBRemote::Terminate() {
193  PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
194 }
195 
196 lldb::ProcessSP
197 ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
198  ListenerSP listener_sp,
199  const FileSpec *crash_file_path,
200  bool can_connect) {
201  lldb::ProcessSP process_sp;
202  if (crash_file_path == nullptr)
203  process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
204  return process_sp;
205 }
206 
207 std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
208  return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
209 }
210 
211 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
212  bool plugin_specified_by_name) {
213  if (plugin_specified_by_name)
214  return true;
215 
216  // For now we are just making sure the file exists for a given module
217  Module *exe_module = target_sp->GetExecutableModulePointer();
218  if (exe_module) {
219  ObjectFile *exe_objfile = exe_module->GetObjectFile();
220  // We can't debug core files...
221  switch (exe_objfile->GetType()) {
222  case ObjectFile::eTypeInvalid:
223  case ObjectFile::eTypeCoreFile:
224  case ObjectFile::eTypeDebugInfo:
225  case ObjectFile::eTypeObjectFile:
226  case ObjectFile::eTypeSharedLibrary:
227  case ObjectFile::eTypeStubLibrary:
228  case ObjectFile::eTypeJIT:
229  return false;
230  case ObjectFile::eTypeExecutable:
231  case ObjectFile::eTypeDynamicLinker:
232  case ObjectFile::eTypeUnknown:
233  break;
234  }
235  return FileSystem::Instance().Exists(exe_module->GetFileSpec());
236  }
237  // However, if there is no executable module, we return true since we might
238  // be preparing to attach.
239  return true;
240 }
241 
242 // ProcessGDBRemote constructor
243 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
244  ListenerSP listener_sp)
245  : Process(target_sp, listener_sp),
246  m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
247  m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
248  m_async_listener_sp(
249  Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
250  m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
251  m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
252  m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
253  m_max_memory_size(0), m_remote_stub_max_memory_size(0),
254  m_addr_to_mmap_size(), m_thread_create_bp_sp(),
255  m_waiting_for_attach(false), m_destroy_tried_resuming(false),
256  m_command_sp(), m_breakpoint_pc_offset(0),
257  m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
258  m_erased_flash_ranges(), m_vfork_in_progress(false) {
260  "async thread should exit");
262  "async thread continue");
264  "async thread did exit");
265 
266  if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
267  repro::GDBRemoteProvider &provider =
268  g->GetOrCreate<repro::GDBRemoteProvider>();
270  }
271 
273 
274  const uint32_t async_event_mask =
276 
277  if (m_async_listener_sp->StartListeningForEvents(
278  &m_async_broadcaster, async_event_mask) != async_event_mask) {
279  LLDB_LOGF(log,
280  "ProcessGDBRemote::%s failed to listen for "
281  "m_async_broadcaster events",
282  __FUNCTION__);
283  }
284 
285  const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit;
286  if (m_async_listener_sp->StartListeningForEvents(
287  &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
288  LLDB_LOGF(log,
289  "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
290  __FUNCTION__);
291  }
292 
293  const uint64_t timeout_seconds =
294  GetGlobalPluginProperties().GetPacketTimeout();
295  if (timeout_seconds > 0)
296  m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
297 
299  GetGlobalPluginProperties().GetUseGPacketForReading();
300 }
301 
302 // Destructor
304  // m_mach_process.UnregisterNotificationCallbacks (this);
305  Clear();
306  // We need to call finalize on the process before destroying ourselves to
307  // make sure all of the broadcaster cleanup goes as planned. If we destruct
308  // this class, then Process::~Process() might have problems trying to fully
309  // destroy the broadcaster.
310  Finalize();
311 
312  // The general Finalize is going to try to destroy the process and that
313  // SHOULD shut down the async thread. However, if we don't kill it it will
314  // get stranded and its connection will go away so when it wakes up it will
315  // crash. So kill it for sure here.
316  StopAsyncThread();
318 }
319 
321  const FileSpec &target_definition_fspec) {
322  ScriptInterpreter *interpreter =
324  Status error;
325  StructuredData::ObjectSP module_object_sp(
326  interpreter->LoadPluginModule(target_definition_fspec, error));
327  if (module_object_sp) {
328  StructuredData::DictionarySP target_definition_sp(
329  interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
330  "gdb-server-target-definition", error));
331 
332  if (target_definition_sp) {
333  StructuredData::ObjectSP target_object(
334  target_definition_sp->GetValueForKey("host-info"));
335  if (target_object) {
336  if (auto host_info_dict = target_object->GetAsDictionary()) {
337  StructuredData::ObjectSP triple_value =
338  host_info_dict->GetValueForKey("triple");
339  if (auto triple_string_value = triple_value->GetAsString()) {
340  std::string triple_string =
341  std::string(triple_string_value->GetValue());
342  ArchSpec host_arch(triple_string.c_str());
343  if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
344  GetTarget().SetArchitecture(host_arch);
345  }
346  }
347  }
348  }
350  StructuredData::ObjectSP breakpoint_pc_offset_value =
351  target_definition_sp->GetValueForKey("breakpoint-pc-offset");
352  if (breakpoint_pc_offset_value) {
353  if (auto breakpoint_pc_int_value =
354  breakpoint_pc_offset_value->GetAsInteger())
355  m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
356  }
357 
358  if (m_register_info_sp->SetRegisterInfo(
359  *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
360  return true;
361  }
362  }
363  }
364  return false;
365 }
366 
368  const llvm::StringRef &comma_separated_register_numbers,
369  std::vector<uint32_t> &regnums, int base) {
370  regnums.clear();
371  for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
372  uint32_t reg;
373  if (llvm::to_integer(x, reg, base))
374  regnums.push_back(reg);
375  }
376  return regnums.size();
377 }
378 
380  if (!force && m_register_info_sp)
381  return;
382 
383  m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
384 
385  // Check if qHostInfo specified a specific packet timeout for this
386  // connection. If so then lets update our setting so the user knows what the
387  // timeout is and can see it.
388  const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
389  if (host_packet_timeout > std::chrono::seconds(0)) {
390  GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
391  }
392 
393  // Register info search order:
394  // 1 - Use the target definition python file if one is specified.
395  // 2 - If the target definition doesn't have any of the info from the
396  // target.xml (registers) then proceed to read the target.xml.
397  // 3 - Fall back on the qRegisterInfo packets.
398  // 4 - Use hardcoded defaults if available.
399 
400  FileSpec target_definition_fspec =
401  GetGlobalPluginProperties().GetTargetDefinitionFile();
402  if (!FileSystem::Instance().Exists(target_definition_fspec)) {
403  // If the filename doesn't exist, it may be a ~ not having been expanded -
404  // try to resolve it.
405  FileSystem::Instance().Resolve(target_definition_fspec);
406  }
407  if (target_definition_fspec) {
408  // See if we can get register definitions from a python file
409  if (ParsePythonTargetDefinition(target_definition_fspec)) {
410  return;
411  } else {
412  StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
413  stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
414  target_definition_fspec.GetPath().c_str());
415  }
416  }
417 
418  const ArchSpec &target_arch = GetTarget().GetArchitecture();
419  const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
420  const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
421 
422  // Use the process' architecture instead of the host arch, if available
423  ArchSpec arch_to_use;
424  if (remote_process_arch.IsValid())
425  arch_to_use = remote_process_arch;
426  else
427  arch_to_use = remote_host_arch;
428 
429  if (!arch_to_use.IsValid())
430  arch_to_use = target_arch;
431 
432  if (GetGDBServerRegisterInfo(arch_to_use))
433  return;
434 
435  char packet[128];
436  std::vector<DynamicRegisterInfo::Register> registers;
437  uint32_t reg_num = 0;
438  for (StringExtractorGDBRemote::ResponseType response_type =
440  response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
441  const int packet_len =
442  ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
443  assert(packet_len < (int)sizeof(packet));
444  UNUSED_IF_ASSERT_DISABLED(packet_len);
445  StringExtractorGDBRemote response;
446  if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
448  response_type = response.GetResponseType();
449  if (response_type == StringExtractorGDBRemote::eResponse) {
450  llvm::StringRef name;
451  llvm::StringRef value;
453 
454  while (response.GetNameColonValue(name, value)) {
455  if (name.equals("name")) {
456  reg_info.name.SetString(value);
457  } else if (name.equals("alt-name")) {
458  reg_info.alt_name.SetString(value);
459  } else if (name.equals("bitsize")) {
460  if (!value.getAsInteger(0, reg_info.byte_size))
461  reg_info.byte_size /= CHAR_BIT;
462  } else if (name.equals("offset")) {
463  value.getAsInteger(0, reg_info.byte_offset);
464  } else if (name.equals("encoding")) {
465  const Encoding encoding = Args::StringToEncoding(value);
466  if (encoding != eEncodingInvalid)
467  reg_info.encoding = encoding;
468  } else if (name.equals("format")) {
469  if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
470  .Success())
471  reg_info.format =
472  llvm::StringSwitch<Format>(value)
473  .Case("binary", eFormatBinary)
474  .Case("decimal", eFormatDecimal)
475  .Case("hex", eFormatHex)
476  .Case("float", eFormatFloat)
477  .Case("vector-sint8", eFormatVectorOfSInt8)
478  .Case("vector-uint8", eFormatVectorOfUInt8)
479  .Case("vector-sint16", eFormatVectorOfSInt16)
480  .Case("vector-uint16", eFormatVectorOfUInt16)
481  .Case("vector-sint32", eFormatVectorOfSInt32)
482  .Case("vector-uint32", eFormatVectorOfUInt32)
483  .Case("vector-float32", eFormatVectorOfFloat32)
484  .Case("vector-uint64", eFormatVectorOfUInt64)
485  .Case("vector-uint128", eFormatVectorOfUInt128)
486  .Default(eFormatInvalid);
487  } else if (name.equals("set")) {
488  reg_info.set_name.SetString(value);
489  } else if (name.equals("gcc") || name.equals("ehframe")) {
490  value.getAsInteger(0, reg_info.regnum_ehframe);
491  } else if (name.equals("dwarf")) {
492  value.getAsInteger(0, reg_info.regnum_dwarf);
493  } else if (name.equals("generic")) {
495  } else if (name.equals("container-regs")) {
497  } else if (name.equals("invalidate-regs")) {
499  }
500  }
501 
502  assert(reg_info.byte_size != 0);
503  registers.push_back(reg_info);
504  } else {
505  break; // ensure exit before reg_num is incremented
506  }
507  } else {
508  break;
509  }
510  }
511 
512  if (registers.empty())
513  registers = GetFallbackRegisters(arch_to_use);
514 
515  AddRemoteRegisters(registers, arch_to_use);
516 }
517 
519  return WillLaunchOrAttach();
520 }
521 
523  return WillLaunchOrAttach();
524 }
525 
527  bool wait_for_launch) {
528  return WillLaunchOrAttach();
529 }
530 
531 Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
532  Log *log = GetLog(GDBRLog::Process);
533 
535  if (error.Fail())
536  return error;
537 
538  error = ConnectToDebugserver(remote_url);
539  if (error.Fail())
540  return error;
541 
543 
545  if (pid == LLDB_INVALID_PROCESS_ID) {
546  // We don't have a valid process ID, so note that we are connected and
547  // could now request to launch or attach, or get remote process listings...
549  } else {
550  // We have a valid process
551  SetID(pid);
552  GetThreadList();
553  StringExtractorGDBRemote response;
554  if (m_gdb_comm.GetStopReply(response)) {
555  SetLastStopPacket(response);
556 
557  Target &target = GetTarget();
558  if (!target.GetArchitecture().IsValid()) {
561  } else {
564  }
565  }
566  }
567 
568  // The remote stub may know about the "main binary" in
569  // the context of a firmware debug session, and can
570  // give us a UUID and an address/slide of where the
571  // binary is loaded in memory.
572  UUID standalone_uuid;
573  addr_t standalone_value;
574  bool standalone_value_is_offset;
576  standalone_uuid, standalone_value, standalone_value_is_offset)) {
577  ModuleSP module_sp;
578 
579  if (standalone_uuid.IsValid()) {
580  ModuleSpec module_spec;
581  module_spec.GetUUID() = standalone_uuid;
582 
583  // Look up UUID in global module cache before attempting
584  // a more expensive search.
585  Status error = ModuleList::GetSharedModule(module_spec, module_sp,
586  nullptr, nullptr, nullptr);
587 
588  if (!module_sp) {
589  // Force a an external lookup, if that tool is available.
590  if (!module_spec.GetSymbolFileSpec())
591  Symbols::DownloadObjectAndSymbolFile(module_spec, true);
592 
593  if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
594  module_sp = std::make_shared<Module>(module_spec);
595  }
596  }
597 
598  // If we couldn't find the binary anywhere else, as a last resort,
599  // read it out of memory.
600  if (!module_sp.get() && standalone_value != LLDB_INVALID_ADDRESS &&
601  !standalone_value_is_offset) {
602  char namebuf[80];
603  snprintf(namebuf, sizeof(namebuf), "mem-image-0x%" PRIx64,
604  standalone_value);
605  module_sp =
606  ReadModuleFromMemory(FileSpec(namebuf), standalone_value);
607  }
608 
610  if (module_sp.get()) {
611  target.GetImages().AppendIfNeeded(module_sp, false);
612 
613  bool changed = false;
614  if (module_sp->GetObjectFile()) {
615  if (standalone_value != LLDB_INVALID_ADDRESS) {
616  if (log)
617  log->Printf("Loading binary UUID %s at %s 0x%" PRIx64,
618  standalone_uuid.GetAsString().c_str(),
619  standalone_value_is_offset ? "offset" : "address",
620  standalone_value);
621  module_sp->SetLoadAddress(target, standalone_value,
622  standalone_value_is_offset, changed);
623  } else {
624  // No address/offset/slide, load the binary at file address,
625  // offset 0.
626  if (log)
627  log->Printf("Loading binary UUID %s at file address",
628  standalone_uuid.GetAsString().c_str());
629  const bool value_is_slide = true;
630  module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
631  }
632  } else {
633  // In-memory image, load at its true address, offset 0.
634  if (log)
635  log->Printf("Loading binary UUID %s from memory",
636  standalone_uuid.GetAsString().c_str());
637  const bool value_is_slide = true;
638  module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
639  }
640 
641  ModuleList added_module;
642  added_module.Append(module_sp, false);
643  target.ModulesDidLoad(added_module);
644  } else {
645  if (log)
646  log->Printf("Unable to find binary with UUID %s and load it at "
647  "%s 0x%" PRIx64,
648  standalone_uuid.GetAsString().c_str(),
649  standalone_value_is_offset ? "offset" : "address",
650  standalone_value);
651  }
652  }
653  }
654 
655  const StateType state = SetThreadStopInfo(response);
656  if (state != eStateInvalid) {
657  SetPrivateState(state);
658  } else
659  error.SetErrorStringWithFormat(
660  "Process %" PRIu64 " was reported after connecting to "
661  "'%s', but state was not stopped: %s",
662  pid, remote_url.str().c_str(), StateAsCString(state));
663  } else
664  error.SetErrorStringWithFormat("Process %" PRIu64
665  " was reported after connecting to '%s', "
666  "but no stop reply packet was received",
667  pid, remote_url.str().c_str());
668  }
669 
670  LLDB_LOGF(log,
671  "ProcessGDBRemote::%s pid %" PRIu64
672  ": normalizing target architecture initial triple: %s "
673  "(GetTarget().GetArchitecture().IsValid() %s, "
674  "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
675  __FUNCTION__, GetID(),
676  GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
677  GetTarget().GetArchitecture().IsValid() ? "true" : "false",
678  m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
679 
680  if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
682  // Prefer the *process'* architecture over that of the *host*, if
683  // available.
686  else
688  }
689 
690  LLDB_LOGF(log,
691  "ProcessGDBRemote::%s pid %" PRIu64
692  ": normalized target architecture triple: %s",
693  __FUNCTION__, GetID(),
694  GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
695 
696  return error;
697 }
698 
700  Status error;
702  return error;
703 }
704 
705 // Process Control
707  ProcessLaunchInfo &launch_info) {
709  Status error;
710 
711  LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
712 
713  uint32_t launch_flags = launch_info.GetFlags().Get();
714  FileSpec stdin_file_spec{};
715  FileSpec stdout_file_spec{};
716  FileSpec stderr_file_spec{};
717  FileSpec working_dir = launch_info.GetWorkingDirectory();
718 
719  const FileAction *file_action;
720  file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
721  if (file_action) {
722  if (file_action->GetAction() == FileAction::eFileActionOpen)
723  stdin_file_spec = file_action->GetFileSpec();
724  }
725  file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
726  if (file_action) {
727  if (file_action->GetAction() == FileAction::eFileActionOpen)
728  stdout_file_spec = file_action->GetFileSpec();
729  }
730  file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
731  if (file_action) {
732  if (file_action->GetAction() == FileAction::eFileActionOpen)
733  stderr_file_spec = file_action->GetFileSpec();
734  }
735 
736  if (log) {
737  if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
738  LLDB_LOGF(log,
739  "ProcessGDBRemote::%s provided with STDIO paths via "
740  "launch_info: stdin=%s, stdout=%s, stderr=%s",
741  __FUNCTION__,
742  stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
743  stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
744  stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
745  else
746  LLDB_LOGF(log,
747  "ProcessGDBRemote::%s no STDIO paths given via launch_info",
748  __FUNCTION__);
749  }
750 
751  const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
752  if (stdin_file_spec || disable_stdio) {
753  // the inferior will be reading stdin from the specified file or stdio is
754  // completely disabled
755  m_stdin_forward = false;
756  } else {
757  m_stdin_forward = true;
758  }
759 
760  // ::LogSetBitMask (GDBR_LOG_DEFAULT);
761  // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
762  // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
763  // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
764  // ::LogSetLogFile ("/dev/stdout");
765 
766  error = EstablishConnectionIfNeeded(launch_info);
767  if (error.Success()) {
768  PseudoTerminal pty;
769  const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
770 
771  PlatformSP platform_sp(GetTarget().GetPlatform());
772  if (disable_stdio) {
773  // set to /dev/null unless redirected to a file above
774  if (!stdin_file_spec)
775  stdin_file_spec.SetFile(FileSystem::DEV_NULL,
776  FileSpec::Style::native);
777  if (!stdout_file_spec)
778  stdout_file_spec.SetFile(FileSystem::DEV_NULL,
779  FileSpec::Style::native);
780  if (!stderr_file_spec)
781  stderr_file_spec.SetFile(FileSystem::DEV_NULL,
782  FileSpec::Style::native);
783  } else if (platform_sp && platform_sp->IsHost()) {
784  // If the debugserver is local and we aren't disabling STDIO, lets use
785  // a pseudo terminal to instead of relying on the 'O' packets for stdio
786  // since 'O' packets can really slow down debugging if the inferior
787  // does a lot of output.
788  if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
789  !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
790  FileSpec secondary_name(pty.GetSecondaryName());
791 
792  if (!stdin_file_spec)
793  stdin_file_spec = secondary_name;
794 
795  if (!stdout_file_spec)
796  stdout_file_spec = secondary_name;
797 
798  if (!stderr_file_spec)
799  stderr_file_spec = secondary_name;
800  }
801  LLDB_LOGF(
802  log,
803  "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
804  "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
805  "stderr=%s",
806  __FUNCTION__,
807  stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
808  stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
809  stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
810  }
811 
812  LLDB_LOGF(log,
813  "ProcessGDBRemote::%s final STDIO paths after all "
814  "adjustments: stdin=%s, stdout=%s, stderr=%s",
815  __FUNCTION__,
816  stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
817  stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
818  stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
819 
820  if (stdin_file_spec)
821  m_gdb_comm.SetSTDIN(stdin_file_spec);
822  if (stdout_file_spec)
823  m_gdb_comm.SetSTDOUT(stdout_file_spec);
824  if (stderr_file_spec)
825  m_gdb_comm.SetSTDERR(stderr_file_spec);
826 
827  m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
828  m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
829 
831  GetTarget().GetArchitecture().GetArchitectureName());
832 
833  const char *launch_event_data = launch_info.GetLaunchEventData();
834  if (launch_event_data != nullptr && *launch_event_data != '\0')
835  m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
836 
837  if (working_dir) {
838  m_gdb_comm.SetWorkingDir(working_dir);
839  }
840 
841  // Send the environment and the program + arguments after we connect
843 
844  {
845  // Scope for the scoped timeout object
847  std::chrono::seconds(10));
848 
849  int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
850  if (arg_packet_err == 0) {
851  std::string error_str;
852  if (m_gdb_comm.GetLaunchSuccess(error_str)) {
854  } else {
855  error.SetErrorString(error_str.c_str());
856  }
857  } else {
858  error.SetErrorStringWithFormat("'A' packet returned an error: %i",
859  arg_packet_err);
860  }
861  }
862 
863  if (GetID() == LLDB_INVALID_PROCESS_ID) {
864  LLDB_LOGF(log, "failed to connect to debugserver: %s",
865  error.AsCString());
867  return error;
868  }
869 
870  StringExtractorGDBRemote response;
871  if (m_gdb_comm.GetStopReply(response)) {
872  SetLastStopPacket(response);
873 
874  const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
875 
876  if (process_arch.IsValid()) {
877  GetTarget().MergeArchitecture(process_arch);
878  } else {
879  const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
880  if (host_arch.IsValid())
881  GetTarget().MergeArchitecture(host_arch);
882  }
883 
885 
886  if (!disable_stdio) {
889  }
890  }
891  } else {
892  LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
893  }
894  return error;
895 }
896 
897 Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
898  Status error;
899  // Only connect if we have a valid connect URL
901 
902  if (!connect_url.empty()) {
903  LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
904  connect_url.str().c_str());
905  std::unique_ptr<ConnectionFileDescriptor> conn_up(
907  if (conn_up) {
908  const uint32_t max_retry_count = 50;
909  uint32_t retry_count = 0;
910  while (!m_gdb_comm.IsConnected()) {
911  if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
912  m_gdb_comm.SetConnection(std::move(conn_up));
913  break;
914  }
915 
916  retry_count++;
917 
918  if (retry_count >= max_retry_count)
919  break;
920 
921  std::this_thread::sleep_for(std::chrono::milliseconds(100));
922  }
923  }
924  }
925 
926  if (!m_gdb_comm.IsConnected()) {
927  if (error.Success())
928  error.SetErrorString("not connected to remote gdb server");
929  return error;
930  }
931 
932  // We always seem to be able to open a connection to a local port so we need
933  // to make sure we can then send data to it. If we can't then we aren't
934  // actually connected to anything, so try and do the handshake with the
935  // remote GDB server and make sure that goes alright.
938  if (error.Success())
939  error.SetErrorString("not connected to remote gdb server");
940  return error;
941  }
942 
950 
951  size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
952  for (size_t idx = 0; idx < num_cmds; idx++) {
953  StringExtractorGDBRemote response;
955  GetExtraStartupCommands().GetArgumentAtIndex(idx), response);
956  }
957  return error;
958 }
959 
963 
964  // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
965  // qProcessInfo as it will be more specific to our process.
966 
967  const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
968  if (remote_process_arch.IsValid()) {
969  process_arch = remote_process_arch;
970  LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
971  process_arch.GetArchitectureName(),
972  process_arch.GetTriple().getTriple());
973  } else {
974  process_arch = m_gdb_comm.GetHostArchitecture();
975  LLDB_LOG(log,
976  "gdb-remote did not have process architecture, using gdb-remote "
977  "host architecture {0} {1}",
978  process_arch.GetArchitectureName(),
979  process_arch.GetTriple().getTriple());
980  }
981 
982  if (int addresssable_bits = m_gdb_comm.GetAddressingBits()) {
983  lldb::addr_t address_mask = ~((1ULL << addresssable_bits) - 1);
984  SetCodeAddressMask(address_mask);
985  SetDataAddressMask(address_mask);
986  }
987 
988  if (process_arch.IsValid()) {
989  const ArchSpec &target_arch = GetTarget().GetArchitecture();
990  if (target_arch.IsValid()) {
991  LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
992  target_arch.GetArchitectureName(),
993  target_arch.GetTriple().getTriple());
994 
995  // If the remote host is ARM and we have apple as the vendor, then
996  // ARM executables and shared libraries can have mixed ARM
997  // architectures.
998  // You can have an armv6 executable, and if the host is armv7, then the
999  // system will load the best possible architecture for all shared
1000  // libraries it has, so we really need to take the remote host
1001  // architecture as our defacto architecture in this case.
1002 
1003  if ((process_arch.GetMachine() == llvm::Triple::arm ||
1004  process_arch.GetMachine() == llvm::Triple::thumb) &&
1005  process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1006  GetTarget().SetArchitecture(process_arch);
1007  LLDB_LOG(log,
1008  "remote process is ARM/Apple, "
1009  "setting target arch to {0} {1}",
1010  process_arch.GetArchitectureName(),
1011  process_arch.GetTriple().getTriple());
1012  } else {
1013  // Fill in what is missing in the triple
1014  const llvm::Triple &remote_triple = process_arch.GetTriple();
1015  llvm::Triple new_target_triple = target_arch.GetTriple();
1016  if (new_target_triple.getVendorName().size() == 0) {
1017  new_target_triple.setVendor(remote_triple.getVendor());
1018 
1019  if (new_target_triple.getOSName().size() == 0) {
1020  new_target_triple.setOS(remote_triple.getOS());
1021 
1022  if (new_target_triple.getEnvironmentName().size() == 0)
1023  new_target_triple.setEnvironment(remote_triple.getEnvironment());
1024  }
1025 
1026  ArchSpec new_target_arch = target_arch;
1027  new_target_arch.SetTriple(new_target_triple);
1028  GetTarget().SetArchitecture(new_target_arch);
1029  }
1030  }
1031 
1032  LLDB_LOG(log,
1033  "final target arch after adjustments for remote architecture: "
1034  "{0} {1}",
1035  target_arch.GetArchitectureName(),
1036  target_arch.GetTriple().getTriple());
1037  } else {
1038  // The target doesn't have a valid architecture yet, set it from the
1039  // architecture we got from the remote GDB server
1040  GetTarget().SetArchitecture(process_arch);
1041  }
1042  }
1043 
1045 
1046  // Find out which StructuredDataPlugins are supported by the debug monitor.
1047  // These plugins transmit data over async $J packets.
1048  if (StructuredData::Array *supported_packets =
1050  MapSupportedStructuredDataPlugins(*supported_packets);
1051 
1052  // If connected to LLDB ("native-signals+"), use signal defs for
1053  // the remote platform. If connected to GDB, just use the standard set.
1054  if (!m_gdb_comm.UsesNativeSignals()) {
1055  SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1056  } else {
1057  PlatformSP platform_sp = GetTarget().GetPlatform();
1058  if (platform_sp && platform_sp->IsConnected())
1059  SetUnixSignals(platform_sp->GetUnixSignals());
1060  else
1061  SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1062  }
1063 }
1064 
1066  ModuleSP module_sp = GetTarget().GetExecutableModule();
1067  if (!module_sp)
1068  return;
1069 
1070  llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1071  if (!offsets)
1072  return;
1073 
1074  bool is_uniform =
1075  size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1076  offsets->offsets.size();
1077  if (!is_uniform)
1078  return; // TODO: Handle non-uniform responses.
1079 
1080  bool changed = false;
1081  module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1082  /*value_is_offset=*/true, changed);
1083  if (changed) {
1084  ModuleList list;
1085  list.Append(module_sp);
1087  }
1088 }
1089 
1091  ArchSpec process_arch;
1092  DidLaunchOrAttach(process_arch);
1093 }
1094 
1096  lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1098  Status error;
1099 
1100  LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1101 
1102  // Clear out and clean up from any current state
1103  Clear();
1104  if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1105  error = EstablishConnectionIfNeeded(attach_info);
1106  if (error.Success()) {
1108 
1109  char packet[64];
1110  const int packet_len =
1111  ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1112  SetID(attach_pid);
1114  eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1115  } else
1116  SetExitStatus(-1, error.AsCString());
1117  }
1118 
1119  return error;
1120 }
1121 
1123  const char *process_name, const ProcessAttachInfo &attach_info) {
1124  Status error;
1125  // Clear out and clean up from any current state
1126  Clear();
1127 
1128  if (process_name && process_name[0]) {
1129  error = EstablishConnectionIfNeeded(attach_info);
1130  if (error.Success()) {
1131  StreamString packet;
1132 
1134 
1135  if (attach_info.GetWaitForLaunch()) {
1137  packet.PutCString("vAttachWait");
1138  } else {
1139  if (attach_info.GetIgnoreExisting())
1140  packet.PutCString("vAttachWait");
1141  else
1142  packet.PutCString("vAttachOrWait");
1143  }
1144  } else
1145  packet.PutCString("vAttachName");
1146  packet.PutChar(';');
1147  packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1150 
1153  new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1154 
1155  } else
1156  SetExitStatus(-1, error.AsCString());
1157  }
1158  return error;
1159 }
1160 
1161 llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1163 }
1164 
1166  return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1167 }
1168 
1169 llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1170  return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1171 }
1172 
1173 llvm::Expected<std::string>
1174 ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1176 }
1177 
1178 llvm::Expected<std::vector<uint8_t>>
1181 }
1182 
1184  // When we exit, disconnect from the GDB server communications
1186 }
1187 
1189  // If you can figure out what the architecture is, fill it in here.
1190  process_arch.Clear();
1191  DidLaunchOrAttach(process_arch);
1192 }
1193 
1195  m_continue_c_tids.clear();
1196  m_continue_C_tids.clear();
1197  m_continue_s_tids.clear();
1198  m_continue_S_tids.clear();
1199  m_jstopinfo_sp.reset();
1200  m_jthreadsinfo_sp.reset();
1201  return Status();
1202 }
1203 
1205  Status error;
1207  LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
1208 
1209  ListenerSP listener_sp(
1210  Listener::MakeListener("gdb-remote.resume-packet-sent"));
1211  if (listener_sp->StartListeningForEvents(
1213  listener_sp->StartListeningForEvents(
1216 
1217  const size_t num_threads = GetThreadList().GetSize();
1218 
1219  StreamString continue_packet;
1220  bool continue_packet_error = false;
1222  if (m_continue_c_tids.size() == num_threads ||
1223  (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1224  m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1225  // All threads are continuing, just send a "c" packet
1226  continue_packet.PutCString("c");
1227  } else {
1228  continue_packet.PutCString("vCont");
1229 
1230  if (!m_continue_c_tids.empty()) {
1231  if (m_gdb_comm.GetVContSupported('c')) {
1232  for (tid_collection::const_iterator
1233  t_pos = m_continue_c_tids.begin(),
1234  t_end = m_continue_c_tids.end();
1235  t_pos != t_end; ++t_pos)
1236  continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1237  } else
1238  continue_packet_error = true;
1239  }
1240 
1241  if (!continue_packet_error && !m_continue_C_tids.empty()) {
1242  if (m_gdb_comm.GetVContSupported('C')) {
1243  for (tid_sig_collection::const_iterator
1244  s_pos = m_continue_C_tids.begin(),
1245  s_end = m_continue_C_tids.end();
1246  s_pos != s_end; ++s_pos)
1247  continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1248  s_pos->first);
1249  } else
1250  continue_packet_error = true;
1251  }
1252 
1253  if (!continue_packet_error && !m_continue_s_tids.empty()) {
1254  if (m_gdb_comm.GetVContSupported('s')) {
1255  for (tid_collection::const_iterator
1256  t_pos = m_continue_s_tids.begin(),
1257  t_end = m_continue_s_tids.end();
1258  t_pos != t_end; ++t_pos)
1259  continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1260  } else
1261  continue_packet_error = true;
1262  }
1263 
1264  if (!continue_packet_error && !m_continue_S_tids.empty()) {
1265  if (m_gdb_comm.GetVContSupported('S')) {
1266  for (tid_sig_collection::const_iterator
1267  s_pos = m_continue_S_tids.begin(),
1268  s_end = m_continue_S_tids.end();
1269  s_pos != s_end; ++s_pos)
1270  continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1271  s_pos->first);
1272  } else
1273  continue_packet_error = true;
1274  }
1275 
1276  if (continue_packet_error)
1277  continue_packet.Clear();
1278  }
1279  } else
1280  continue_packet_error = true;
1281 
1282  if (continue_packet_error) {
1283  // Either no vCont support, or we tried to use part of the vCont packet
1284  // that wasn't supported by the remote GDB server. We need to try and
1285  // make a simple packet that can do our continue
1286  const size_t num_continue_c_tids = m_continue_c_tids.size();
1287  const size_t num_continue_C_tids = m_continue_C_tids.size();
1288  const size_t num_continue_s_tids = m_continue_s_tids.size();
1289  const size_t num_continue_S_tids = m_continue_S_tids.size();
1290  if (num_continue_c_tids > 0) {
1291  if (num_continue_c_tids == num_threads) {
1292  // All threads are resuming...
1294  continue_packet.PutChar('c');
1295  continue_packet_error = false;
1296  } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1297  num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1298  // Only one thread is continuing
1300  continue_packet.PutChar('c');
1301  continue_packet_error = false;
1302  }
1303  }
1304 
1305  if (continue_packet_error && num_continue_C_tids > 0) {
1306  if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1307  num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1308  num_continue_S_tids == 0) {
1309  const int continue_signo = m_continue_C_tids.front().second;
1310  // Only one thread is continuing
1311  if (num_continue_C_tids > 1) {
1312  // More that one thread with a signal, yet we don't have vCont
1313  // support and we are being asked to resume each thread with a
1314  // signal, we need to make sure they are all the same signal, or we
1315  // can't issue the continue accurately with the current support...
1316  if (num_continue_C_tids > 1) {
1317  continue_packet_error = false;
1318  for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1319  if (m_continue_C_tids[i].second != continue_signo)
1320  continue_packet_error = true;
1321  }
1322  }
1323  if (!continue_packet_error)
1325  } else {
1326  // Set the continue thread ID
1327  continue_packet_error = false;
1329  }
1330  if (!continue_packet_error) {
1331  // Add threads continuing with the same signo...
1332  continue_packet.Printf("C%2.2x", continue_signo);
1333  }
1334  }
1335  }
1336 
1337  if (continue_packet_error && num_continue_s_tids > 0) {
1338  if (num_continue_s_tids == num_threads) {
1339  // All threads are resuming...
1341 
1342  continue_packet.PutChar('s');
1343 
1344  continue_packet_error = false;
1345  } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1346  num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1347  // Only one thread is stepping
1349  continue_packet.PutChar('s');
1350  continue_packet_error = false;
1351  }
1352  }
1353 
1354  if (!continue_packet_error && num_continue_S_tids > 0) {
1355  if (num_continue_S_tids == num_threads) {
1356  const int step_signo = m_continue_S_tids.front().second;
1357  // Are all threads trying to step with the same signal?
1358  continue_packet_error = false;
1359  if (num_continue_S_tids > 1) {
1360  for (size_t i = 1; i < num_threads; ++i) {
1361  if (m_continue_S_tids[i].second != step_signo)
1362  continue_packet_error = true;
1363  }
1364  }
1365  if (!continue_packet_error) {
1366  // Add threads stepping with the same signo...
1368  continue_packet.Printf("S%2.2x", step_signo);
1369  }
1370  } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1371  num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1372  // Only one thread is stepping with signal
1374  continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1375  continue_packet_error = false;
1376  }
1377  }
1378  }
1379 
1380  if (continue_packet_error) {
1381  error.SetErrorString("can't make continue packet for this resume");
1382  } else {
1383  EventSP event_sp;
1384  if (!m_async_thread.IsJoinable()) {
1385  error.SetErrorString("Trying to resume but the async thread is dead.");
1386  LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1387  "async thread is dead.");
1388  return error;
1389  }
1390 
1393  new EventDataBytes(continue_packet.GetString().data(),
1394  continue_packet.GetSize()));
1395 
1396  if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1397  error.SetErrorString("Resume timed out.");
1398  LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1399  } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1400  error.SetErrorString("Broadcast continue, but the async thread was "
1401  "killed before we got an ack back.");
1402  LLDB_LOGF(log,
1403  "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1404  "async thread was killed before we got an ack back.");
1405  return error;
1406  }
1407  }
1408  }
1409 
1410  return error;
1411 }
1412 
1414  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1415  m_thread_ids.clear();
1416  m_thread_pcs.clear();
1417 }
1418 
1420  llvm::StringRef value) {
1421  m_thread_ids.clear();
1423  StringExtractorGDBRemote thread_ids{value};
1424 
1425  do {
1426  auto pid_tid = thread_ids.GetPidTid(pid);
1427  if (pid_tid && pid_tid->first == pid) {
1428  lldb::tid_t tid = pid_tid->second;
1429  if (tid != LLDB_INVALID_THREAD_ID &&
1431  m_thread_ids.push_back(tid);
1432  }
1433  } while (thread_ids.GetChar() == ',');
1434 
1435  return m_thread_ids.size();
1436 }
1437 
1439  llvm::StringRef value) {
1440  m_thread_pcs.clear();
1441  for (llvm::StringRef x : llvm::split(value, ',')) {
1442  lldb::addr_t pc;
1443  if (llvm::to_integer(x, pc, 16))
1444  m_thread_pcs.push_back(pc);
1445  }
1446  return m_thread_pcs.size();
1447 }
1448 
1450  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1451 
1452  if (m_jthreadsinfo_sp) {
1453  // If we have the JSON threads info, we can get the thread list from that
1454  StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1455  if (thread_infos && thread_infos->GetSize() > 0) {
1456  m_thread_ids.clear();
1457  m_thread_pcs.clear();
1458  thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1459  StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1460  if (thread_dict) {
1461  // Set the thread stop info from the JSON dictionary
1462  SetThreadStopInfo(thread_dict);
1464  if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1465  m_thread_ids.push_back(tid);
1466  }
1467  return true; // Keep iterating through all thread_info objects
1468  });
1469  }
1470  if (!m_thread_ids.empty())
1471  return true;
1472  } else {
1473  // See if we can get the thread IDs from the current stop reply packets
1474  // that might contain a "threads" key/value pair
1475 
1476  if (m_last_stop_packet) {
1477  // Get the thread stop info
1479  const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1480 
1481  m_thread_pcs.clear();
1482  const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1483  if (thread_pcs_pos != std::string::npos) {
1484  const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1485  const size_t end = stop_info_str.find(';', start);
1486  if (end != std::string::npos) {
1487  std::string value = stop_info_str.substr(start, end - start);
1489  }
1490  }
1491 
1492  const size_t threads_pos = stop_info_str.find(";threads:");
1493  if (threads_pos != std::string::npos) {
1494  const size_t start = threads_pos + strlen(";threads:");
1495  const size_t end = stop_info_str.find(';', start);
1496  if (end != std::string::npos) {
1497  std::string value = stop_info_str.substr(start, end - start);
1499  return true;
1500  }
1501  }
1502  }
1503  }
1504 
1505  bool sequence_mutex_unavailable = false;
1506  m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1507  if (sequence_mutex_unavailable) {
1508  return false; // We just didn't get the list
1509  }
1510  return true;
1511 }
1512 
1514  ThreadList &new_thread_list) {
1515  // locker will keep a mutex locked until it goes out of scope
1517  LLDB_LOGV(log, "pid = {0}", GetID());
1518 
1519  size_t num_thread_ids = m_thread_ids.size();
1520  // The "m_thread_ids" thread ID list should always be updated after each stop
1521  // reply packet, but in case it isn't, update it here.
1522  if (num_thread_ids == 0) {
1523  if (!UpdateThreadIDList())
1524  return false;
1525  num_thread_ids = m_thread_ids.size();
1526  }
1527 
1528  ThreadList old_thread_list_copy(old_thread_list);
1529  if (num_thread_ids > 0) {
1530  for (size_t i = 0; i < num_thread_ids; ++i) {
1531  tid_t tid = m_thread_ids[i];
1532  ThreadSP thread_sp(
1533  old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1534  if (!thread_sp) {
1535  thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1536  LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1537  thread_sp.get(), thread_sp->GetID());
1538  } else {
1539  LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1540  thread_sp.get(), thread_sp->GetID());
1541  }
1542 
1543  SetThreadPc(thread_sp, i);
1544  new_thread_list.AddThreadSortedByIndexID(thread_sp);
1545  }
1546  }
1547 
1548  // Whatever that is left in old_thread_list_copy are not present in
1549  // new_thread_list. Remove non-existent threads from internal id table.
1550  size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1551  for (size_t i = 0; i < old_num_thread_ids; i++) {
1552  ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1553  if (old_thread_sp) {
1554  lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1555  m_thread_id_to_index_id_map.erase(old_thread_id);
1556  }
1557  }
1558 
1559  return true;
1560 }
1561 
1562 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1563  if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1565  ThreadGDBRemote *gdb_thread =
1566  static_cast<ThreadGDBRemote *>(thread_sp.get());
1567  RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1568  if (reg_ctx_sp) {
1569  uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1571  if (pc_regnum != LLDB_INVALID_REGNUM) {
1572  gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1573  }
1574  }
1575  }
1576 }
1577 
1579  ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1580  // See if we got thread stop infos for all threads via the "jThreadsInfo"
1581  // packet
1582  if (thread_infos_sp) {
1583  StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1584  if (thread_infos) {
1585  lldb::tid_t tid;
1586  const size_t n = thread_infos->GetSize();
1587  for (size_t i = 0; i < n; ++i) {
1588  StructuredData::Dictionary *thread_dict =
1589  thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1590  if (thread_dict) {
1591  if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1592  "tid", tid, LLDB_INVALID_THREAD_ID)) {
1593  if (tid == thread->GetID())
1594  return (bool)SetThreadStopInfo(thread_dict);
1595  }
1596  }
1597  }
1598  }
1599  }
1600  return false;
1601 }
1602 
1604  // See if we got thread stop infos for all threads via the "jThreadsInfo"
1605  // packet
1607  return true;
1608 
1609  // See if we got thread stop info for any threads valid stop info reasons
1610  // threads via the "jstopinfo" packet stop reply packet key/value pair?
1611  if (m_jstopinfo_sp) {
1612  // If we have "jstopinfo" then we have stop descriptions for all threads
1613  // that have stop reasons, and if there is no entry for a thread, then it
1614  // has no stop reason.
1615  thread->GetRegisterContext()->InvalidateIfNeeded(true);
1616  if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1617  thread->SetStopInfo(StopInfoSP());
1618  }
1619  return true;
1620  }
1621 
1622  // Fall back to using the qThreadStopInfo packet
1623  StringExtractorGDBRemote stop_packet;
1624  if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1625  return SetThreadStopInfo(stop_packet) == eStateStopped;
1626  return false;
1627 }
1628 
1630  lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1631  uint8_t signo, const std::string &thread_name, const std::string &reason,
1632  const std::string &description, uint32_t exc_type,
1633  const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1634  bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1635  // queue_serial are valid
1636  LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1637  std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1638  ThreadSP thread_sp;
1639  if (tid != LLDB_INVALID_THREAD_ID) {
1640  // Scope for "locker" below
1641  {
1642  // m_thread_list_real does have its own mutex, but we need to hold onto
1643  // the mutex between the call to m_thread_list_real.FindThreadByID(...)
1644  // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1645  std::lock_guard<std::recursive_mutex> guard(
1647  thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1648 
1649  if (!thread_sp) {
1650  // Create the thread if we need to
1651  thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1652  m_thread_list_real.AddThread(thread_sp);
1653  }
1654  }
1655 
1656  if (thread_sp) {
1657  ThreadGDBRemote *gdb_thread =
1658  static_cast<ThreadGDBRemote *>(thread_sp.get());
1659  RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1660 
1661  gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1662 
1663  auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1664  if (iter != m_thread_ids.end()) {
1665  SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1666  }
1667 
1668  for (const auto &pair : expedited_register_map) {
1669  StringExtractor reg_value_extractor(pair.second);
1670  DataBufferSP buffer_sp(new DataBufferHeap(
1671  reg_value_extractor.GetStringRef().size() / 2, 0));
1672  reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1673  uint32_t lldb_regnum =
1674  gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1675  eRegisterKindProcessPlugin, pair.first);
1676  gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1677  }
1678 
1679  // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1680  // SVE register sizes and offsets if value of VG register has changed
1681  // since last stop.
1682  const ArchSpec &arch = GetTarget().GetArchitecture();
1683  if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1684  GDBRemoteRegisterContext *reg_ctx_sp =
1685  static_cast<GDBRemoteRegisterContext *>(
1686  gdb_thread->GetRegisterContext().get());
1687 
1688  if (reg_ctx_sp)
1689  reg_ctx_sp->AArch64SVEReconfigure();
1690  }
1691 
1692  thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1693 
1694  gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1695  // Check if the GDB server was able to provide the queue name, kind and
1696  // serial number
1697  if (queue_vars_valid)
1698  gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1699  queue_serial, dispatch_queue_t,
1700  associated_with_dispatch_queue);
1701  else
1702  gdb_thread->ClearQueueInfo();
1703 
1705  associated_with_dispatch_queue);
1706 
1707  if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1708  gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1709 
1710  // Make sure we update our thread stop reason just once
1711  if (!thread_sp->StopInfoIsUpToDate()) {
1712  thread_sp->SetStopInfo(StopInfoSP());
1713  // If there's a memory thread backed by this thread, we need to use it
1714  // to calculate StopInfo.
1715  if (ThreadSP memory_thread_sp =
1716  m_thread_list.GetBackingThread(thread_sp))
1717  thread_sp = memory_thread_sp;
1718 
1719  if (exc_type != 0) {
1720  const size_t exc_data_size = exc_data.size();
1721 
1722  thread_sp->SetStopInfo(
1724  *thread_sp, exc_type, exc_data_size,
1725  exc_data_size >= 1 ? exc_data[0] : 0,
1726  exc_data_size >= 2 ? exc_data[1] : 0,
1727  exc_data_size >= 3 ? exc_data[2] : 0));
1728  } else {
1729  bool handled = false;
1730  bool did_exec = false;
1731  if (!reason.empty()) {
1732  if (reason == "trace") {
1733  addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1734  lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1735  ->GetBreakpointSiteList()
1736  .FindByAddress(pc);
1737 
1738  // If the current pc is a breakpoint site then the StopInfo
1739  // should be set to Breakpoint Otherwise, it will be set to
1740  // Trace.
1741  if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1742  thread_sp->SetStopInfo(
1744  *thread_sp, bp_site_sp->GetID()));
1745  } else
1746  thread_sp->SetStopInfo(
1747  StopInfo::CreateStopReasonToTrace(*thread_sp));
1748  handled = true;
1749  } else if (reason == "breakpoint") {
1750  addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1751  lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1752  ->GetBreakpointSiteList()
1753  .FindByAddress(pc);
1754  if (bp_site_sp) {
1755  // If the breakpoint is for this thread, then we'll report the
1756  // hit, but if it is for another thread, we can just report no
1757  // reason. We don't need to worry about stepping over the
1758  // breakpoint here, that will be taken care of when the thread
1759  // resumes and notices that there's a breakpoint under the pc.
1760  handled = true;
1761  if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1762  thread_sp->SetStopInfo(
1764  *thread_sp, bp_site_sp->GetID()));
1765  } else {
1766  StopInfoSP invalid_stop_info_sp;
1767  thread_sp->SetStopInfo(invalid_stop_info_sp);
1768  }
1769  }
1770  } else if (reason == "trap") {
1771  // Let the trap just use the standard signal stop reason below...
1772  } else if (reason == "watchpoint") {
1773  StringExtractor desc_extractor(description.c_str());
1774  addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1775  uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1776  addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1777  watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1778  if (wp_addr != LLDB_INVALID_ADDRESS) {
1779  WatchpointSP wp_sp;
1781  if ((core >= ArchSpec::kCore_mips_first &&
1782  core <= ArchSpec::kCore_mips_last) ||
1783  (core >= ArchSpec::eCore_arm_generic &&
1784  core <= ArchSpec::eCore_arm_aarch64))
1786  wp_hit_addr);
1787  if (!wp_sp)
1788  wp_sp =
1790  if (wp_sp) {
1791  wp_sp->SetHardwareIndex(wp_index);
1792  watch_id = wp_sp->GetID();
1793  }
1794  }
1795  if (watch_id == LLDB_INVALID_WATCH_ID) {
1798  LLDB_LOGF(log, "failed to find watchpoint");
1799  }
1800  thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1801  *thread_sp, watch_id, wp_hit_addr));
1802  handled = true;
1803  } else if (reason == "exception") {
1804  thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1805  *thread_sp, description.c_str()));
1806  handled = true;
1807  } else if (reason == "exec") {
1808  did_exec = true;
1809  thread_sp->SetStopInfo(
1811  handled = true;
1812  } else if (reason == "processor trace") {
1813  thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1814  *thread_sp, description.c_str()));
1815  } else if (reason == "fork") {
1816  StringExtractor desc_extractor(description.c_str());
1817  lldb::pid_t child_pid = desc_extractor.GetU64(
1819  lldb::tid_t child_tid = desc_extractor.GetU64(
1821  thread_sp->SetStopInfo(StopInfo::CreateStopReasonFork(
1822  *thread_sp, child_pid, child_tid));
1823  handled = true;
1824  } else if (reason == "vfork") {
1825  StringExtractor desc_extractor(description.c_str());
1826  lldb::pid_t child_pid = desc_extractor.GetU64(
1828  lldb::tid_t child_tid = desc_extractor.GetU64(
1830  thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1831  *thread_sp, child_pid, child_tid));
1832  handled = true;
1833  } else if (reason == "vforkdone") {
1834  thread_sp->SetStopInfo(
1836  handled = true;
1837  }
1838  } else if (!signo) {
1839  addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1840  lldb::BreakpointSiteSP bp_site_sp =
1841  thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1842  pc);
1843 
1844  // If the current pc is a breakpoint site then the StopInfo should
1845  // be set to Breakpoint even though the remote stub did not set it
1846  // as such. This can happen when the thread is involuntarily
1847  // interrupted (e.g. due to stops on other threads) just as it is
1848  // about to execute the breakpoint instruction.
1849  if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1850  thread_sp->SetStopInfo(
1852  *thread_sp, bp_site_sp->GetID()));
1853  handled = true;
1854  }
1855  }
1856 
1857  if (!handled && signo && !did_exec) {
1858  if (signo == SIGTRAP) {
1859  // Currently we are going to assume SIGTRAP means we are either
1860  // hitting a breakpoint or hardware single stepping.
1861  handled = true;
1862  addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1864  lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1865  ->GetBreakpointSiteList()
1866  .FindByAddress(pc);
1867 
1868  if (bp_site_sp) {
1869  // If the breakpoint is for this thread, then we'll report the
1870  // hit, but if it is for another thread, we can just report no
1871  // reason. We don't need to worry about stepping over the
1872  // breakpoint here, that will be taken care of when the thread
1873  // resumes and notices that there's a breakpoint under the pc.
1874  if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1875  if (m_breakpoint_pc_offset != 0)
1876  thread_sp->GetRegisterContext()->SetPC(pc);
1877  thread_sp->SetStopInfo(
1879  *thread_sp, bp_site_sp->GetID()));
1880  } else {
1881  StopInfoSP invalid_stop_info_sp;
1882  thread_sp->SetStopInfo(invalid_stop_info_sp);
1883  }
1884  } else {
1885  // If we were stepping then assume the stop was the result of
1886  // the trace. If we were not stepping then report the SIGTRAP.
1887  // FIXME: We are still missing the case where we single step
1888  // over a trap instruction.
1889  if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1890  thread_sp->SetStopInfo(
1891  StopInfo::CreateStopReasonToTrace(*thread_sp));
1892  else
1893  thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1894  *thread_sp, signo, description.c_str()));
1895  }
1896  }
1897  if (!handled)
1898  thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1899  *thread_sp, signo, description.c_str()));
1900  }
1901 
1902  if (!description.empty()) {
1903  lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1904  if (stop_info_sp) {
1905  const char *stop_info_desc = stop_info_sp->GetDescription();
1906  if (!stop_info_desc || !stop_info_desc[0])
1907  stop_info_sp->SetDescription(description.c_str());
1908  } else {
1909  thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1910  *thread_sp, description.c_str()));
1911  }
1912  }
1913  }
1914  }
1915  }
1916  }
1917  return thread_sp;
1918 }
1919 
1920 lldb::ThreadSP
1922  static ConstString g_key_tid("tid");
1923  static ConstString g_key_name("name");
1924  static ConstString g_key_reason("reason");
1925  static ConstString g_key_metype("metype");
1926  static ConstString g_key_medata("medata");
1927  static ConstString g_key_qaddr("qaddr");
1928  static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1929  static ConstString g_key_associated_with_dispatch_queue(
1930  "associated_with_dispatch_queue");
1931  static ConstString g_key_queue_name("qname");
1932  static ConstString g_key_queue_kind("qkind");
1933  static ConstString g_key_queue_serial_number("qserialnum");
1934  static ConstString g_key_registers("registers");
1935  static ConstString g_key_memory("memory");
1936  static ConstString g_key_address("address");
1937  static ConstString g_key_bytes("bytes");
1938  static ConstString g_key_description("description");
1939  static ConstString g_key_signal("signal");
1940 
1941  // Stop with signal and thread info
1943  uint8_t signo = 0;
1944  std::string value;
1945  std::string thread_name;
1946  std::string reason;
1947  std::string description;
1948  uint32_t exc_type = 0;
1949  std::vector<addr_t> exc_data;
1950  addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1951  ExpeditedRegisterMap expedited_register_map;
1952  bool queue_vars_valid = false;
1953  addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
1954  LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
1955  std::string queue_name;
1956  QueueKind queue_kind = eQueueKindUnknown;
1957  uint64_t queue_serial_number = 0;
1958  // Iterate through all of the thread dictionary key/value pairs from the
1959  // structured data dictionary
1960 
1961  // FIXME: we're silently ignoring invalid data here
1962  thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
1963  &signo, &reason, &description, &exc_type, &exc_data,
1964  &thread_dispatch_qaddr, &queue_vars_valid,
1965  &associated_with_dispatch_queue, &dispatch_queue_t,
1966  &queue_name, &queue_kind, &queue_serial_number](
1967  ConstString key,
1968  StructuredData::Object *object) -> bool {
1969  if (key == g_key_tid) {
1970  // thread in big endian hex
1971  tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
1972  } else if (key == g_key_metype) {
1973  // exception type in big endian hex
1974  exc_type = object->GetIntegerValue(0);
1975  } else if (key == g_key_medata) {
1976  // exception data in big endian hex
1977  StructuredData::Array *array = object->GetAsArray();
1978  if (array) {
1979  array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
1980  exc_data.push_back(object->GetIntegerValue());
1981  return true; // Keep iterating through all array items
1982  });
1983  }
1984  } else if (key == g_key_name) {
1985  thread_name = std::string(object->GetStringValue());
1986  } else if (key == g_key_qaddr) {
1987  thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
1988  } else if (key == g_key_queue_name) {
1989  queue_vars_valid = true;
1990  queue_name = std::string(object->GetStringValue());
1991  } else if (key == g_key_queue_kind) {
1992  std::string queue_kind_str = std::string(object->GetStringValue());
1993  if (queue_kind_str == "serial") {
1994  queue_vars_valid = true;
1995  queue_kind = eQueueKindSerial;
1996  } else if (queue_kind_str == "concurrent") {
1997  queue_vars_valid = true;
1998  queue_kind = eQueueKindConcurrent;
1999  }
2000  } else if (key == g_key_queue_serial_number) {
2001  queue_serial_number = object->GetIntegerValue(0);
2002  if (queue_serial_number != 0)
2003  queue_vars_valid = true;
2004  } else if (key == g_key_dispatch_queue_t) {
2005  dispatch_queue_t = object->GetIntegerValue(0);
2006  if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2007  queue_vars_valid = true;
2008  } else if (key == g_key_associated_with_dispatch_queue) {
2009  queue_vars_valid = true;
2010  bool associated = object->GetBooleanValue();
2011  if (associated)
2012  associated_with_dispatch_queue = eLazyBoolYes;
2013  else
2014  associated_with_dispatch_queue = eLazyBoolNo;
2015  } else if (key == g_key_reason) {
2016  reason = std::string(object->GetStringValue());
2017  } else if (key == g_key_description) {
2018  description = std::string(object->GetStringValue());
2019  } else if (key == g_key_registers) {
2020  StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2021 
2022  if (registers_dict) {
2023  registers_dict->ForEach(
2024  [&expedited_register_map](ConstString key,
2025  StructuredData::Object *object) -> bool {
2026  uint32_t reg;
2027  if (llvm::to_integer(key.AsCString(), reg))
2028  expedited_register_map[reg] =
2029  std::string(object->GetStringValue());
2030  return true; // Keep iterating through all array items
2031  });
2032  }
2033  } else if (key == g_key_memory) {
2034  StructuredData::Array *array = object->GetAsArray();
2035  if (array) {
2036  array->ForEach([this](StructuredData::Object *object) -> bool {
2037  StructuredData::Dictionary *mem_cache_dict =
2038  object->GetAsDictionary();
2039  if (mem_cache_dict) {
2040  lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2041  if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2042  "address", mem_cache_addr)) {
2043  if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2044  llvm::StringRef str;
2045  if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2046  StringExtractor bytes(str);
2047  bytes.SetFilePos(0);
2048 
2049  const size_t byte_size = bytes.GetStringRef().size() / 2;
2050  DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2051  const size_t bytes_copied =
2052  bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2053  if (bytes_copied == byte_size)
2054  m_memory_cache.AddL1CacheData(mem_cache_addr,
2055  data_buffer_sp);
2056  }
2057  }
2058  }
2059  }
2060  return true; // Keep iterating through all array items
2061  });
2062  }
2063 
2064  } else if (key == g_key_signal)
2065  signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2066  return true; // Keep iterating through all dictionary key/value pairs
2067  });
2068 
2069  return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2070  reason, description, exc_type, exc_data,
2071  thread_dispatch_qaddr, queue_vars_valid,
2072  associated_with_dispatch_queue, dispatch_queue_t,
2073  queue_name, queue_kind, queue_serial_number);
2074 }
2075 
2076 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2077  lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2078  stop_packet.SetFilePos(0);
2079  const char stop_type = stop_packet.GetChar();
2080  switch (stop_type) {
2081  case 'T':
2082  case 'S': {
2083  // This is a bit of a hack, but is is required. If we did exec, we need to
2084  // clear our thread lists and also know to rebuild our dynamic register
2085  // info before we lookup and threads and populate the expedited register
2086  // values so we need to know this right away so we can cleanup and update
2087  // our registers.
2088  const uint32_t stop_id = GetStopID();
2089  if (stop_id == 0) {
2090  // Our first stop, make sure we have a process ID, and also make sure we
2091  // know about our registers
2092  if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
2093  SetID(pid);
2094  BuildDynamicRegisterInfo(true);
2095  }
2096  // Stop with signal and thread info
2099  const uint8_t signo = stop_packet.GetHexU8();
2100  llvm::StringRef key;
2101  llvm::StringRef value;
2102  std::string thread_name;
2103  std::string reason;
2104  std::string description;
2105  uint32_t exc_type = 0;
2106  std::vector<addr_t> exc_data;
2107  addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2108  bool queue_vars_valid =
2109  false; // says if locals below that start with "queue_" are valid
2110  addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2111  LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2112  std::string queue_name;
2113  QueueKind queue_kind = eQueueKindUnknown;
2114  uint64_t queue_serial_number = 0;
2115  ExpeditedRegisterMap expedited_register_map;
2116  while (stop_packet.GetNameColonValue(key, value)) {
2117  if (key.compare("metype") == 0) {
2118  // exception type in big endian hex
2119  value.getAsInteger(16, exc_type);
2120  } else if (key.compare("medata") == 0) {
2121  // exception data in big endian hex
2122  uint64_t x;
2123  value.getAsInteger(16, x);
2124  exc_data.push_back(x);
2125  } else if (key.compare("thread") == 0) {
2126  // thread-id
2127  StringExtractorGDBRemote thread_id{value};
2128  auto pid_tid = thread_id.GetPidTid(pid);
2129  if (pid_tid) {
2130  stop_pid = pid_tid->first;
2131  tid = pid_tid->second;
2132  } else
2133  tid = LLDB_INVALID_THREAD_ID;
2134  } else if (key.compare("threads") == 0) {
2135  std::lock_guard<std::recursive_mutex> guard(
2136  m_thread_list_real.GetMutex());
2137  UpdateThreadIDsFromStopReplyThreadsValue(value);
2138  } else if (key.compare("thread-pcs") == 0) {
2139  m_thread_pcs.clear();
2140  // A comma separated list of all threads in the current
2141  // process that includes the thread for this stop reply packet
2142  lldb::addr_t pc;
2143  while (!value.empty()) {
2144  llvm::StringRef pc_str;
2145  std::tie(pc_str, value) = value.split(',');
2146  if (pc_str.getAsInteger(16, pc))
2148  m_thread_pcs.push_back(pc);
2149  }
2150  } else if (key.compare("jstopinfo") == 0) {
2151  StringExtractor json_extractor(value);
2152  std::string json;
2153  // Now convert the HEX bytes into a string value
2154  json_extractor.GetHexByteString(json);
2155 
2156  // This JSON contains thread IDs and thread stop info for all threads.
2157  // It doesn't contain expedited registers, memory or queue info.
2158  m_jstopinfo_sp = StructuredData::ParseJSON(json);
2159  } else if (key.compare("hexname") == 0) {
2160  StringExtractor name_extractor(value);
2161  std::string name;
2162  // Now convert the HEX bytes into a string value
2163  name_extractor.GetHexByteString(thread_name);
2164  } else if (key.compare("name") == 0) {
2165  thread_name = std::string(value);
2166  } else if (key.compare("qaddr") == 0) {
2167  value.getAsInteger(16, thread_dispatch_qaddr);
2168  } else if (key.compare("dispatch_queue_t") == 0) {
2169  queue_vars_valid = true;
2170  value.getAsInteger(16, dispatch_queue_t);
2171  } else if (key.compare("qname") == 0) {
2172  queue_vars_valid = true;
2173  StringExtractor name_extractor(value);
2174  // Now convert the HEX bytes into a string value
2175  name_extractor.GetHexByteString(queue_name);
2176  } else if (key.compare("qkind") == 0) {
2177  queue_kind = llvm::StringSwitch<QueueKind>(value)
2178  .Case("serial", eQueueKindSerial)
2179  .Case("concurrent", eQueueKindConcurrent)
2180  .Default(eQueueKindUnknown);
2181  queue_vars_valid = queue_kind != eQueueKindUnknown;
2182  } else if (key.compare("qserialnum") == 0) {
2183  if (!value.getAsInteger(0, queue_serial_number))
2184  queue_vars_valid = true;
2185  } else if (key.compare("reason") == 0) {
2186  reason = std::string(value);
2187  } else if (key.compare("description") == 0) {
2188  StringExtractor desc_extractor(value);
2189  // Now convert the HEX bytes into a string value
2190  desc_extractor.GetHexByteString(description);
2191  } else if (key.compare("memory") == 0) {
2192  // Expedited memory. GDB servers can choose to send back expedited
2193  // memory that can populate the L1 memory cache in the process so that
2194  // things like the frame pointer backchain can be expedited. This will
2195  // help stack backtracing be more efficient by not having to send as
2196  // many memory read requests down the remote GDB server.
2197 
2198  // Key/value pair format: memory:<addr>=<bytes>;
2199  // <addr> is a number whose base will be interpreted by the prefix:
2200  // "0x[0-9a-fA-F]+" for hex
2201  // "0[0-7]+" for octal
2202  // "[1-9]+" for decimal
2203  // <bytes> is native endian ASCII hex bytes just like the register
2204  // values
2205  llvm::StringRef addr_str, bytes_str;
2206  std::tie(addr_str, bytes_str) = value.split('=');
2207  if (!addr_str.empty() && !bytes_str.empty()) {
2208  lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2209  if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2210  StringExtractor bytes(bytes_str);
2211  const size_t byte_size = bytes.GetBytesLeft() / 2;
2212  DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2213  const size_t bytes_copied =
2214  bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2215  if (bytes_copied == byte_size)
2216  m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2217  }
2218  }
2219  } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2220  key.compare("awatch") == 0) {
2221  // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2223  value.getAsInteger(16, wp_addr);
2224 
2225  WatchpointSP wp_sp =
2226  GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2227  uint32_t wp_index = LLDB_INVALID_INDEX32;
2228 
2229  if (wp_sp)
2230  wp_index = wp_sp->GetHardwareIndex();
2231 
2232  reason = "watchpoint";
2233  StreamString ostr;
2234  ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2235  description = std::string(ostr.GetString());
2236  } else if (key.compare("library") == 0) {
2237  auto error = LoadModules();
2238  if (error) {
2239  Log *log(
2241  LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2242  }
2243  } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2244  // fork includes child pid/tid in thread-id format
2245  StringExtractorGDBRemote thread_id{value};
2246  auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2247  if (!pid_tid) {
2248  Log *log(
2250  LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2252  }
2253 
2254  reason = key.str();
2255  StreamString ostr;
2256  ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2257  description = std::string(ostr.GetString());
2258  } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2259  uint32_t reg = UINT32_MAX;
2260  if (!key.getAsInteger(16, reg))
2261  expedited_register_map[reg] = std::string(std::move(value));
2262  }
2263  }
2264 
2265  if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2267  LLDB_LOG(log,
2268  "Received stop for incorrect PID = {0} (inferior PID = {1})",
2269  stop_pid, pid);
2270  return eStateInvalid;
2271  }
2272 
2273  if (tid == LLDB_INVALID_THREAD_ID) {
2274  // A thread id may be invalid if the response is old style 'S' packet
2275  // which does not provide the
2276  // thread information. So update the thread list and choose the first
2277  // one.
2278  UpdateThreadIDList();
2279 
2280  if (!m_thread_ids.empty()) {
2281  tid = m_thread_ids.front();
2282  }
2283  }
2284 
2285  ThreadSP thread_sp = SetThreadStopInfo(
2286  tid, expedited_register_map, signo, thread_name, reason, description,
2287  exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2288  associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2289  queue_kind, queue_serial_number);
2290 
2291  return eStateStopped;
2292  } break;
2293 
2294  case 'W':
2295  case 'X':
2296  // process exited
2297  return eStateExited;
2298 
2299  default:
2300  break;
2301  }
2302  return eStateInvalid;
2303 }
2304 
2305 void ProcessGDBRemote::RefreshStateAfterStop() {
2306  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2307 
2308  m_thread_ids.clear();
2309  m_thread_pcs.clear();
2310 
2311  // Set the thread stop info. It might have a "threads" key whose value is a
2312  // list of all thread IDs in the current process, so m_thread_ids might get
2313  // set.
2314  // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2315  if (m_thread_ids.empty()) {
2316  // No, we need to fetch the thread list manually
2317  UpdateThreadIDList();
2318  }
2319 
2320  // We might set some stop info's so make sure the thread list is up to
2321  // date before we do that or we might overwrite what was computed here.
2322  UpdateThreadListIfNeeded();
2323 
2324  if (m_last_stop_packet)
2325  SetThreadStopInfo(*m_last_stop_packet);
2326  m_last_stop_packet.reset();
2327 
2328  // If we have queried for a default thread id
2329  if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2330  m_thread_list.SetSelectedThreadByID(m_initial_tid);
2331  m_initial_tid = LLDB_INVALID_THREAD_ID;
2332  }
2333 
2334  // Let all threads recover from stopping and do any clean up based on the
2335  // previous thread state (if any).
2336  m_thread_list_real.RefreshStateAfterStop();
2337 }
2338 
2339 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2340  Status error;
2341 
2342  if (m_public_state.GetValue() == eStateAttaching) {
2343  // We are being asked to halt during an attach. We need to just close our
2344  // file handle and debugserver will go away, and we can be done...
2345  m_gdb_comm.Disconnect();
2346  } else
2347  caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2348  return error;
2349 }
2350 
2351 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2352  Status error;
2354  LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2355 
2356  error = m_gdb_comm.Detach(keep_stopped);
2357  if (log) {
2358  if (error.Success())
2359  log->PutCString(
2360  "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2361  else
2362  LLDB_LOGF(log,
2363  "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2364  error.AsCString() ? error.AsCString() : "<unknown error>");
2365  }
2366 
2367  if (!error.Success())
2368  return error;
2369 
2370  // Sleep for one second to let the process get all detached...
2371  StopAsyncThread();
2372 
2373  SetPrivateState(eStateDetached);
2374  ResumePrivateStateThread();
2375 
2376  // KillDebugserverProcess ();
2377  return error;
2378 }
2379 
2380 Status ProcessGDBRemote::DoDestroy() {
2381  Status error;
2383  LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2384 
2385  // There is a bug in older iOS debugservers where they don't shut down the
2386  // process they are debugging properly. If the process is sitting at a
2387  // breakpoint or an exception, this can cause problems with restarting. So
2388  // we check to see if any of our threads are stopped at a breakpoint, and if
2389  // so we remove all the breakpoints, resume the process, and THEN destroy it
2390  // again.
2391  //
2392  // Note, we don't have a good way to test the version of debugserver, but I
2393  // happen to know that the set of all the iOS debugservers which don't
2394  // support GetThreadSuffixSupported() and that of the debugservers with this
2395  // bug are equal. There really should be a better way to test this!
2396  //
2397  // We also use m_destroy_tried_resuming to make sure we only do this once, if
2398  // we resume and then halt and get called here to destroy again and we're
2399  // still at a breakpoint or exception, then we should just do the straight-
2400  // forward kill.
2401  //
2402  // And of course, if we weren't able to stop the process by the time we get
2403  // here, it isn't necessary (or helpful) to do any of this.
2404 
2405  if (!m_gdb_comm.GetThreadSuffixSupported() &&
2406  m_public_state.GetValue() != eStateRunning) {
2407  PlatformSP platform_sp = GetTarget().GetPlatform();
2408 
2409  if (platform_sp && platform_sp->GetName() &&
2410  platform_sp->GetName().GetStringRef() ==
2412  if (m_destroy_tried_resuming) {
2413  if (log)
2414  log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2415  "destroy once already, not doing it again.");
2416  } else {
2417  // At present, the plans are discarded and the breakpoints disabled
2418  // Process::Destroy, but we really need it to happen here and it
2419  // doesn't matter if we do it twice.
2420  m_thread_list.DiscardThreadPlans();
2421  DisableAllBreakpointSites();
2422 
2423  bool stop_looks_like_crash = false;
2424  ThreadList &threads = GetThreadList();
2425 
2426  {
2427  std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2428 
2429  size_t num_threads = threads.GetSize();
2430  for (size_t i = 0; i < num_threads; i++) {
2431  ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2432  StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2433  StopReason reason = eStopReasonInvalid;
2434  if (stop_info_sp)
2435  reason = stop_info_sp->GetStopReason();
2436  if (reason == eStopReasonBreakpoint ||
2437  reason == eStopReasonException) {
2438  LLDB_LOGF(log,
2439  "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2440  " stopped with reason: %s.",
2441  thread_sp->GetProtocolID(),
2442  stop_info_sp->GetDescription());
2443  stop_looks_like_crash = true;
2444  break;
2445  }
2446  }
2447  }
2448 
2449  if (stop_looks_like_crash) {
2450  if (log)
2451  log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2452  "breakpoint, continue and then kill.");
2453  m_destroy_tried_resuming = true;
2454 
2455  // If we are going to run again before killing, it would be good to
2456  // suspend all the threads before resuming so they won't get into
2457  // more trouble. Sadly, for the threads stopped with the breakpoint
2458  // or exception, the exception doesn't get cleared if it is
2459  // suspended, so we do have to run the risk of letting those threads
2460  // proceed a bit.
2461 
2462  {
2463  std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2464 
2465  size_t num_threads = threads.GetSize();
2466  for (size_t i = 0; i < num_threads; i++) {
2467  ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2468  StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2469  StopReason reason = eStopReasonInvalid;
2470  if (stop_info_sp)
2471  reason = stop_info_sp->GetStopReason();
2472  if (reason != eStopReasonBreakpoint &&
2473  reason != eStopReasonException) {
2474  LLDB_LOGF(log,
2475  "ProcessGDBRemote::DoDestroy() - Suspending "
2476  "thread: 0x%4.4" PRIx64 " before running.",
2477  thread_sp->GetProtocolID());
2478  thread_sp->SetResumeState(eStateSuspended);
2479  }
2480  }
2481  }
2482  Resume();
2483  return Destroy(false);
2484  }
2485  }
2486  }
2487  }
2488 
2489  // Interrupt if our inferior is running...
2490  int exit_status = SIGABRT;
2491  std::string exit_string;
2492 
2493  if (m_gdb_comm.IsConnected()) {
2494  if (m_public_state.GetValue() != eStateAttaching) {
2495  StringExtractorGDBRemote response;
2497  std::chrono::seconds(3));
2498 
2499  if (m_gdb_comm.SendPacketAndWaitForResponse("k", response,
2500  GetInterruptTimeout()) ==
2501  GDBRemoteCommunication::PacketResult::Success) {
2502  char packet_cmd = response.GetChar(0);
2503 
2504  if (packet_cmd == 'W' || packet_cmd == 'X') {
2505 #if defined(__APPLE__)
2506  // For Native processes on Mac OS X, we launch through the Host
2507  // Platform, then hand the process off to debugserver, which becomes
2508  // the parent process through "PT_ATTACH". Then when we go to kill
2509  // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2510  // we call waitpid which returns with no error and the correct
2511  // status. But amusingly enough that doesn't seem to actually reap
2512  // the process, but instead it is left around as a Zombie. Probably
2513  // the kernel is in the process of switching ownership back to lldb
2514  // which was the original parent, and gets confused in the handoff.
2515  // Anyway, so call waitpid here to finally reap it.
2516  PlatformSP platform_sp(GetTarget().GetPlatform());
2517  if (platform_sp && platform_sp->IsHost()) {
2518  int status;
2519  ::pid_t reap_pid;
2520  reap_pid = waitpid(GetID(), &status, WNOHANG);
2521  LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2522  }
2523 #endif
2524  SetLastStopPacket(response);
2525  ClearThreadIDList();
2526  exit_status = response.GetHexU8();
2527  } else {
2528  LLDB_LOGF(log,
2529  "ProcessGDBRemote::DoDestroy - got unexpected response "
2530  "to k packet: %s",
2531  response.GetStringRef().data());
2532  exit_string.assign("got unexpected response to k packet: ");
2533  exit_string.append(std::string(response.GetStringRef()));
2534  }
2535  } else {
2536  LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
2537  exit_string.assign("failed to send the k packet");
2538  }
2539  } else {
2540  LLDB_LOGF(log,
2541  "ProcessGDBRemote::DoDestroy - killed or interrupted while "
2542  "attaching");
2543  exit_string.assign("killed or interrupted while attaching.");
2544  }
2545  } else {
2546  // If we missed setting the exit status on the way out, do it here.
2547  // NB set exit status can be called multiple times, the first one sets the
2548  // status.
2549  exit_string.assign("destroying when not connected to debugserver");
2550  }
2551 
2552  SetExitStatus(exit_status, exit_string.c_str());
2553 
2554  StopAsyncThread();
2555  KillDebugserverProcess();
2556  return error;
2557 }
2558 
2559 void ProcessGDBRemote::SetLastStopPacket(
2560  const StringExtractorGDBRemote &response) {
2561  const bool did_exec =
2562  response.GetStringRef().find(";reason:exec;") != std::string::npos;
2563  if (did_exec) {
2565  LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2566 
2567  m_thread_list_real.Clear();
2568  m_thread_list.Clear();
2569  BuildDynamicRegisterInfo(true);
2570  m_gdb_comm.ResetDiscoverableSettings(did_exec);
2571  }
2572 
2573  m_last_stop_packet = response;
2574 }
2575 
2576 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2577  Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2578 }
2579 
2580 // Process Queries
2581 
2582 bool ProcessGDBRemote::IsAlive() {
2583  return m_gdb_comm.IsConnected() && Process::IsAlive();
2584 }
2585 
2586 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2587  // request the link map address via the $qShlibInfoAddr packet
2588  lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2589 
2590  // the loaded module list can also provides a link map address
2591  if (addr == LLDB_INVALID_ADDRESS) {
2592  llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2593  if (!list) {
2595  LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2596  } else {
2597  addr = list->m_link_map;
2598  }
2599  }
2600 
2601  return addr;
2602 }
2603 
2604 void ProcessGDBRemote::WillPublicStop() {
2605  // See if the GDB remote client supports the JSON threads info. If so, we
2606  // gather stop info for all threads, expedited registers, expedited memory,
2607  // runtime queue information (iOS and MacOSX only), and more. Expediting
2608  // memory will help stack backtracing be much faster. Expediting registers
2609  // will make sure we don't have to read the thread registers for GPRs.
2610  m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2611 
2612  if (m_jthreadsinfo_sp) {
2613  // Now set the stop info for each thread and also expedite any registers
2614  // and memory that was in the jThreadsInfo response.
2615  StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2616  if (thread_infos) {
2617  const size_t n = thread_infos->GetSize();
2618  for (size_t i = 0; i < n; ++i) {
2619  StructuredData::Dictionary *thread_dict =
2620  thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2621  if (thread_dict)
2622  SetThreadStopInfo(thread_dict);
2623  }
2624  }
2625  }
2626 }
2627 
2628 // Process Memory
2629 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2630  Status &error) {
2631  GetMaxMemorySize();
2632  bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2633  // M and m packets take 2 bytes for 1 byte of memory
2634  size_t max_memory_size =
2635  binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2636  if (size > max_memory_size) {
2637  // Keep memory read sizes down to a sane limit. This function will be
2638  // called multiple times in order to complete the task by
2639  // lldb_private::Process so it is ok to do this.
2640  size = max_memory_size;
2641  }
2642 
2643  char packet[64];
2644  int packet_len;
2645  packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2646  binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2647  (uint64_t)size);
2648  assert(packet_len + 1 < (int)sizeof(packet));
2649  UNUSED_IF_ASSERT_DISABLED(packet_len);
2650  StringExtractorGDBRemote response;
2651  if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2652  GetInterruptTimeout()) ==
2653  GDBRemoteCommunication::PacketResult::Success) {
2654  if (response.IsNormalResponse()) {
2655  error.Clear();
2656  if (binary_memory_read) {
2657  // The lower level GDBRemoteCommunication packet receive layer has
2658  // already de-quoted any 0x7d character escaping that was present in
2659  // the packet
2660 
2661  size_t data_received_size = response.GetBytesLeft();
2662  if (data_received_size > size) {
2663  // Don't write past the end of BUF if the remote debug server gave us
2664  // too much data for some reason.
2665  data_received_size = size;
2666  }
2667  memcpy(buf, response.GetStringRef().data(), data_received_size);
2668  return data_received_size;
2669  } else {
2670  return response.GetHexBytes(
2671  llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2672  }
2673  } else if (response.IsErrorResponse())
2674  error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2675  else if (response.IsUnsupportedResponse())
2676  error.SetErrorStringWithFormat(
2677  "GDB server does not support reading memory");
2678  else
2679  error.SetErrorStringWithFormat(
2680  "unexpected response to GDB server memory read packet '%s': '%s'",
2681  packet, response.GetStringRef().data());
2682  } else {
2683  error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2684  }
2685  return 0;
2686 }
2687 
2688 bool ProcessGDBRemote::SupportsMemoryTagging() {
2689  return m_gdb_comm.GetMemoryTaggingSupported();
2690 }
2691 
2692 llvm::Expected<std::vector<uint8_t>>
2693 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2694  int32_t type) {
2695  // By this point ReadMemoryTags has validated that tagging is enabled
2696  // for this target/process/address.
2697  DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2698  if (!buffer_sp) {
2699  return llvm::createStringError(llvm::inconvertibleErrorCode(),
2700  "Error reading memory tags from remote");
2701  }
2702 
2703  // Return the raw tag data
2704  llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2705  std::vector<uint8_t> got;
2706  got.reserve(tag_data.size());
2707  std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2708  return got;
2709 }
2710 
2711 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2712  int32_t type,
2713  const std::vector<uint8_t> &tags) {
2714  // By now WriteMemoryTags should have validated that tagging is enabled
2715  // for this target/process.
2716  return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2717 }
2718 
2719 Status ProcessGDBRemote::WriteObjectFile(
2720  std::vector<ObjectFile::LoadableData> entries) {
2721  Status error;
2722  // Sort the entries by address because some writes, like those to flash
2723  // memory, must happen in order of increasing address.
2724  std::stable_sort(
2725  std::begin(entries), std::end(entries),
2726  [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2727  return a.Dest < b.Dest;
2728  });
2729  m_allow_flash_writes = true;
2730  error = Process::WriteObjectFile(entries);
2731  if (error.Success())
2732  error = FlashDone();
2733  else
2734  // Even though some of the writing failed, try to send a flash done if some
2735  // of the writing succeeded so the flash state is reset to normal, but
2736  // don't stomp on the error status that was set in the write failure since
2737  // that's the one we want to report back.
2738  FlashDone();
2739  m_allow_flash_writes = false;
2740  return error;
2741 }
2742 
2743 bool ProcessGDBRemote::HasErased(FlashRange range) {
2744  auto size = m_erased_flash_ranges.GetSize();
2745  for (size_t i = 0; i < size; ++i)
2746  if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2747  return true;
2748  return false;
2749 }
2750 
2751 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2752  Status status;
2753 
2754  MemoryRegionInfo region;
2755  status = GetMemoryRegionInfo(addr, region);
2756  if (!status.Success())
2757  return status;
2758 
2759  // The gdb spec doesn't say if erasures are allowed across multiple regions,
2760  // but we'll disallow it to be safe and to keep the logic simple by worring
2761  // about only one region's block size. DoMemoryWrite is this function's
2762  // primary user, and it can easily keep writes within a single memory region
2763  if (addr + size > region.GetRange().GetRangeEnd()) {
2764  status.SetErrorString("Unable to erase flash in multiple regions");
2765  return status;
2766  }
2767 
2768  uint64_t blocksize = region.GetBlocksize();
2769  if (blocksize == 0) {
2770  status.SetErrorString("Unable to erase flash because blocksize is 0");
2771  return status;
2772  }
2773 
2774  // Erasures can only be done on block boundary adresses, so round down addr
2775  // and round up size
2776  lldb::addr_t block_start_addr = addr - (addr % blocksize);
2777  size += (addr - block_start_addr);
2778  if ((size % blocksize) != 0)
2779  size += (blocksize - size % blocksize);
2780 
2781  FlashRange range(block_start_addr, size);
2782 
2783  if (HasErased(range))
2784  return status;
2785 
2786  // We haven't erased the entire range, but we may have erased part of it.
2787  // (e.g., block A is already erased and range starts in A and ends in B). So,
2788  // adjust range if necessary to exclude already erased blocks.
2789  if (!m_erased_flash_ranges.IsEmpty()) {
2790  // Assuming that writes and erasures are done in increasing addr order,
2791  // because that is a requirement of the vFlashWrite command. Therefore, we
2792  // only need to look at the last range in the list for overlap.
2793  const auto &last_range = *m_erased_flash_ranges.Back();
2794  if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2795  auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2796  // overlap will be less than range.GetByteSize() or else HasErased()
2797  // would have been true
2798  range.SetByteSize(range.GetByteSize() - overlap);
2799  range.SetRangeBase(range.GetRangeBase() + overlap);
2800  }
2801  }
2802 
2803  StreamString packet;
2804  packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2805  (uint64_t)range.GetByteSize());
2806 
2807  StringExtractorGDBRemote response;
2808  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2809  GetInterruptTimeout()) ==
2810  GDBRemoteCommunication::PacketResult::Success) {
2811  if (response.IsOKResponse()) {
2812  m_erased_flash_ranges.Insert(range, true);
2813  } else {
2814  if (response.IsErrorResponse())
2815  status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2816  addr);
2817  else if (response.IsUnsupportedResponse())
2818  status.SetErrorStringWithFormat("GDB server does not support flashing");
2819  else
2820  status.SetErrorStringWithFormat(
2821  "unexpected response to GDB server flash erase packet '%s': '%s'",
2822  packet.GetData(), response.GetStringRef().data());
2823  }
2824  } else {
2825  status.SetErrorStringWithFormat("failed to send packet: '%s'",
2826  packet.GetData());
2827  }
2828  return status;
2829 }
2830 
2831 Status ProcessGDBRemote::FlashDone() {
2832  Status status;
2833  // If we haven't erased any blocks, then we must not have written anything
2834  // either, so there is no need to actually send a vFlashDone command
2835  if (m_erased_flash_ranges.IsEmpty())
2836  return status;
2837  StringExtractorGDBRemote response;
2838  if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2839  GetInterruptTimeout()) ==
2840  GDBRemoteCommunication::PacketResult::Success) {
2841  if (response.IsOKResponse()) {
2842  m_erased_flash_ranges.Clear();
2843  } else {
2844  if (response.IsErrorResponse())
2845  status.SetErrorStringWithFormat("flash done failed");
2846  else if (response.IsUnsupportedResponse())
2847  status.SetErrorStringWithFormat("GDB server does not support flashing");
2848  else
2849  status.SetErrorStringWithFormat(
2850  "unexpected response to GDB server flash done packet: '%s'",
2851  response.GetStringRef().data());
2852  }
2853  } else {
2854  status.SetErrorStringWithFormat("failed to send flash done packet");
2855  }
2856  return status;
2857 }
2858 
2859 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2860  size_t size, Status &error) {
2861  GetMaxMemorySize();
2862  // M and m packets take 2 bytes for 1 byte of memory
2863  size_t max_memory_size = m_max_memory_size / 2;
2864  if (size > max_memory_size) {
2865  // Keep memory read sizes down to a sane limit. This function will be
2866  // called multiple times in order to complete the task by
2867  // lldb_private::Process so it is ok to do this.
2868  size = max_memory_size;
2869  }
2870 
2871  StreamGDBRemote packet;
2872 
2873  MemoryRegionInfo region;
2874  Status region_status = GetMemoryRegionInfo(addr, region);
2875 
2876  bool is_flash =
2877  region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2878 
2879  if (is_flash) {
2880  if (!m_allow_flash_writes) {
2881  error.SetErrorString("Writing to flash memory is not allowed");
2882  return 0;
2883  }
2884  // Keep the write within a flash memory region
2885  if (addr + size > region.GetRange().GetRangeEnd())
2886  size = region.GetRange().GetRangeEnd() - addr;
2887  // Flash memory must be erased before it can be written
2888  error = FlashErase(addr, size);
2889  if (!error.Success())
2890  return 0;
2891  packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2892  packet.PutEscapedBytes(buf, size);
2893  } else {
2894  packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2895  packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2897  }
2898  StringExtractorGDBRemote response;
2899  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2900  GetInterruptTimeout()) ==
2901  GDBRemoteCommunication::PacketResult::Success) {
2902  if (response.IsOKResponse()) {
2903  error.Clear();
2904  return size;
2905  } else if (response.IsErrorResponse())
2906  error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2907  addr);
2908  else if (response.IsUnsupportedResponse())
2909  error.SetErrorStringWithFormat(
2910  "GDB server does not support writing memory");
2911  else
2912  error.SetErrorStringWithFormat(
2913  "unexpected response to GDB server memory write packet '%s': '%s'",
2914  packet.GetData(), response.GetStringRef().data());
2915  } else {
2916  error.SetErrorStringWithFormat("failed to send packet: '%s'",
2917  packet.GetData());
2918  }
2919  return 0;
2920 }
2921 
2922 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2923  uint32_t permissions,
2924  Status &error) {
2925  Log *log(
2927  addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2928 
2929  if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2930  allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2931  if (allocated_addr != LLDB_INVALID_ADDRESS ||
2932  m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2933  return allocated_addr;
2934  }
2935 
2936  if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2937  // Call mmap() to create memory in the inferior..
2938  unsigned prot = 0;
2939  if (permissions & lldb::ePermissionsReadable)
2940  prot |= eMmapProtRead;
2941  if (permissions & lldb::ePermissionsWritable)
2942  prot |= eMmapProtWrite;
2943  if (permissions & lldb::ePermissionsExecutable)
2944  prot |= eMmapProtExec;
2945 
2946  if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2948  m_addr_to_mmap_size[allocated_addr] = size;
2949  else {
2950  allocated_addr = LLDB_INVALID_ADDRESS;
2951  LLDB_LOGF(log,
2952  "ProcessGDBRemote::%s no direct stub support for memory "
2953  "allocation, and InferiorCallMmap also failed - is stub "
2954  "missing register context save/restore capability?",
2955  __FUNCTION__);
2956  }
2957  }
2958 
2959  if (allocated_addr == LLDB_INVALID_ADDRESS)
2960  error.SetErrorStringWithFormat(
2961  "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2962  (uint64_t)size, GetPermissionsAsCString(permissions));
2963  else
2964  error.Clear();
2965  return allocated_addr;
2966 }
2967 
2968 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2969  MemoryRegionInfo &region_info) {
2970 
2971  Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2972  return error;
2973 }
2974 
2975 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2976 
2977  Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2978  return error;
2979 }
2980 
2981 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2982  Status error(m_gdb_comm.GetWatchpointSupportInfo(
2983  num, after, GetTarget().GetArchitecture()));
2984  return error;
2985 }
2986 
2987 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2988  Status error;
2989  LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2990 
2991  switch (supported) {
2992  case eLazyBoolCalculate:
2993  // We should never be deallocating memory without allocating memory first
2994  // so we should never get eLazyBoolCalculate
2995  error.SetErrorString(
2996  "tried to deallocate memory without ever allocating memory");
2997  break;
2998 
2999  case eLazyBoolYes:
3000  if (!m_gdb_comm.DeallocateMemory(addr))
3001  error.SetErrorStringWithFormat(
3002  "unable to deallocate memory at 0x%" PRIx64, addr);
3003  break;
3004 
3005  case eLazyBoolNo:
3006  // Call munmap() to deallocate memory in the inferior..
3007  {
3008  MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3009  if (pos != m_addr_to_mmap_size.end() &&
3010  InferiorCallMunmap(this, addr, pos->second))
3011  m_addr_to_mmap_size.erase(pos);
3012  else
3013  error.SetErrorStringWithFormat(
3014  "unable to deallocate memory at 0x%" PRIx64, addr);
3015  }
3016  break;
3017  }
3018 
3019  return error;
3020 }
3021 
3022 // Process STDIO
3023 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3024  Status &error) {
3025  if (m_stdio_communication.IsConnected()) {
3026  ConnectionStatus status;
3027  m_stdio_communication.Write(src, src_len, status, nullptr);
3028  } else if (m_stdin_forward) {
3029  m_gdb_comm.SendStdinNotification(src, src_len);
3030  }
3031  return 0;
3032 }
3033 
3034 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3035  Status error;
3036  assert(bp_site != nullptr);
3037 
3038  // Get logging info
3040  user_id_t site_id = bp_site->GetID();
3041 
3042  // Get the breakpoint address
3043  const addr_t addr = bp_site->GetLoadAddress();
3044 
3045  // Log that a breakpoint was requested
3046  LLDB_LOGF(log,
3047  "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3048  ") address = 0x%" PRIx64,
3049  site_id, (uint64_t)addr);
3050 
3051  // Breakpoint already exists and is enabled
3052  if (bp_site->IsEnabled()) {
3053  LLDB_LOGF(log,
3054  "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3055  ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3056  site_id, (uint64_t)addr);
3057  return error;
3058  }
3059 
3060  // Get the software breakpoint trap opcode size
3061  const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3062 
3063  // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3064  // breakpoint type is supported by the remote stub. These are set to true by
3065  // default, and later set to false only after we receive an unimplemented
3066  // response when sending a breakpoint packet. This means initially that
3067  // unless we were specifically instructed to use a hardware breakpoint, LLDB
3068  // will attempt to set a software breakpoint. HardwareRequired() also queries
3069  // a boolean variable which indicates if the user specifically asked for
3070  // hardware breakpoints. If true then we will skip over software
3071  // breakpoints.
3072  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3073  (!bp_site->HardwareRequired())) {
3074  // Try to send off a software breakpoint packet ($Z0)
3075  uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3076  eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3077  if (error_no == 0) {
3078  // The breakpoint was placed successfully
3079  bp_site->SetEnabled(true);
3081  return error;
3082  }
3083 
3084  // SendGDBStoppointTypePacket() will return an error if it was unable to
3085  // set this breakpoint. We need to differentiate between a error specific
3086  // to placing this breakpoint or if we have learned that this breakpoint
3087  // type is unsupported. To do this, we must test the support boolean for
3088  // this breakpoint type to see if it now indicates that this breakpoint
3089  // type is unsupported. If they are still supported then we should return
3090  // with the error code. If they are now unsupported, then we would like to
3091  // fall through and try another form of breakpoint.
3092  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3093  if (error_no != UINT8_MAX)
3094  error.SetErrorStringWithFormat(
3095  "error: %d sending the breakpoint request", error_no);
3096  else
3097  error.SetErrorString("error sending the breakpoint request");
3098  return error;
3099  }
3100 
3101  // We reach here when software breakpoints have been found to be
3102  // unsupported. For future calls to set a breakpoint, we will not attempt
3103  // to set a breakpoint with a type that is known not to be supported.
3104  LLDB_LOGF(log, "Software breakpoints are unsupported");
3105 
3106  // So we will fall through and try a hardware breakpoint
3107  }
3108 
3109  // The process of setting a hardware breakpoint is much the same as above.
3110  // We check the supported boolean for this breakpoint type, and if it is
3111  // thought to be supported then we will try to set this breakpoint with a
3112  // hardware breakpoint.
3113  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3114  // Try to send off a hardware breakpoint packet ($Z1)
3115  uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3116  eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3117  if (error_no == 0) {
3118  // The breakpoint was placed successfully
3119  bp_site->SetEnabled(true);
3121  return error;
3122  }
3123 
3124  // Check if the error was something other then an unsupported breakpoint
3125  // type
3126  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3127  // Unable to set this hardware breakpoint
3128  if (error_no != UINT8_MAX)
3129  error.SetErrorStringWithFormat(
3130  "error: %d sending the hardware breakpoint request "
3131  "(hardware breakpoint resources might be exhausted or unavailable)",
3132  error_no);
3133  else
3134  error.SetErrorString("error sending the hardware breakpoint request "
3135  "(hardware breakpoint resources "
3136  "might be exhausted or unavailable)");
3137  return error;
3138  }
3139 
3140  // We will reach here when the stub gives an unsupported response to a
3141  // hardware breakpoint
3142  LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3143 
3144  // Finally we will falling through to a #trap style breakpoint
3145  }
3146 
3147  // Don't fall through when hardware breakpoints were specifically requested
3148  if (bp_site->HardwareRequired()) {
3149  error.SetErrorString("hardware breakpoints are not supported");
3150  return error;
3151  }
3152 
3153  // As a last resort we want to place a manual breakpoint. An instruction is
3154  // placed into the process memory using memory write packets.
3155  return EnableSoftwareBreakpoint(bp_site);
3156 }
3157 
3158 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3159  Status error;
3160  assert(bp_site != nullptr);
3161  addr_t addr = bp_site->GetLoadAddress();
3162  user_id_t site_id = bp_site->GetID();
3164  LLDB_LOGF(log,
3165  "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3166  ") addr = 0x%8.8" PRIx64,
3167  site_id, (uint64_t)addr);
3168 
3169  if (bp_site->IsEnabled()) {
3170  const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3171 
3172  BreakpointSite::Type bp_type = bp_site->GetType();
3173  switch (bp_type) {
3175  error = DisableSoftwareBreakpoint(bp_site);
3176  break;
3177 
3179  if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3180  addr, bp_op_size,
3181  GetInterruptTimeout()))
3182  error.SetErrorToGenericError();
3183  break;
3184 
3186  if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3187  addr, bp_op_size,
3188  GetInterruptTimeout()))
3189  error.SetErrorToGenericError();
3190  } break;
3191  }
3192  if (error.Success())
3193  bp_site->SetEnabled(false);
3194  } else {
3195  LLDB_LOGF(log,
3196  "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3197  ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3198  site_id, (uint64_t)addr);
3199  return error;
3200  }
3201 
3202  if (error.Success())
3203  error.SetErrorToGenericError();
3204  return error;
3205 }
3206 
3207 // Pre-requisite: wp != NULL.
3209  assert(wp);
3210  bool watch_read = wp->WatchpointRead();
3211  bool watch_write = wp->WatchpointWrite();
3212 
3213  // watch_read and watch_write cannot both be false.
3214  assert(watch_read || watch_write);
3215  if (watch_read && watch_write)
3216  return eWatchpointReadWrite;
3217  else if (watch_read)
3218  return eWatchpointRead;
3219  else // Must be watch_write, then.
3220  return eWatchpointWrite;
3221 }
3222 
3223 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3224  Status error;
3225  if (wp) {
3226  user_id_t watchID = wp->GetID();
3227  addr_t addr = wp->GetLoadAddress();
3228  Log *log(
3230  LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3231  watchID);
3232  if (wp->IsEnabled()) {
3233  LLDB_LOGF(log,
3234  "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3235  ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3236  watchID, (uint64_t)addr);
3237  return error;
3238  }
3239 
3241  // Pass down an appropriate z/Z packet...
3242  if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3243  if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3244  wp->GetByteSize(),
3245  GetInterruptTimeout()) == 0) {
3246  wp->SetEnabled(true, notify);
3247  return error;
3248  } else
3249  error.SetErrorString("sending gdb watchpoint packet failed");
3250  } else
3251  error.SetErrorString("watchpoints not supported");
3252  } else {
3253  error.SetErrorString("Watchpoint argument was NULL.");
3254  }
3255  if (error.Success())
3256  error.SetErrorToGenericError();
3257  return error;
3258 }
3259 
3260 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3261  Status error;
3262  if (wp) {
3263  user_id_t watchID = wp->GetID();
3264 
3265  Log *log(
3267 
3268  addr_t addr = wp->GetLoadAddress();
3269 
3270  LLDB_LOGF(log,
3271  "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3272  ") addr = 0x%8.8" PRIx64,
3273  watchID, (uint64_t)addr);
3274 
3275  if (!wp->IsEnabled()) {
3276  LLDB_LOGF(log,
3277  "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3278  ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3279  watchID, (uint64_t)addr);
3280  // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3281  // attempt might come from the user-supplied actions, we'll route it in
3282  // order for the watchpoint object to intelligently process this action.
3283  wp->SetEnabled(false, notify);
3284  return error;
3285  }
3286 
3287  if (wp->IsHardware()) {
3289  // Pass down an appropriate z/Z packet...
3290  if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3291  wp->GetByteSize(),
3292  GetInterruptTimeout()) == 0) {
3293  wp->SetEnabled(false, notify);
3294  return error;
3295  } else
3296  error.SetErrorString("sending gdb watchpoint packet failed");
3297  }
3298  // TODO: clear software watchpoints if we implement them
3299  } else {
3300  error.SetErrorString("Watchpoint argument was NULL.");
3301  }
3302  if (error.Success())
3303  error.SetErrorToGenericError();
3304  return error;
3305 }
3306 
3307 void ProcessGDBRemote::Clear() {
3308  m_thread_list_real.Clear();
3309  m_thread_list.Clear();
3310 }
3311 
3312 Status ProcessGDBRemote::DoSignal(int signo) {
3313  Status error;
3315  LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3316 
3317  if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3318  error.SetErrorStringWithFormat("failed to send signal %i", signo);
3319  return error;
3320 }
3321 
3322 Status
3323 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3324  // Make sure we aren't already connected?
3325  if (m_gdb_comm.IsConnected())
3326  return Status();
3327 
3328  PlatformSP platform_sp(GetTarget().GetPlatform());
3329  if (platform_sp && !platform_sp->IsHost())
3330  return Status("Lost debug server connection");
3331 
3332  auto error = LaunchAndConnectToDebugserver(process_info);
3333  if (error.Fail()) {
3334  const char *error_string = error.AsCString();
3335  if (error_string == nullptr)
3336  error_string = "unable to launch " DEBUGSERVER_BASENAME;
3337  }
3338  return error;
3339 }
3340 #if !defined(_WIN32)
3341 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3342 #endif
3343 
3344 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3345 static bool SetCloexecFlag(int fd) {
3346 #if defined(FD_CLOEXEC)
3347  int flags = ::fcntl(fd, F_GETFD);
3348  if (flags == -1)
3349  return false;
3350  return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3351 #else
3352  return false;
3353 #endif
3354 }
3355 #endif
3356 
3357 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3358  const ProcessInfo &process_info) {
3359  using namespace std::placeholders; // For _1, _2, etc.
3360 
3361  Status error;
3362  if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3363  // If we locate debugserver, keep that located version around
3364  static FileSpec g_debugserver_file_spec;
3365 
3366  ProcessLaunchInfo debugserver_launch_info;
3367  // Make debugserver run in its own session so signals generated by special
3368  // terminal key sequences (^C) don't affect debugserver.
3369  debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3370 
3371  const std::weak_ptr<ProcessGDBRemote> this_wp =
3372  std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3373  debugserver_launch_info.SetMonitorProcessCallback(
3374  std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3375  debugserver_launch_info.SetUserID(process_info.GetUserID());
3376 
3377 #if defined(__APPLE__)
3378  // On macOS 11, we need to support x86_64 applications translated to
3379  // arm64. We check whether a binary is translated and spawn the correct
3380  // debugserver accordingly.
3381  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3382  static_cast<int>(process_info.GetProcessID()) };
3383  struct kinfo_proc processInfo;
3384  size_t bufsize = sizeof(processInfo);
3385  if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3386  &bufsize, NULL, 0) == 0 && bufsize > 0) {
3387  if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3388  FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3389  debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3390  }
3391  }
3392 #endif
3393 
3394  int communication_fd = -1;
3395 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3396  // Use a socketpair on non-Windows systems for security and performance
3397  // reasons.
3398  int sockets[2]; /* the pair of socket descriptors */
3399  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3400  error.SetErrorToErrno();
3401  return error;
3402  }
3403 
3404  int our_socket = sockets[0];
3405  int gdb_socket = sockets[1];
3406  auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3407  auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3408 
3409  // Don't let any child processes inherit our communication socket
3410  SetCloexecFlag(our_socket);
3411  communication_fd = gdb_socket;
3412 #endif
3413 
3414  error = m_gdb_comm.StartDebugserverProcess(
3415  nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3416  nullptr, nullptr, communication_fd);
3417 
3418  if (error.Success())
3419  m_debugserver_pid = debugserver_launch_info.GetProcessID();
3420  else
3421  m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3422 
3423  if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3424 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3425  // Our process spawned correctly, we can now set our connection to use
3426  // our end of the socket pair
3427  cleanup_our.release();
3428  m_gdb_comm.SetConnection(
3429  std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3430 #endif
3431  StartAsyncThread();
3432  }
3433 
3434  if (error.Fail()) {
3436 
3437  LLDB_LOGF(log, "failed to start debugserver process: %s",
3438  error.AsCString());
3439  return error;
3440  }
3441 
3442  if (m_gdb_comm.IsConnected()) {
3443  // Finish the connection process by doing the handshake without
3444  // connecting (send NULL URL)
3445  error = ConnectToDebugserver("");
3446  } else {
3447  error.SetErrorString("connection failed");
3448  }
3449  }
3450  return error;
3451 }
3452 
3453 bool ProcessGDBRemote::MonitorDebugserverProcess(
3454  std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3455  bool exited, // True if the process did exit
3456  int signo, // Zero for no signal
3457  int exit_status // Exit value of process if signal is zero
3458 ) {
3459  // "debugserver_pid" argument passed in is the process ID for debugserver
3460  // that we are tracking...
3462  const bool handled = true;
3463 
3464  LLDB_LOGF(log,
3465  "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3466  ", signo=%i (0x%x), exit_status=%i)",
3467  __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3468 
3469  std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3470  LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3471  static_cast<void *>(process_sp.get()));
3472  if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3473  return handled;
3474 
3475  // Sleep for a half a second to make sure our inferior process has time to
3476  // set its exit status before we set it incorrectly when both the debugserver
3477  // and the inferior process shut down.
3478  std::this_thread::sleep_for(std::chrono::milliseconds(500));
3479 
3480  // If our process hasn't yet exited, debugserver might have died. If the
3481  // process did exit, then we are reaping it.
3482  const StateType state = process_sp->GetState();
3483 
3484  if (state != eStateInvalid && state != eStateUnloaded &&
3485  state != eStateExited && state != eStateDetached) {
3486  char error_str[1024];
3487  if (signo) {
3488  const char *signal_cstr =
3489  process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3490  if (signal_cstr)
3491  ::snprintf(error_str, sizeof(error_str),
3492  DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3493  else
3494  ::snprintf(error_str, sizeof(error_str),
3495  DEBUGSERVER_BASENAME " died with signal %i", signo);
3496  } else {
3497  ::snprintf(error_str, sizeof(error_str),
3498  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3499  exit_status);
3500  }
3501 
3502  process_sp->SetExitStatus(-1, error_str);
3503  }
3504  // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3505  // longer has a debugserver instance
3506  process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3507  return handled;
3508 }
3509 
3510 void ProcessGDBRemote::KillDebugserverProcess() {
3511  m_gdb_comm.Disconnect();
3512  if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3513  Host::Kill(m_debugserver_pid, SIGINT);
3514  m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3515  }
3516 }
3517 
3518 void ProcessGDBRemote::Initialize() {
3519  static llvm::once_flag g_once_flag;
3520 
3521  llvm::call_once(g_once_flag, []() {
3522  PluginManager::RegisterPlugin(GetPluginNameStatic(),
3523  GetPluginDescriptionStatic(), CreateInstance,
3524  DebuggerInitialize);
3525  });
3526 }
3527 
3528 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3530  debugger, PluginProperties::GetSettingName())) {
3531  const bool is_global_setting = true;
3533  debugger, GetGlobalPluginProperties().GetValueProperties(),
3534  ConstString("Properties for the gdb-remote process plug-in."),
3535  is_global_setting);
3536  }
3537 }
3538 
3539 bool ProcessGDBRemote::StartAsyncThread() {
3541 
3542  LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3543 
3544  std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3545  if (!m_async_thread.IsJoinable()) {
3546  // Create a thread that watches our internal state and controls which
3547  // events make it to clients (into the DCProcess event queue).
3548 
3549  llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
3550  "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
3551  if (!async_thread) {
3553  async_thread.takeError(),
3554  "failed to launch host thread: {}");
3555  return false;
3556  }
3557  m_async_thread = *async_thread;
3558  } else
3559  LLDB_LOGF(log,
3560  "ProcessGDBRemote::%s () - Called when Async thread was "
3561  "already running.",
3562  __FUNCTION__);
3563 
3564  return m_async_thread.IsJoinable();
3565 }
3566 
3567 void ProcessGDBRemote::StopAsyncThread() {
3569 
3570  LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3571 
3572  std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3573  if (m_async_thread.IsJoinable()) {
3574  m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3575 
3576  // This will shut down the async thread.
3577  m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3578 
3579  // Stop the stdio thread
3580  m_async_thread.Join(nullptr);
3581  m_async_thread.Reset();
3582  } else
3583  LLDB_LOGF(
3584  log,
3585  "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3586  __FUNCTION__);
3587 }
3588 
3589 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3590  ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3591 
3593  LLDB_LOGF(log,
3594  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3595  ") thread starting...",
3596  __FUNCTION__, arg, process->GetID());
3597 
3598  EventSP event_sp;
3599 
3600  // We need to ignore any packets that come in after we have
3601  // have decided the process has exited. There are some
3602  // situations, for instance when we try to interrupt a running
3603  // process and the interrupt fails, where another packet might
3604  // get delivered after we've decided to give up on the process.
3605  // But once we've decided we are done with the process we will
3606  // not be in a state to do anything useful with new packets.
3607  // So it is safer to simply ignore any remaining packets by
3608  // explicitly checking for eStateExited before reentering the
3609  // fetch loop.
3610 
3611  bool done = false;
3612  while (!done && process->GetPrivateState() != eStateExited) {
3613  LLDB_LOGF(log,
3614  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3615  ") listener.WaitForEvent (NULL, event_sp)...",
3616  __FUNCTION__, arg, process->GetID());
3617 
3618  if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3619  const uint32_t event_type = event_sp->GetType();
3620  if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3621  LLDB_LOGF(log,
3622  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3623  ") Got an event of type: %d...",
3624  __FUNCTION__, arg, process->GetID(), event_type);
3625 
3626  switch (event_type) {
3627  case eBroadcastBitAsyncContinue: {
3628  const EventDataBytes *continue_packet =
3629  EventDataBytes::GetEventDataFromEvent(event_sp.get());
3630 
3631  if (continue_packet) {
3632  const char *continue_cstr =
3633  (const char *)continue_packet->GetBytes();
3634  const size_t continue_cstr_len = continue_packet->GetByteSize();
3635  LLDB_LOGF(log,
3636  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3637  ") got eBroadcastBitAsyncContinue: %s",
3638  __FUNCTION__, arg, process->GetID(), continue_cstr);
3639 
3640  if (::strstr(continue_cstr, "vAttach") == nullptr)
3641  process->SetPrivateState(eStateRunning);
3642  StringExtractorGDBRemote response;
3643 
3644  StateType stop_state =
3646  *process, *process->GetUnixSignals(),
3647  llvm::StringRef(continue_cstr, continue_cstr_len),
3648  process->GetInterruptTimeout(), response);
3649 
3650  // We need to immediately clear the thread ID list so we are sure
3651  // to get a valid list of threads. The thread ID list might be
3652  // contained within the "response", or the stop reply packet that
3653  // caused the stop. So clear it now before we give the stop reply
3654  // packet to the process using the
3655  // process->SetLastStopPacket()...
3656  process->ClearThreadIDList();
3657 
3658  switch (stop_state) {
3659  case eStateStopped:
3660  case eStateCrashed:
3661  case eStateSuspended:
3662  process->SetLastStopPacket(response);
3663  process->SetPrivateState(stop_state);
3664  break;
3665 
3666  case eStateExited: {
3667  process->SetLastStopPacket(response);
3668  process->ClearThreadIDList();
3669  response.SetFilePos(1);
3670 
3671  int exit_status = response.GetHexU8();
3672  std::string desc_string;
3673  if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3674  llvm::StringRef desc_str;
3675  llvm::StringRef desc_token;
3676  while (response.GetNameColonValue(desc_token, desc_str)) {
3677  if (desc_token != "description")
3678  continue;
3679  StringExtractor extractor(desc_str);
3680  extractor.GetHexByteString(desc_string);
3681  }
3682  }
3683  process->SetExitStatus(exit_status, desc_string.c_str());
3684  done = true;
3685  break;
3686  }
3687  case eStateInvalid: {
3688  // Check to see if we were trying to attach and if we got back
3689  // the "E87" error code from debugserver -- this indicates that
3690  // the process is not debuggable. Return a slightly more
3691  // helpful error message about why the attach failed.
3692  if (::strstr(continue_cstr, "vAttach") != nullptr &&
3693  response.GetError() == 0x87) {
3694  process->SetExitStatus(-1, "cannot attach to process due to "
3695  "System Integrity Protection");
3696  } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3697  response.GetStatus().Fail()) {
3698  process->SetExitStatus(-1, response.GetStatus().AsCString());
3699  } else {
3700  process->SetExitStatus(-1, "lost connection");
3701  }
3702  done = true;
3703  break;
3704  }
3705 
3706  default:
3707  process->SetPrivateState(stop_state);
3708  break;
3709  } // switch(stop_state)
3710  } // if (continue_packet)
3711  } // case eBroadcastBitAsyncContinue
3712  break;
3713 
3714  case eBroadcastBitAsyncThreadShouldExit:
3715  LLDB_LOGF(log,
3716  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3717  ") got eBroadcastBitAsyncThreadShouldExit...",
3718  __FUNCTION__, arg, process->GetID());
3719  done = true;
3720  break;
3721 
3722  default:
3723  LLDB_LOGF(log,
3724  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3725  ") got unknown event 0x%8.8x",
3726  __FUNCTION__, arg, process->GetID(), event_type);
3727  done = true;
3728  break;
3729  }
3730  } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3731  switch (event_type) {
3732  case Communication::eBroadcastBitReadThreadDidExit:
3733  process->SetExitStatus(-1, "lost connection");
3734  done = true;
3735  break;
3736 
3737  default:
3738  LLDB_LOGF(log,
3739  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3740  ") got unknown event 0x%8.8x",
3741  __FUNCTION__, arg, process->GetID(), event_type);
3742  done = true;
3743  break;
3744  }
3745  }
3746  } else {
3747  LLDB_LOGF(log,
3748  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3749  ") listener.WaitForEvent (NULL, event_sp) => false",
3750  __FUNCTION__, arg, process->GetID());
3751  done = true;
3752  }
3753  }
3754 
3755  LLDB_LOGF(log,
3756  "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3757  ") thread exiting...",
3758  __FUNCTION__, arg, process->GetID());
3759 
3760  return {};
3761 }
3762 
3763 // uint32_t
3764 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3765 // &matches, std::vector<lldb::pid_t> &pids)
3766 //{
3767 // // If we are planning to launch the debugserver remotely, then we need to
3768 // fire up a debugserver
3769 // // process and ask it for the list of processes. But if we are local, we
3770 // can let the Host do it.
3771 // if (m_local_debugserver)
3772 // {
3773 // return Host::ListProcessesMatchingName (name, matches, pids);
3774 // }
3775 // else
3776 // {
3777 // // FIXME: Implement talking to the remote debugserver.
3778 // return 0;
3779 // }
3780 //
3781 //}
3782 //
3783 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3784  void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3785  lldb::user_id_t break_loc_id) {
3786  // I don't think I have to do anything here, just make sure I notice the new
3787  // thread when it starts to
3788  // run so I can stop it if that's what I want to do.
3790  LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3791  return false;
3792 }
3793 
3794 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3796  LLDB_LOG(log, "Check if need to update ignored signals");
3797 
3798  // QPassSignals package is not supported by the server, there is no way we
3799  // can ignore any signals on server side.
3800  if (!m_gdb_comm.GetQPassSignalsSupported())
3801  return Status();
3802 
3803  // No signals, nothing to send.
3804  if (m_unix_signals_sp == nullptr)
3805  return Status();
3806 
3807  // Signals' version hasn't changed, no need to send anything.
3808  uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3809  if (new_signals_version == m_last_signals_version) {
3810  LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3811  m_last_signals_version);
3812  return Status();
3813  }
3814 
3815  auto signals_to_ignore =
3816  m_unix_signals_sp->GetFilteredSignals(false, false, false);
3817  Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3818 
3819  LLDB_LOG(log,
3820  "Signals' version changed. old version={0}, new version={1}, "
3821  "signals ignored={2}, update result={3}",
3822  m_last_signals_version, new_signals_version,
3823  signals_to_ignore.size(), error);
3824 
3825  if (error.Success())
3826  m_last_signals_version = new_signals_version;
3827 
3828  return error;
3829 }
3830 
3831 bool ProcessGDBRemote::StartNoticingNewThreads() {
3833  if (m_thread_create_bp_sp) {
3834  if (log && log->GetVerbose())
3835  LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3836  m_thread_create_bp_sp->SetEnabled(true);
3837  } else {
3838  PlatformSP platform_sp(GetTarget().GetPlatform());
3839  if (platform_sp) {
3840  m_thread_create_bp_sp =
3841  platform_sp->SetThreadCreationBreakpoint(GetTarget());
3842  if (m_thread_create_bp_sp) {
3843  if (log && log->GetVerbose())
3844  LLDB_LOGF(
3845  log, "Successfully created new thread notification breakpoint %i",
3846  m_thread_create_bp_sp->GetID());
3847  m_thread_create_bp_sp->SetCallback(
3848  ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3849  } else {
3850  LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3851  }
3852  }
3853  }
3854  return m_thread_create_bp_sp.get() != nullptr;
3855 }
3856 
3857 bool ProcessGDBRemote::StopNoticingNewThreads() {
3859  if (log && log->GetVerbose())
3860  LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3861 
3862  if (m_thread_create_bp_sp)
3863  m_thread_create_bp_sp->SetEnabled(false);
3864 
3865  return true;
3866 }
3867 
3868 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3869  if (m_dyld_up.get() == nullptr)
3870  m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3871  return m_dyld_up.get();
3872 }
3873 
3874 Status ProcessGDBRemote::SendEventData(const char *data) {
3875  int return_value;
3876  bool was_supported;
3877 
3878  Status error;
3879 
3880  return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3881  if (return_value != 0) {
3882  if (!was_supported)
3883  error.SetErrorString("Sending events is not supported for this process.");
3884  else
3885  error.SetErrorStringWithFormat("Error sending event data: %d.",
3886  return_value);
3887  }
3888  return error;
3889 }
3890 
3891 DataExtractor ProcessGDBRemote::GetAuxvData() {
3892  DataBufferSP buf;
3893  if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3894  llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3895  if (response)
3896  buf = std::make_shared<DataBufferHeap>(response->c_str(),
3897  response->length());
3898  else
3900  ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS),
3901  response.takeError(), "{0}");
3902  }
3903  return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3904 }
3905 
3907 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3908  StructuredData::ObjectSP object_sp;
3909 
3910  if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3912  SystemRuntime *runtime = GetSystemRuntime();
3913  if (runtime) {
3914  runtime->AddThreadExtendedInfoPacketHints(args_dict);
3915  }
3916  args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3917 
3918  StreamString packet;
3919  packet << "jThreadExtendedInfo:";
3920  args_dict->Dump(packet, false);
3921 
3922  // FIXME the final character of a JSON dictionary, '}', is the escape
3923  // character in gdb-remote binary mode. lldb currently doesn't escape
3924  // these characters in its packet output -- so we add the quoted version of
3925  // the } character here manually in case we talk to a debugserver which un-
3926  // escapes the characters at packet read time.
3927  packet << (char)(0x7d ^ 0x20);
3928 
3929  StringExtractorGDBRemote response;
3930  response.SetResponseValidatorToJSON();
3931  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3932  GDBRemoteCommunication::PacketResult::Success) {
3934  response.GetResponseType();
3935  if (response_type == StringExtractorGDBRemote::eResponse) {
3936  if (!response.Empty()) {
3937  object_sp =
3939  }
3940  }
3941  }
3942  }
3943  return object_sp;
3944 }
3945 
3946 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3947  lldb::addr_t image_list_address, lldb::addr_t image_count) {
3948 
3950  args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3951  image_list_address);
3952  args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3953 
3954  return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3955 }
3956 
3957 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3959 
3960  args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3961 
3962  return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3963 }
3964 
3965 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3966  const std::vector<lldb::addr_t> &load_addresses) {
3969 
3970  for (auto addr : load_addresses) {
3972  addresses->AddItem(addr_sp);
3973  }
3974 
3975  args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3976 
3977  return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3978 }
3979 
3981 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3982  StructuredData::ObjectSP args_dict) {
3983  StructuredData::ObjectSP object_sp;
3984 
3985  if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3986  // Scope for the scoped timeout object
3987  GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3988  std::chrono::seconds(10));
3989 
3990  StreamString packet;
3991  packet << "jGetLoadedDynamicLibrariesInfos:";
3992  args_dict->Dump(packet, false);
3993 
3994  // FIXME the final character of a JSON dictionary, '}', is the escape
3995  // character in gdb-remote binary mode. lldb currently doesn't escape
3996  // these characters in its packet output -- so we add the quoted version of
3997  // the } character here manually in case we talk to a debugserver which un-
3998  // escapes the characters at packet read time.
3999  packet << (char)(0x7d ^ 0x20);
4000 
4001  StringExtractorGDBRemote response;
4002  response.SetResponseValidatorToJSON();
4003  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4004  GDBRemoteCommunication::PacketResult::Success) {
4006  response.GetResponseType();
4007  if (response_type == StringExtractorGDBRemote::eResponse) {
4008  if (!response.Empty()) {
4009  object_sp =
4011  }
4012  }
4013  }
4014  }
4015  return object_sp;
4016 }
4017 
4018 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4019  StructuredData::ObjectSP object_sp;
4021 
4022  if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4023  StreamString packet;
4024  packet << "jGetSharedCacheInfo:";
4025  args_dict->Dump(packet, false);
4026 
4027  // FIXME the final character of a JSON dictionary, '}', is the escape
4028  // character in gdb-remote binary mode. lldb currently doesn't escape
4029  // these characters in its packet output -- so we add the quoted version of
4030  // the } character here manually in case we talk to a debugserver which un-
4031  // escapes the characters at packet read time.
4032  packet << (char)(0x7d ^ 0x20);
4033 
4034  StringExtractorGDBRemote response;
4035  response.SetResponseValidatorToJSON();
4036  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4037  GDBRemoteCommunication::PacketResult::Success) {
4039  response.GetResponseType();
4040  if (response_type == StringExtractorGDBRemote::eResponse) {
4041  if (!response.Empty()) {
4042  object_sp =
4044  }
4045  }
4046  }
4047  }
4048  return object_sp;
4049 }
4050 
4051 Status ProcessGDBRemote::ConfigureStructuredData(
4052  ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4053  return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4054 }
4055 
4056 // Establish the largest memory read/write payloads we should use. If the
4057 // remote stub has a max packet size, stay under that size.
4058 //
4059 // If the remote stub's max packet size is crazy large, use a reasonable
4060 // largeish default.
4061 //
4062 // If the remote stub doesn't advertise a max packet size, use a conservative
4063 // default.
4064 
4065 void ProcessGDBRemote::GetMaxMemorySize() {
4066  const uint64_t reasonable_largeish_default = 128 * 1024;
4067  const uint64_t conservative_default = 512;
4068 
4069  if (m_max_memory_size == 0) {
4070  uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4071  if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4072  // Save the stub's claimed maximum packet size
4073  m_remote_stub_max_memory_size = stub_max_size;
4074 
4075  // Even if the stub says it can support ginormous packets, don't exceed
4076  // our reasonable largeish default packet size.
4077  if (stub_max_size > reasonable_largeish_default) {
4078  stub_max_size = reasonable_largeish_default;
4079  }
4080 
4081  // Memory packet have other overheads too like Maddr,size:#NN Instead of
4082  // calculating the bytes taken by size and addr every time, we take a
4083  // maximum guess here.
4084  if (stub_max_size > 70)
4085  stub_max_size -= 32 + 32 + 6;
4086  else {
4087  // In unlikely scenario that max packet size is less then 70, we will
4088  // hope that data being written is small enough to fit.
4089  Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4091  if (log)
4092  log->Warning("Packet size is too small. "
4093  "LLDB may face problems while writing memory");
4094  }
4095 
4096  m_max_memory_size = stub_max_size;
4097  } else {
4098  m_max_memory_size = conservative_default;
4099  }
4100  }
4101 }
4102 
4103 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4104  uint64_t user_specified_max) {
4105  if (user_specified_max != 0) {
4106  GetMaxMemorySize();
4107 
4108  if (m_remote_stub_max_memory_size != 0) {
4109  if (m_remote_stub_max_memory_size < user_specified_max) {
4110  m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4111  // packet size too
4112  // big, go as big
4113  // as the remote stub says we can go.
4114  } else {
4115  m_max_memory_size = user_specified_max; // user's packet size is good
4116  }
4117  } else {
4118  m_max_memory_size =
4119  user_specified_max; // user's packet size is probably fine
4120  }
4121  }
4122 }
4123 
4124 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4125  const ArchSpec &arch,
4126  ModuleSpec &module_spec) {
4128 
4129  const ModuleCacheKey key(module_file_spec.GetPath(),
4130  arch.GetTriple().getTriple());
4131  auto cached = m_cached_module_specs.find(key);
4132  if (cached != m_cached_module_specs.end()) {
4133  module_spec = cached->second;
4134  return bool(module_spec);
4135  }
4136 
4137  if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4138  LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4139  __FUNCTION__, module_file_spec.GetPath().c_str(),
4140  arch.GetTriple().getTriple().c_str());
4141  return false;
4142  }
4143 
4144  if (log) {
4145  StreamString stream;
4146  module_spec.Dump(stream);
4147  LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4148  __FUNCTION__, module_file_spec.GetPath().c_str(),
4149  arch.GetTriple().getTriple().c_str(), stream.GetData());
4150  }
4151 
4152  m_cached_module_specs[key] = module_spec;
4153  return true;
4154 }
4155 
4156 void ProcessGDBRemote::PrefetchModuleSpecs(
4157  llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4158  auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4159  if (module_specs) {
4160  for (const FileSpec &spec : module_file_specs)
4161  m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4162  triple.getTriple())] = ModuleSpec();
4163  for (const ModuleSpec &spec : *module_specs)
4164  m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4165  triple.getTriple())] = spec;
4166  }
4167 }
4168 
4169 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4170  return m_gdb_comm.GetOSVersion();
4171 }
4172 
4173 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4174  return m_gdb_comm.GetMacCatalystVersion();
4175 }
4176 
4177 namespace {
4178 
4179 typedef std::vector<std::string> stringVec;
4180 
4181 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4182 struct RegisterSetInfo {
4183  ConstString name;
4184 };
4185 
4186 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4187 
4188 struct GdbServerTargetInfo {
4189  std::string arch;
4190  std::string osabi;
4191  stringVec includes;
4192  RegisterSetMap reg_set_map;
4193 };
4194 
4195 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4196  std::vector<DynamicRegisterInfo::Register> &registers) {
4197  if (!feature_node)
4198  return false;
4199 
4200  feature_node.ForEachChildElementWithName(
4201  "reg", [&target_info, &registers](const XMLNode &reg_node) -> bool {
4202  std::string gdb_group;
4203  std::string gdb_type;
4205  bool encoding_set = false;
4206  bool format_set = false;
4207 
4208  // FIXME: we're silently ignoring invalid data here
4209  reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4210  &encoding_set, &format_set, &reg_info](
4211  const llvm::StringRef &name,
4212  const llvm::StringRef &value) -> bool {
4213  if (name == "name") {
4214  reg_info.name.SetString(value);
4215  } else if (name == "bitsize") {
4216  if (llvm::to_integer(value, reg_info.byte_size))
4217  reg_info.byte_size =
4218  llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4219  } else if (name == "type") {
4220  gdb_type = value.str();
4221  } else if (name == "group") {
4222  gdb_group = value.str();
4223  } else if (name == "regnum") {
4224  llvm::to_integer(value, reg_info.regnum_remote);
4225  } else if (name == "offset") {
4226  llvm::to_integer(value, reg_info.byte_offset);
4227  } else if (name == "altname") {
4228  reg_info.alt_name.SetString(value);
4229  } else if (name == "encoding") {
4230  encoding_set = true;
4231  reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4232  } else if (name == "format") {
4233  format_set = true;
4234  if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4235  nullptr)
4236  .Success())
4237  reg_info.format =
4238  llvm::StringSwitch<lldb::Format>(value)
4239  .Case("vector-sint8", eFormatVectorOfSInt8)
4240  .Case("vector-uint8", eFormatVectorOfUInt8)
4241  .Case("vector-sint16", eFormatVectorOfSInt16)
4242  .Case("vector-uint16", eFormatVectorOfUInt16)
4243  .Case("vector-sint32", eFormatVectorOfSInt32)
4244  .Case("vector-uint32", eFormatVectorOfUInt32)
4245  .Case("vector-float32", eFormatVectorOfFloat32)
4246  .Case("vector-uint64", eFormatVectorOfUInt64)
4247  .Case("vector-uint128", eFormatVectorOfUInt128)
4248  .Default(eFormatInvalid);
4249  } else if (name == "group_id") {
4250  uint32_t set_id = UINT32_MAX;
4251  llvm::to_integer(value, set_id);
4252  RegisterSetMap::const_iterator pos =
4253  target_info.reg_set_map.find(set_id);
4254  if (pos != target_info.reg_set_map.end())
4255  reg_info.set_name = pos->second.name;
4256  } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4257  llvm::to_integer(value, reg_info.regnum_ehframe);
4258  } else if (name == "dwarf_regnum") {
4259  llvm::to_integer(value, reg_info.regnum_dwarf);
4260  } else if (name == "generic") {
4262  } else if (name == "value_regnums") {
4264  0);
4265  } else if (name == "invalidate_regnums") {
4267  value, reg_info.invalidate_regs, 0);
4268  } else {
4270  GDBR_LOG_PROCESS));
4271  LLDB_LOGF(log,
4272  "ProcessGDBRemote::%s unhandled reg attribute %s = %s",
4273  __FUNCTION__, name.data(), value.data());
4274  }
4275  return true; // Keep iterating through all attributes
4276  });
4277 
4278  if (!gdb_type.empty() && !(encoding_set || format_set)) {
4279  if (llvm::StringRef(gdb_type).startswith("int")) {
4280  reg_info.format = eFormatHex;
4281  reg_info.encoding = eEncodingUint;
4282  } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4283  reg_info.format = eFormatAddressInfo;
4284  reg_info.encoding = eEncodingUint;
4285  } else if (gdb_type == "float") {
4286  reg_info.format = eFormatFloat;
4287  reg_info.encoding = eEncodingIEEE754;
4288  } else if (gdb_type == "aarch64v" ||
4289  llvm::StringRef(gdb_type).startswith("vec") ||
4290  gdb_type == "i387_ext" || gdb_type == "uint128") {
4291  // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4292  // them as vector (similarly to xmm/ymm)
4293  reg_info.format = eFormatVectorOfUInt8;
4294  reg_info.encoding = eEncodingVector;
4295  }
4296  }
4297 
4298  // Only update the register set name if we didn't get a "reg_set"
4299  // attribute. "set_name" will be empty if we didn't have a "reg_set"
4300  // attribute.
4301  if (!reg_info.set_name) {
4302  if (!gdb_group.empty()) {
4303  reg_info.set_name.SetCString(gdb_group.c_str());
4304  } else {
4305  // If no register group name provided anywhere,
4306  // we'll create a 'general' register set
4307  reg_info.set_name.SetCString("general");
4308  }
4309  }
4310 
4311  if (reg_info.byte_size == 0) {
4312  Log *log(
4314  LLDB_LOGF(log,
4315  "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4316  __FUNCTION__, reg_info.name.AsCString());
4317  } else
4318  registers.push_back(reg_info);
4319 
4320  return true; // Keep iterating through all "reg" elements
4321  });
4322  return true;
4323 }
4324 
4325 } // namespace
4326 
4327 // This method fetches a register description feature xml file from
4328 // the remote stub and adds registers/register groupsets/architecture
4329 // information to the current process. It will call itself recursively
4330 // for nested register definition files. It returns true if it was able
4331 // to fetch and parse an xml file.
4332 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4333  ArchSpec &arch_to_use, std::string xml_filename,
4334  std::vector<DynamicRegisterInfo::Register> &registers) {
4335  // request the target xml file
4336  llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4337  if (errorToBool(raw.takeError()))
4338  return false;
4339 
4340  XMLDocument xml_document;
4341 
4342  if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4343  xml_filename.c_str())) {
4344  GdbServerTargetInfo target_info;
4345  std::vector<XMLNode> feature_nodes;
4346 
4347  // The top level feature XML file will start with a <target> tag.
4348  XMLNode target_node = xml_document.GetRootElement("target");
4349  if (target_node) {
4350  target_node.ForEachChildElement([&target_info, &feature_nodes](
4351  const XMLNode &node) -> bool {
4352  llvm::StringRef name = node.GetName();
4353  if (name == "architecture") {
4354  node.GetElementText(target_info.arch);
4355  } else if (name == "osabi") {
4356  node.GetElementText(target_info.osabi);
4357  } else if (name == "xi:include" || name == "include") {
4358  std::string href = node.GetAttributeValue("href");
4359  if (!href.empty())
4360  target_info.includes.push_back(href);
4361  } else if (name == "feature") {
4362  feature_nodes.push_back(node);
4363  } else if (name == "groups") {
4365  "group", [&target_info](const XMLNode &node) -> bool {
4366  uint32_t set_id = UINT32_MAX;
4367  RegisterSetInfo set_info;
4368 
4369  node.ForEachAttribute(
4370  [&set_id, &set_info](const llvm::StringRef &name,
4371  const llvm::StringRef &value) -> bool {
4372  // FIXME: we're silently ignoring invalid data here
4373  if (name == "id")
4374  llvm::to_integer(value, set_id);
4375  if (name == "name")
4376  set_info.name = ConstString(value);
4377  return true; // Keep iterating through all attributes
4378  });
4379 
4380  if (set_id != UINT32_MAX)
4381  target_info.reg_set_map[set_id] = set_info;
4382  return true; // Keep iterating through all "group" elements
4383  });
4384  }
4385  return true; // Keep iterating through all children of the target_node
4386  });
4387  } else {
4388  // In an included XML feature file, we're already "inside" the <target>
4389  // tag of the initial XML file; this included file will likely only have
4390  // a <feature> tag. Need to check for any more included files in this
4391  // <feature> element.
4392  XMLNode feature_node = xml_document.GetRootElement("feature");
4393  if (feature_node) {
4394  feature_nodes.push_back(feature_node);
4395  feature_node.ForEachChildElement([&target_info](
4396  const XMLNode &node) -> bool {
4397  llvm::StringRef name = node.GetName();
4398  if (name == "xi:include" || name == "include") {
4399  std::string href = node.GetAttributeValue("href");
4400  if (!href.empty())
4401  target_info.includes.push_back(href);
4402  }
4403  return true;
4404  });
4405  }
4406  }
4407 
4408  // gdbserver does not implement the LLDB packets used to determine host
4409  // or process architecture. If that is the case, attempt to use
4410  // the <architecture/> field from target.xml, e.g.:
4411  //
4412  // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4413  // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4414  // arm board)
4415  if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4416  // We don't have any information about vendor or OS.
4417  arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4418  .Case("i386:x86-64", "x86_64")
4419  .Default(target_info.arch) +
4420  "--");
4421 
4422  if (arch_to_use.IsValid())
4423  GetTarget().MergeArchitecture(arch_to_use);
4424  }
4425 
4426  if (arch_to_use.IsValid()) {
4427  for (auto &feature_node : feature_nodes) {
4428  ParseRegisters(feature_node, target_info,
4429  registers);
4430  }
4431 
4432  for (const auto &include : target_info.includes) {
4433  GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4434  registers);
4435  }
4436  }
4437  } else {
4438  return false;
4439  }
4440  return true;
4441 }
4442 
4443 void ProcessGDBRemote::AddRemoteRegisters(
4444  std::vector<DynamicRegisterInfo::Register> &registers,
4445  const ArchSpec &arch_to_use) {
4446  std::map<uint32_t, uint32_t> remote_to_local_map;
4447  uint32_t remote_regnum = 0;
4448  for (auto it : llvm::enumerate(registers)) {
4449  DynamicRegisterInfo::Register &remote_reg_info = it.value();
4450 
4451  // Assign successive remote regnums if missing.
4452  if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4453  remote_reg_info.regnum_remote = remote_regnum;
4454 
4455  // Create a mapping from remote to local regnos.
4456  remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4457 
4458  remote_regnum = remote_reg_info.regnum_remote + 1;
4459  }
4460 
4461  for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4462  auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4463  auto lldb_regit = remote_to_local_map.find(process_regnum);
4464  return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4466  };
4467 
4468  llvm::transform(remote_reg_info.value_regs,
4469  remote_reg_info.value_regs.begin(), proc_to_lldb);
4470  llvm::transform(remote_reg_info.invalidate_regs,
4471  remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4472  }
4473 
4474  // Don't use Process::GetABI, this code gets called from DidAttach, and
4475  // in that context we haven't set the Target's architecture yet, so the
4476  // ABI is also potentially incorrect.
4477  if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4478  abi_sp->AugmentRegisterInfo(registers);
4479 
4480  m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4481 }
4482 
4483 // query the target of gdb-remote for extended target information returns
4484 // true on success (got register definitions), false on failure (did not).
4485 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4486  // Make sure LLDB has an XML parser it can use first
4487  if (!XMLDocument::XMLEnabled())
4488  return false;
4489 
4490  // check that we have extended feature read support
4491  if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4492  return false;
4493 
4494  std::vector<DynamicRegisterInfo::Register> registers;
4495  if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4496  registers))
4497  AddRemoteRegisters(registers, arch_to_use);
4498 
4499  return m_register_info_sp->GetNumRegisters() > 0;
4500 }
4501 
4502 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4503  // Make sure LLDB has an XML parser it can use first
4504  if (!XMLDocument::XMLEnabled())
4505  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4506  "XML parsing not available");
4507 
4509  LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4510 
4512  GDBRemoteCommunicationClient &comm = m_gdb_comm;
4513  bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4514 
4515  // check that we have extended feature read support
4516  if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4517  // request the loaded library list
4518  llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4519  if (!raw)
4520  return raw.takeError();
4521 
4522  // parse the xml file in memory
4523  LLDB_LOGF(log, "parsing: %s", raw->c_str());
4524  XMLDocument doc;
4525 
4526  if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4527  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4528  "Error reading noname.xml");
4529 
4530  XMLNode root_element = doc.GetRootElement("library-list-svr4");
4531  if (!root_element)
4532  return llvm::createStringError(
4533  llvm::inconvertibleErrorCode(),
4534  "Error finding library-list-svr4 xml element");
4535 
4536  // main link map structure
4537  std::string main_lm = root_element.GetAttributeValue("main-lm");
4538  // FIXME: we're silently ignoring invalid data here
4539  if (!main_lm.empty())
4540  llvm::to_integer(main_lm, list.m_link_map);
4541 
4542  root_element.ForEachChildElementWithName(
4543  "library", [log, &list](const XMLNode &library) -> bool {
4545 
4546  // FIXME: we're silently ignoring invalid data here
4547  library.ForEachAttribute(
4548  [&module](const llvm::StringRef &name,
4549  const llvm::StringRef &value) -> bool {
4550  uint64_t uint_value = LLDB_INVALID_ADDRESS;
4551  if (name == "name")
4552  module.set_name(value.str());
4553  else if (name == "lm") {
4554  // the address of the link_map struct.
4555  llvm::to_integer(value, uint_value);
4556  module.set_link_map(uint_value);
4557  } else if (name == "l_addr") {
4558  // the displacement as read from the field 'l_addr' of the
4559  // link_map struct.
4560  llvm::to_integer(value, uint_value);
4561  module.set_base(uint_value);
4562  // base address is always a displacement, not an absolute
4563  // value.
4564  module.set_base_is_offset(true);
4565  } else if (name == "l_ld") {
4566  // the memory address of the libraries PT_DYNAMIC section.
4567  llvm::to_integer(value, uint_value);
4568  module.set_dynamic(uint_value);
4569  }
4570 
4571  return true; // Keep iterating over all properties of "library"
4572  });
4573 
4574  if (log) {
4575  std::string name;
4576  lldb::addr_t lm = 0, base = 0, ld = 0;
4577  bool base_is_offset;
4578 
4579  module.get_name(name);
4580  module.get_link_map(lm);
4581  module.get_base(base);
4582  module.get_base_is_offset(base_is_offset);
4583  module.get_dynamic(ld);
4584 
4585  LLDB_LOGF(log,
4586  "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4587  "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4588  lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4589  name.c_str());
4590  }
4591 
4592  list.add(module);
4593  return true; // Keep iterating over all "library" elements in the root
4594  // node
4595  });
4596 
4597  if (log)
4598  LLDB_LOGF(log, "found %" PRId32 " modules in total",
4599  (int)list.m_list.size());
4600  return list;
4601  } else if (comm.GetQXferLibrariesReadSupported()) {
4602  // request the loaded library list
4603  llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4604 
4605  if (!raw)
4606  return raw.takeError();
4607 
4608  LLDB_LOGF(log, "parsing: %s", raw->c_str());
4609  XMLDocument doc;
4610 
4611  if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4612  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4613  "Error reading noname.xml");
4614 
4615  XMLNode root_element = doc.GetRootElement("library-list");
4616  if (!root_element)
4617  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4618  "Error finding library-list xml element");
4619 
4620  // FIXME: we're silently ignoring invalid data here
4621  root_element.ForEachChildElementWithName(
4622  "library", [log, &list](const XMLNode &library) -> bool {
4624 
4625  std::string name = library.GetAttributeValue("name");
4626  module.set_name(name);
4627 
4628  // The base address of a given library will be the address of its
4629  // first section. Most remotes send only one section for Windows
4630  // targets for example.
4631  const XMLNode &section =
4632  library.FindFirstChildElementWithName("section");
4633  std::string address = section.GetAttributeValue("address");
4634  uint64_t address_value = LLDB_INVALID_ADDRESS;
4635  llvm::to_integer(address, address_value);
4636  module.set_base(address_value);
4637  // These addresses are absolute values.
4638  module.set_base_is_offset(false);
4639 
4640  if (log) {
4641  std::string name;
4642  lldb::addr_t base = 0;
4643  bool base_is_offset;
4644  module.get_name(name);
4645  module.get_base(base);
4646  module.get_base_is_offset(base_is_offset);
4647 
4648  LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4649  (base_is_offset ? "offset" : "absolute"), name.c_str());
4650  }
4651 
4652  list.add(module);
4653  return true; // Keep iterating over all "library" elements in the root
4654  // node
4655  });
4656 
4657  if (log)
4658  LLDB_LOGF(log, "found %" PRId32 " modules in total",
4659  (int)list.m_list.size());
4660  return list;
4661  } else {
4662  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4663  "Remote libraries not supported");
4664  }
4665 }
4666 
4667 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4668  lldb::addr_t link_map,
4669  lldb::addr_t base_addr,
4670  bool value_is_offset) {
4671  DynamicLoader *loader = GetDynamicLoader();
4672  if (!loader)
4673  return nullptr;
4674 
4675  return loader->LoadModuleAtAddress(file, link_map, base_addr,
4676  value_is_offset);
4677 }
4678 
4679 llvm::Error ProcessGDBRemote::LoadModules() {
4681 
4682  // request a list of loaded libraries from GDBServer
4683  llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4684  if (!module_list)
4685  return module_list.takeError();
4686 
4687  // get a list of all the modules
4688  ModuleList new_modules;
4689 
4690  for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4691  std::string mod_name;
4692  lldb::addr_t mod_base;
4693  lldb::addr_t link_map;
4694  bool mod_base_is_offset;
4695 
4696  bool valid = true;
4697  valid &= modInfo.get_name(mod_name);
4698  valid &= modInfo.get_base(mod_base);
4699  valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4700  if (!valid)
4701  continue;
4702 
4703  if (!modInfo.get_link_map(link_map))
4704  link_map = LLDB_INVALID_ADDRESS;
4705 
4706  FileSpec file(mod_name);
4707  FileSystem::Instance().Resolve(file);
4708  lldb::ModuleSP module_sp =
4709  LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4710 
4711  if (module_sp.get())
4712  new_modules.Append(module_sp);
4713  }
4714 
4715  if (new_modules.GetSize() > 0) {
4716  ModuleList removed_modules;
4717  Target &target = GetTarget();
4718  ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4719 
4720  for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4721  const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4722 
4723  bool found = false;
4724  for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4725  if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4726  found = true;
4727  }
4728 
4729  // The main executable will never be included in libraries-svr4, don't
4730  // remove it
4731  if (!found &&
4732  loaded_module.get() != target.GetExecutableModulePointer()) {
4733  removed_modules.Append(loaded_module);
4734  }
4735  }
4736 
4737  loaded_modules.Remove(removed_modules);
4738  m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4739 
4740  new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4741  lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4742  if (!obj)
4743  return true;
4744 
4745  if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4746  return true;
4747 
4748  lldb::ModuleSP module_copy_sp = module_sp;
4749  target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4750  return false;
4751  });
4752 
4753  loaded_modules.AppendIfNeeded(new_modules);
4754  m_process->GetTarget().ModulesDidLoad(new_modules);
4755  }
4756 
4757  return llvm::ErrorSuccess();
4758 }
4759 
4760 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4761  bool &is_loaded,
4762  lldb::addr_t &load_addr) {
4763  is_loaded = false;
4764  load_addr = LLDB_INVALID_ADDRESS;
4765 
4766  std::string file_path = file.GetPath(false);
4767  if (file_path.empty())
4768  return Status("Empty file name specified");
4769 
4770  StreamString packet;
4771  packet.PutCString("qFileLoadAddress:");
4772  packet.PutStringAsRawHex8(file_path);
4773 
4774  StringExtractorGDBRemote response;
4775  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
4776  GDBRemoteCommunication::PacketResult::Success)
4777  return Status("Sending qFileLoadAddress packet failed");
4778 
4779  if (response.IsErrorResponse()) {
4780  if (response.GetError() == 1) {
4781  // The file is not loaded into the inferior
4782  is_loaded = false;
4783  load_addr = LLDB_INVALID_ADDRESS;
4784  return Status();
4785  }
4786 
4787  return Status(
4788  "Fetching file load address from remote server returned an error");
4789  }
4790 
4791  if (response.IsNormalResponse()) {
4792  is_loaded = true;
4793  load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4794  return Status();
4795  }
4796 
4797  return Status(
4798  "Unknown error happened during sending the load address packet");
4799 }
4800 
4801 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4802  // We must call the lldb_private::Process::ModulesDidLoad () first before we
4803  // do anything
4804  Process::ModulesDidLoad(module_list);
4805 
4806  // After loading shared libraries, we can ask our remote GDB server if it
4807  // needs any symbols.
4808  m_gdb_comm.ServeSymbolLookups(this);
4809 }
4810 
4811 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4812  AppendSTDOUT(out.data(), out.size());
4813 }
4814 
4815 static const char *end_delimiter = "--end--;";
4816 static const int end_delimiter_len = 8;
4817 
4818 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4819  std::string input = data.str(); // '1' to move beyond 'A'
4820  if (m_partial_profile_data.length() > 0) {
4821  m_partial_profile_data.append(input);
4822  input = m_partial_profile_data;
4823  m_partial_profile_data.clear();
4824  }
4825 
4826  size_t found, pos = 0, len = input.length();
4827  while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4828  StringExtractorGDBRemote profileDataExtractor(
4829  input.substr(pos, found).c_str());
4830  std::string profile_data =
4831  HarmonizeThreadIdsForProfileData(profileDataExtractor);
4832  BroadcastAsyncProfileData(profile_data);
4833 
4834  pos = found + end_delimiter_len;
4835  }
4836 
4837  if (pos < len) {
4838  // Last incomplete chunk.
4839  m_partial_profile_data = input.substr(pos);
4840  }
4841 }
4842 
4843 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4844  StringExtractorGDBRemote &profileDataExtractor) {
4845  std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4846  std::string output;
4847  llvm::raw_string_ostream output_stream(output);
4848  llvm::StringRef name, value;
4849 
4850  // Going to assuming thread_used_usec comes first, else bail out.
4851  while (profileDataExtractor.GetNameColonValue(name, value)) {
4852  if (name.compare("thread_used_id") == 0) {
4853  StringExtractor threadIDHexExtractor(value);
4854  uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4855 
4856  bool has_used_usec = false;
4857  uint32_t curr_used_usec = 0;
4858  llvm::StringRef usec_name, usec_value;
4859  uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4860  if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4861  if (usec_name.equals("thread_used_usec")) {
4862  has_used_usec = true;
4863  usec_value.getAsInteger(0, curr_used_usec);
4864  } else {
4865  // We didn't find what we want, it is probably an older version. Bail
4866  // out.
4867  profileDataExtractor.SetFilePos(input_file_pos);
4868  }
4869  }
4870 
4871  if (has_used_usec) {
4872  uint32_t prev_used_usec = 0;
4873  std::map<uint64_t, uint32_t>::iterator iterator =
4874  m_thread_id_to_used_usec_map.find(thread_id);
4875  if (iterator != m_thread_id_to_used_usec_map.end()) {
4876  prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4877  }
4878 
4879  uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4880  // A good first time record is one that runs for at least 0.25 sec
4881  bool good_first_time =
4882  (prev_used_usec == 0) && (real_used_usec > 250000);
4883  bool good_subsequent_time =
4884  (prev_used_usec > 0) &&
4885  ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4886 
4887  if (good_first_time || good_subsequent_time) {
4888  // We try to avoid doing too many index id reservation, resulting in
4889  // fast increase of index ids.
4890 
4891  output_stream << name << ":";
4892  int32_t index_id = AssignIndexIDToThread(thread_id);
4893  output_stream << index_id << ";";
4894 
4895  output_stream << usec_name << ":" << usec_value << ";";
4896  } else {
4897  // Skip past 'thread_used_name'.
4898  llvm::StringRef local_name, local_value;
4899  profileDataExtractor.GetNameColonValue(local_name, local_value);
4900  }
4901 
4902  // Store current time as previous time so that they can be compared
4903  // later.
4904  new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4905  } else {
4906  // Bail out and use old string.
4907  output_stream << name << ":" << value << ";";
4908  }
4909  } else {
4910  output_stream << name << ":" << value << ";";
4911  }
4912  }
4913  output_stream << end_delimiter;
4914  m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4915 
4916  return output_stream.str();
4917 }
4918 
4919 void ProcessGDBRemote::HandleStopReply() {
4920  if (GetStopID() != 0)
4921  return;
4922 
4923  if (GetID() == LLDB_INVALID_PROCESS_ID) {
4924  lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4925  if (pid != LLDB_INVALID_PROCESS_ID)
4926  SetID(pid);
4927  }
4928  BuildDynamicRegisterInfo(true);
4929 }
4930 
4931 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4932  if (!m_gdb_comm.GetSaveCoreSupported())
4933  return false;
4934 
4935  StreamString packet;
4936  packet.PutCString("qSaveCore;path-hint:");
4937  packet.PutStringAsRawHex8(outfile);
4938 
4939  StringExtractorGDBRemote response;
4940  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4941  GDBRemoteCommunication::PacketResult::Success) {
4942  // TODO: grab error message from the packet? StringExtractor seems to
4943  // be missing a method for that
4944  if (response.IsErrorResponse())
4945  return llvm::createStringError(
4946  llvm::inconvertibleErrorCode(),
4947  llvm::formatv("qSaveCore returned an error"));
4948 
4949  std::string path;
4950 
4951  // process the response
4952  for (auto x : llvm::split(response.GetStringRef(), ';')) {
4953  if (x.consume_front("core-path:"))
4955  }
4956 
4957  // verify that we've gotten what we need
4958  if (path.empty())
4959  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4960  "qSaveCore returned no core path");
4961 
4962  // now transfer the core file
4963  FileSpec remote_core{llvm::StringRef(path)};
4964  Platform &platform = *GetTarget().GetPlatform();
4965  Status error = platform.GetFile(remote_core, FileSpec(outfile));
4966 
4967  if (platform.IsRemote()) {
4968  // NB: we unlink the file on error too
4969  platform.Unlink(remote_core);
4970  if (error.Fail())
4971  return error.ToError();
4972  }
4973 
4974  return true;
4975  }
4976 
4977  return llvm::createStringError(llvm::inconvertibleErrorCode(),
4978  "Unable to send qSaveCore");
4979 }
4980 
4981 static const char *const s_async_json_packet_prefix = "JSON-async:";
4982 
4984 ParseStructuredDataPacket(llvm::StringRef packet) {
4986 
4987  if (!packet.consume_front(s_async_json_packet_prefix)) {
4988  if (log) {
4989  LLDB_LOGF(
4990  log,
4991  "GDBRemoteCommunicationClientBase::%s() received $J packet "
4992  "but was not a StructuredData packet: packet starts with "
4993  "%s",
4994  __FUNCTION__,
4995  packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4996  }
4997  return StructuredData::ObjectSP();
4998  }
4999 
5000  // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5001  StructuredData::ObjectSP json_sp =
5003  if (log) {
5004  if (json_sp) {
5005  StreamString json_str;
5006  json_sp->Dump(json_str, true);
5007  json_str.Flush();
5008  LLDB_LOGF(log,
5009  "ProcessGDBRemote::%s() "
5010  "received Async StructuredData packet: %s",
5011  __FUNCTION__, json_str.GetData());
5012  } else {
5013  LLDB_LOGF(log,
5014  "ProcessGDBRemote::%s"
5015  "() received StructuredData packet:"
5016  " parse failure",
5017  __FUNCTION__);
5018  }
5019  }
5020  return json_sp;
5021 }
5022 
5023 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5024  auto structured_data_sp = ParseStructuredDataPacket(data);
5025  if (structured_data_sp)
5026  RouteAsyncStructuredData(structured_data_sp);
5027 }
5028 
5030 public:
5032  : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5033  "Tests packet speeds of various sizes to determine "
5034  "the performance characteristics of the GDB remote "
5035  "connection. ",
5036  nullptr),
5037  m_option_group(),
5038  m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5039  "The number of packets to send of each varying size "
5040  "(default is 1000).",
5041  1000),
5042  m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5043  "The maximum number of bytes to send in a packet. Sizes "
5044  "increase in powers of 2 while the size is less than or "
5045  "equal to this option value. (default 1024).",
5046  1024),
5047  m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5048  "The maximum number of bytes to receive in a packet. Sizes "
5049  "increase in powers of 2 while the size is less than or "
5050  "equal to this option value. (default 1024).",
5051  1024),
5052  m_json(LLDB_OPT_SET_1, false, "json", 'j',
5053  "Print the output as JSON data for easy parsing.", false, true) {
5054  m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5055  m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5056  m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5057  m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5058  m_option_group.Finalize();
5059  }
5060 
5061  ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
5062 
5063  Options *GetOptions() override { return &m_option_group; }
5064 
5065  bool DoExecute(Args &command, CommandReturnObject &result) override {
5066  const size_t argc = command.GetArgumentCount();
5067  if (argc == 0) {
5068  ProcessGDBRemote *process =
5069  (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5070  .GetProcessPtr();
5071  if (process) {
5072  StreamSP output_stream_sp(
5073  m_interpreter.GetDebugger().GetAsyncOutputStream());
5074  result.SetImmediateOutputStream(output_stream_sp);
5075 
5076  const uint32_t num_packets =
5077  (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5078  const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5079  const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5080  const bool json = m_json.GetOptionValue().GetCurrentValue();
5081  const uint64_t k_recv_amount =
5082  4 * 1024 * 1024; // Receive amount in bytes
5083  process->GetGDBRemote().TestPacketSpeed(
5084  num_packets, max_send, max_recv, k_recv_amount, json,
5085  output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5087  return true;
5088  }
5089  } else {
5090  result.AppendErrorWithFormat("'%s' takes no arguments",
5091  m_cmd_name.c_str());
5092  }
5094  return false;
5095  }
5096 
5097 protected:
5103 };
5104 
5106 private:
5107 public:
5109  : CommandObjectParsed(interpreter, "process plugin packet history",
5110  "Dumps the packet history buffer. ", nullptr) {}
5111 
5112  ~CommandObjectProcessGDBRemotePacketHistory() override = default;
5113 
5114  bool DoExecute(Args &command, CommandReturnObject &result) override {
5115  const size_t argc = command.GetArgumentCount();
5116  if (argc == 0) {
5117  ProcessGDBRemote *process =
5118  (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5119  .GetProcessPtr();
5120  if (process) {
5121  process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5123  return true;
5124  }
5125  } else {
5126  result.AppendErrorWithFormat("'%s' takes no arguments",
5127  m_cmd_name.c_str());
5128  }
5130  return false;
5131  }
5132 };
5133 
5135 private:
5136 public:
5139  interpreter, "process plugin packet xfer-size",
5140  "Maximum size that lldb will try to read/write one one chunk.",
5141  nullptr) {}
5142 
5143  ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
5144 
5145  bool DoExecute(Args &command, CommandReturnObject &result) override {
5146  const size_t argc = command.GetArgumentCount();
5147  if (argc == 0) {
5148  result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5149  "amount to be transferred when "
5150  "reading/writing",
5151  m_cmd_name.c_str());
5152  return false;
5153  }
5154 
5155  ProcessGDBRemote *process =
5156  (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5157  if (process) {
5158  const char *packet_size = command.GetArgumentAtIndex(0);
5159  errno = 0;
5160  uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5161  if (errno == 0 && user_specified_max != 0) {
5162  process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5164  return true;
5165  }
5166  }
5168  return false;
5169  }
5170 };
5171 
5173 private:
5174 public:
5176  : CommandObjectParsed(interpreter, "process plugin packet send",
5177  "Send a custom packet through the GDB remote "
5178  "protocol and print the answer. "
5179  "The packet header and footer will automatically "
5180  "be added to the packet prior to sending and "
5181  "stripped from the result.",
5182  nullptr) {}
5183 
5184  ~CommandObjectProcessGDBRemotePacketSend() override = default;
5185 
5186  bool DoExecute(Args &command, CommandReturnObject &result) override {
5187  const size_t argc = command.GetArgumentCount();
5188  if (argc == 0) {
5189  result.AppendErrorWithFormat(
5190  "'%s' takes a one or more packet content arguments",
5191  m_cmd_name.c_str());
5192  return false;
5193  }
5194 
5195  ProcessGDBRemote *process =
5196  (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5197  if (process) {
5198  for (size_t i = 0; i < argc; ++i) {
5199  const char *packet_cstr = command.GetArgumentAtIndex(0);
5200  StringExtractorGDBRemote response;
5202  packet_cstr, response, process->GetInterruptTimeout());
5204  Stream &output_strm = result.GetOutputStream();
5205  output_strm.Printf(" packet: %s\n", packet_cstr);
5206  std::string response_str = std::string(response.GetStringRef());
5207 
5208  if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5209  response_str = process->HarmonizeThreadIdsForProfileData(response);
5210  }
5211 
5212  if (response_str.empty())
5213  output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5214  else
5215  output_strm.Printf("response: %s\n", response.GetStringRef().data());
5216  }
5217  }
5218  return true;
5219  }
5220 };
5221 
5223 private:
5224 public:
5226  : CommandObjectRaw(interpreter, "process plugin packet monitor",
5227  "Send a qRcmd packet through the GDB remote protocol "
5228  "and print the response."
5229  "The argument passed to this command will be hex "
5230  "encoded into a valid 'qRcmd' packet, sent and the "
5231  "response will be printed.") {}
5232 
5233  ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
5234 
5235  bool DoExecute(llvm::StringRef command,
5236  CommandReturnObject &result) override {
5237  if (command.empty()) {
5238  result.AppendErrorWithFormat("'%s' takes a command string argument",
5239  m_cmd_name.c_str());
5240  return false;
5241  }
5242 
5243  ProcessGDBRemote *process =
5244  (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5245  if (process) {
5246  StreamString packet;
5247  packet.PutCString("qRcmd,");
5248  packet.PutBytesAsRawHex8(command.data(), command.size());
5249 
5250  StringExtractorGDBRemote response;
5251  Stream &output_strm = result.GetOutputStream();
5253  packet.GetString(), response, process->GetInterruptTimeout(),
5254  [&output_strm](llvm::StringRef output) { output_strm << output; });
5256  output_strm.Printf(" packet: %s\n", packet.GetData());
5257  const std::string &response_str = std::string(response.GetStringRef());
5258 
5259  if (response_str.empty())
5260  output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5261  else
5262  output_strm.Printf("response: %s\n", response.GetStringRef().data());
5263  }
5264  return true;
5265  }
5266 };
5267 
5269 private:
5270 public:
5272  : CommandObjectMultiword(interpreter, "process plugin packet",
5273  "Commands that deal with GDB remote packets.",
5274  nullptr) {
5275  LoadSubCommand(
5276  "history",
5277  CommandObjectSP(
5278  new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5279  LoadSubCommand(
5280  "send", CommandObjectSP(
5281  new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5282  LoadSubCommand(
5283  "monitor",
5284  CommandObjectSP(
5285  new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5286  LoadSubCommand(
5287  "xfer-size",
5288  CommandObjectSP(
5290  LoadSubCommand("speed-test",
5291  CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5292  interpreter)));
5293  }
5294 
5295  ~CommandObjectProcessGDBRemotePacket() override = default;
5296 };
5297 
5299 public:
5302  interpreter, "process plugin",
5303  "Commands for operating on a ProcessGDBRemote process.",
5304  "process plugin <subcommand> [<subcommand-options>]") {
5305  LoadSubCommand(
5306  "packet",
5307  CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5308  }
5309 
5310  ~CommandObjectMultiwordProcessGDBRemote() override = default;
5311 };
5312 
5313 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5314  if (!m_command_sp)
5315  m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5316  GetTarget().GetDebugger().GetCommandInterpreter());
5317  return m_command_sp.get();
5318 }
5319 
5320 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5321  GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5322  if (bp_site->IsEnabled() &&
5323  (bp_site->GetType() == BreakpointSite::eSoftware ||
5324  bp_site->GetType() == BreakpointSite::eExternal)) {
5325  m_gdb_comm.SendGDBStoppointTypePacket(
5326  eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5327  GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5328  }
5329  });
5330 }
5331 
5332 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5333  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5334  GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5335  if (bp_site->IsEnabled() &&
5336  bp_site->GetType() == BreakpointSite::eHardware) {
5337  m_gdb_comm.SendGDBStoppointTypePacket(
5338  eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5339  GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5340  }
5341  });
5342  }
5343 
5344  WatchpointList &wps = GetTarget().GetWatchpointList();
5345  size_t wp_count = wps.GetSize();
5346  for (size_t i = 0; i < wp_count; ++i) {
5347  WatchpointSP wp = wps.GetByIndex(i);
5348  if (wp->IsEnabled()) {
5349  GDBStoppointType type = GetGDBStoppointType(wp.get());
5350  m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5351  wp->GetByteSize(),
5352  GetInterruptTimeout());
5353  }
5354  }
5355 }
5356 
5357 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5359 
5360  lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5361  // Any valid TID will suffice, thread-relevant actions will set a proper TID
5362  // anyway.
5363  lldb::tid_t parent_tid = m_thread_ids.front();
5364 
5365  lldb::pid_t follow_pid, detach_pid;
5366  lldb::tid_t follow_tid, detach_tid;
5367 
5368  switch (GetFollowForkMode()) {
5369  case eFollowParent:
5370  follow_pid = parent_pid;
5371  follow_tid = parent_tid;
5372  detach_pid = child_pid;
5373  detach_tid = child_tid;
5374  break;
5375  case eFollowChild:
5376  follow_pid = child_pid;
5377  follow_tid = child_tid;
5378  detach_pid = parent_pid;
5379  detach_tid = parent_tid;
5380  break;
5381  }
5382 
5383  // Switch to the process that is going to be detached.
5384  if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5385  LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5386  return;
5387  }
5388 
5389  // Disable all software breakpoints in the forked process.
5390  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5391  DidForkSwitchSoftwareBreakpoints(false);
5392 
5393  // Remove hardware breakpoints / watchpoints from parent process if we're
5394  // following child.
5395  if (GetFollowForkMode() == eFollowChild)
5396  DidForkSwitchHardwareTraps(false);
5397 
5398  // Switch to the process that is going to be followed
5399  if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5400  !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5401  LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5402  return;
5403  }
5404 
5405  LLDB_LOG(log, "Detaching process {0}", detach_pid);
5406  Status error = m_gdb_comm.Detach(false, detach_pid);
5407  if (error.Fail()) {
5408  LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5409  error.AsCString() ? error.AsCString() : "<unknown error>");
5410  return;
5411  }
5412 
5413  // Hardware breakpoints/watchpoints are not inherited implicitly,
5414  // so we need to readd them if we're following child.
5415  if (GetFollowForkMode() == eFollowChild)
5416  DidForkSwitchHardwareTraps(true);
5417 }
5418 
5419 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5421 
5422  assert(!m_vfork_in_progress);
5423  m_vfork_in_progress = true;
5424 
5425  // Disable all software breakpoints for the duration of vfork.
5426  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5427  DidForkSwitchSoftwareBreakpoints(false);
5428 
5429  lldb::pid_t detach_pid;
5430  lldb::tid_t detach_tid;
5431 
5432  switch (GetFollowForkMode()) {
5433  case eFollowParent:
5434  detach_pid = child_pid;
5435  detach_tid = child_tid;
5436  break;
5437  case eFollowChild:
5438  detach_pid = m_gdb_comm.GetCurrentProcessID();
5439  // Any valid TID will suffice, thread-relevant actions will set a proper TID
5440  // anyway.
5441  detach_tid = m_thread_ids.front();
5442 
5443  // Switch to the parent process before detaching it.
5444  if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5445  LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5446  return;
5447  }
5448 
5449  // Remove hardware breakpoints / watchpoints from the parent process.
5450  DidForkSwitchHardwareTraps(false);
5451 
5452  // Switch to the child process.
5453  if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5454  !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5455  LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5456  return;
5457  }
5458  break;
5459  }
5460 
5461  LLDB_LOG(log, "Detaching process {0}", detach_pid);
5462  Status error = m_gdb_comm.Detach(false, detach_pid);
5463  if (error.Fail()) {
5464  LLDB_LOG(log,
5465  "ProcessGDBRemote::DidFork() detach packet send failed: {0}",