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