LLDB  mainline
GDBRemoteCommunicationServerLLGS.cpp
Go to the documentation of this file.
1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
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 <errno.h>
10 
11 #include "lldb/Host/Config.h"
12 
15 
16 #include <chrono>
17 #include <cstring>
18 #include <thread>
19 
21 #include "lldb/Host/Debug.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileAction.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/PosixApi.h"
32 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/Endian.h"
35 #include "lldb/Utility/JSON.h"
37 #include "lldb/Utility/Log.h"
39 #include "lldb/Utility/State.h"
41 #include "lldb/Utility/UriParser.h"
42 #include "llvm/ADT/Triple.h"
43 #include "llvm/Support/ScopedPrinter.h"
44 
45 #include "ProcessGDBRemote.h"
46 #include "ProcessGDBRemoteLog.h"
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 using namespace lldb_private::process_gdb_remote;
52 using namespace llvm;
53 
54 // GDBRemote Errors
55 
56 namespace {
58  // Set to the first unused error number in literal form below
59  eErrorFirst = 29,
60  eErrorNoProcess = eErrorFirst,
61  eErrorResume,
62  eErrorExitStatus
63 };
64 }
65 
66 // GDBRemoteCommunicationServerLLGS constructor
67 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
68  MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
69  : GDBRemoteCommunicationServerCommon("gdb-remote.server",
70  "gdb-remote.server.rx_packet"),
71  m_mainloop(mainloop), m_process_factory(process_factory),
72  m_stdio_communication("process.stdio") {
73  RegisterPacketHandlers();
74 }
75 
76 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
173 
189 
191  [this](StringExtractorGDBRemote packet, Status &error,
192  bool &interrupt, bool &quit) {
193  quit = true;
194  return this->Handle_k(packet);
195  });
196 }
197 
199  m_process_launch_info = info;
200 }
201 
204 
206  return Status("%s: no process command line specified to launch",
207  __FUNCTION__);
208 
209  const bool should_forward_stdio =
210  m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
211  m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
212  m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
214  m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
215 
216  if (should_forward_stdio) {
218  return Status(std::move(Err));
219  }
220 
221  {
222  std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
223  assert(!m_debugged_process_up && "lldb-server creating debugged "
224  "process but one already exists");
225  auto process_or =
227  if (!process_or)
228  return Status(process_or.takeError());
229  m_debugged_process_up = std::move(*process_or);
230  }
231 
232  // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
233  // needed. llgs local-process debugging may specify PTY paths, which will
234  // make these file actions non-null process launch -i/e/o will also make
235  // these file actions non-null nullptr means that the traffic is expected to
236  // flow over gdb-remote protocol
237  if (should_forward_stdio) {
238  // nullptr means it's not redirected to file or pty (in case of LLGS local)
239  // at least one of stdio will be transferred pty<->gdb-remote we need to
240  // give the pty master handle to this object to read and/or write
241  LLDB_LOG(log,
242  "pid = {0}: setting up stdout/stderr redirection via $O "
243  "gdb-remote commands",
244  m_debugged_process_up->GetID());
245 
246  // Setup stdout/stderr mapping from inferior to $O
247  auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
248  if (terminal_fd >= 0) {
249  if (log)
250  log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
251  "inferior STDIO fd to %d",
252  __FUNCTION__, terminal_fd);
253  Status status = SetSTDIOFileDescriptor(terminal_fd);
254  if (status.Fail())
255  return status;
256  } else {
257  if (log)
258  log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
259  "inferior STDIO since terminal fd reported as %d",
260  __FUNCTION__, terminal_fd);
261  }
262  } else {
263  LLDB_LOG(log,
264  "pid = {0} skipping stdout/stderr redirection via $O: inferior "
265  "will communicate over client-provided file descriptors",
266  m_debugged_process_up->GetID());
267  }
268 
269  printf("Launched '%s' as process %" PRIu64 "...\n",
271  m_debugged_process_up->GetID());
272 
273  return Status();
274 }
275 
278  if (log)
279  log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
280  __FUNCTION__, pid);
281 
282  // Before we try to attach, make sure we aren't already monitoring something
283  // else.
284  if (m_debugged_process_up &&
286  return Status("cannot attach to process %" PRIu64
287  " when another process with pid %" PRIu64
288  " is being debugged.",
289  pid, m_debugged_process_up->GetID());
290 
291  // Try to attach.
292  auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
293  if (!process_or) {
294  Status status(process_or.takeError());
295  llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
296  status);
297  return status;
298  }
299  m_debugged_process_up = std::move(*process_or);
300 
301  // Setup stdout/stderr mapping from inferior.
302  auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
303  if (terminal_fd >= 0) {
304  if (log)
305  log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
306  "inferior STDIO fd to %d",
307  __FUNCTION__, terminal_fd);
308  Status status = SetSTDIOFileDescriptor(terminal_fd);
309  if (status.Fail())
310  return status;
311  } else {
312  if (log)
313  log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
314  "inferior STDIO since terminal fd reported as %d",
315  __FUNCTION__, terminal_fd);
316  }
317 
318  printf("Attached to process %" PRIu64 "...\n", pid);
319  return Status();
320 }
321 
323  NativeProcessProtocol *process) {
324  assert(process && "process cannot be NULL");
326  if (log) {
327  log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
328  "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
329  __FUNCTION__, process->GetID(),
330  StateAsCString(process->GetState()));
331  }
332 }
333 
336  NativeProcessProtocol *process) {
337  assert(process && "process cannot be NULL");
339 
340  // send W notification
341  auto wait_status = process->GetExitStatus();
342  if (!wait_status) {
343  LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
344  process->GetID());
345 
346  StreamGDBRemote response;
347  response.PutChar('E');
348  response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
349  return SendPacketNoLock(response.GetString());
350  }
351 
352  LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
353  *wait_status);
354 
355  StreamGDBRemote response;
356  response.Format("{0:g}", *wait_status);
357  return SendPacketNoLock(response.GetString());
358 }
359 
360 static void AppendHexValue(StreamString &response, const uint8_t *buf,
361  uint32_t buf_size, bool swap) {
362  int64_t i;
363  if (swap) {
364  for (i = buf_size - 1; i >= 0; i--)
365  response.PutHex8(buf[i]);
366  } else {
367  for (i = 0; i < buf_size; i++)
368  response.PutHex8(buf[i]);
369  }
370 }
371 
373  StreamString &response, NativeRegisterContext &reg_ctx,
374  const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
375  lldb::ByteOrder byte_order) {
376  RegisterValue reg_value;
377  if (!reg_value_p) {
378  Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
379  if (error.Success())
380  reg_value_p = &reg_value;
381  // else log.
382  }
383 
384  if (reg_value_p) {
385  AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
386  reg_value_p->GetByteSize(),
387  byte_order == lldb::eByteOrderLittle);
388  } else {
389  // Zero-out any unreadable values.
390  if (reg_info.byte_size > 0) {
391  std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
392  AppendHexValue(response, zeros.data(), zeros.size(), false);
393  }
394  }
395 }
396 
399 
400  NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
401 
402  JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
403 
404 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
405  // Expedite all registers in the first register set (i.e. should be GPRs)
406  // that are not contained in other registers.
407  const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
408  if (!reg_set_p)
409  return nullptr;
410  for (const uint32_t *reg_num_p = reg_set_p->registers;
411  *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
412  uint32_t reg_num = *reg_num_p;
413 #else
414  // Expedite only a couple of registers until we figure out why sending
415  // registers is expensive.
416  static const uint32_t k_expedited_registers[] = {
419 
420  for (const uint32_t *generic_reg_p = k_expedited_registers;
421  *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
423  eRegisterKindGeneric, *generic_reg_p);
424  if (reg_num == LLDB_INVALID_REGNUM)
425  continue; // Target does not support the given register.
426 #endif
427 
428  const RegisterInfo *const reg_info_p =
429  reg_ctx.GetRegisterInfoAtIndex(reg_num);
430  if (reg_info_p == nullptr) {
431  if (log)
432  log->Printf(
433  "%s failed to get register info for register index %" PRIu32,
434  __FUNCTION__, reg_num);
435  continue;
436  }
437 
438  if (reg_info_p->value_regs != nullptr)
439  continue; // Only expedite registers that are not contained in other
440  // registers.
441 
442  RegisterValue reg_value;
443  Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
444  if (error.Fail()) {
445  if (log)
446  log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
447  __FUNCTION__,
448  reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
449  reg_num, error.AsCString());
450  continue;
451  }
452 
453  StreamString stream;
454  WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
455  &reg_value, lldb::eByteOrderBig);
456 
457  register_object_sp->SetObject(
458  llvm::to_string(reg_num),
459  std::make_shared<JSONString>(stream.GetString()));
460  }
461 
462  return register_object_sp;
463 }
464 
465 static const char *GetStopReasonString(StopReason stop_reason) {
466  switch (stop_reason) {
467  case eStopReasonTrace:
468  return "trace";
470  return "breakpoint";
472  return "watchpoint";
473  case eStopReasonSignal:
474  return "signal";
476  return "exception";
477  case eStopReasonExec:
478  return "exec";
480  case eStopReasonInvalid:
483  case eStopReasonNone:
484  break; // ignored
485  }
486  return nullptr;
487 }
488 
490  bool abridged) {
492 
493  JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
494 
495  // Ensure we can get info on the given thread.
496  uint32_t thread_idx = 0;
497  for (NativeThreadProtocol *thread;
498  (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
499  ++thread_idx) {
500 
501  lldb::tid_t tid = thread->GetID();
502 
503  // Grab the reason this thread stopped.
504  struct ThreadStopInfo tid_stop_info;
505  std::string description;
506  if (!thread->GetStopReason(tid_stop_info, description))
507  return nullptr;
508 
509  const int signum = tid_stop_info.details.signal.signo;
510  if (log) {
511  log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
512  " tid %" PRIu64
513  " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
514  __FUNCTION__, process.GetID(), tid, signum,
515  tid_stop_info.reason, tid_stop_info.details.exception.type);
516  }
517 
518  JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
519  threads_array_sp->AppendObject(thread_obj_sp);
520 
521  if (!abridged) {
522  if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread))
523  thread_obj_sp->SetObject("registers", registers_sp);
524  }
525 
526  thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
527  if (signum != 0)
528  thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
529 
530  const std::string thread_name = thread->GetName();
531  if (!thread_name.empty())
532  thread_obj_sp->SetObject("name",
533  std::make_shared<JSONString>(thread_name));
534 
535  if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
536  thread_obj_sp->SetObject("reason",
537  std::make_shared<JSONString>(stop_reason_str));
538 
539  if (!description.empty())
540  thread_obj_sp->SetObject("description",
541  std::make_shared<JSONString>(description));
542 
543  if ((tid_stop_info.reason == eStopReasonException) &&
544  tid_stop_info.details.exception.type) {
545  thread_obj_sp->SetObject(
546  "metype",
547  std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
548 
549  JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
550  for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
551  ++i) {
552  medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
553  tid_stop_info.details.exception.data[i]));
554  }
555  thread_obj_sp->SetObject("medata", medata_array_sp);
556  }
557 
558  // TODO: Expedite interesting regions of inferior memory
559  }
560 
561  return threads_array_sp;
562 }
563 
566  lldb::tid_t tid) {
568 
569  // Ensure we have a debugged process.
570  if (!m_debugged_process_up ||
572  return SendErrorResponse(50);
573 
574  LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
575  m_debugged_process_up->GetID(), tid);
576 
577  // Ensure we can get info on the given thread.
578  NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
579  if (!thread)
580  return SendErrorResponse(51);
581 
582  // Grab the reason this thread stopped.
583  struct ThreadStopInfo tid_stop_info;
584  std::string description;
585  if (!thread->GetStopReason(tid_stop_info, description))
586  return SendErrorResponse(52);
587 
588  // FIXME implement register handling for exec'd inferiors.
589  // if (tid_stop_info.reason == eStopReasonExec) {
590  // const bool force = true;
591  // InitializeRegisters(force);
592  // }
593 
594  StreamString response;
595  // Output the T packet with the thread
596  response.PutChar('T');
597  int signum = tid_stop_info.details.signal.signo;
598  LLDB_LOG(
599  log,
600  "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
601  m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
602  tid_stop_info.details.exception.type);
603 
604  // Print the signal number.
605  response.PutHex8(signum & 0xff);
606 
607  // Include the tid.
608  response.Printf("thread:%" PRIx64 ";", tid);
609 
610  // Include the thread name if there is one.
611  const std::string thread_name = thread->GetName();
612  if (!thread_name.empty()) {
613  size_t thread_name_len = thread_name.length();
614 
615  if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
616  response.PutCString("name:");
617  response.PutCString(thread_name);
618  } else {
619  // The thread name contains special chars, send as hex bytes.
620  response.PutCString("hexname:");
621  response.PutStringAsRawHex8(thread_name);
622  }
623  response.PutChar(';');
624  }
625 
626  // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
627  // send all thread IDs back in the "threads" key whose value is a list of hex
628  // thread IDs separated by commas:
629  // "threads:10a,10b,10c;"
630  // This will save the debugger from having to send a pair of qfThreadInfo and
631  // qsThreadInfo packets, but it also might take a lot of room in the stop
632  // reply packet, so it must be enabled only on systems where there are no
633  // limits on packet lengths.
635  response.PutCString("threads:");
636 
637  uint32_t thread_index = 0;
638  NativeThreadProtocol *listed_thread;
639  for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
640  listed_thread; ++thread_index,
641  listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
642  if (thread_index > 0)
643  response.PutChar(',');
644  response.Printf("%" PRIx64, listed_thread->GetID());
645  }
646  response.PutChar(';');
647 
648  // Include JSON info that describes the stop reason for any threads that
649  // actually have stop reasons. We use the new "jstopinfo" key whose values
650  // is hex ascii JSON that contains the thread IDs thread stop info only for
651  // threads that have stop reasons. Only send this if we have more than one
652  // thread otherwise this packet has all the info it needs.
653  if (thread_index > 0) {
654  const bool threads_with_valid_stop_info_only = true;
655  JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
656  *m_debugged_process_up, threads_with_valid_stop_info_only);
657  if (threads_info_sp) {
658  response.PutCString("jstopinfo:");
659  StreamString unescaped_response;
660  threads_info_sp->Write(unescaped_response);
661  response.PutStringAsRawHex8(unescaped_response.GetData());
662  response.PutChar(';');
663  } else
664  LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
665  m_debugged_process_up->GetID());
666  }
667 
668  uint32_t i = 0;
669  response.PutCString("thread-pcs");
670  char delimiter = ':';
671  for (NativeThreadProtocol *thread;
672  (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
673  ++i) {
674  NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
675 
676  uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
678  const RegisterInfo *const reg_info_p =
679  reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
680 
681  RegisterValue reg_value;
682  Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
683  if (error.Fail()) {
684  if (log)
685  log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
686  __FUNCTION__,
687  reg_info_p->name ? reg_info_p->name
688  : "<unnamed-register>",
689  reg_to_read, error.AsCString());
690  continue;
691  }
692 
693  response.PutChar(delimiter);
694  delimiter = ',';
695  WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
696  &reg_value, endian::InlHostByteOrder());
697  }
698 
699  response.PutChar(';');
700  }
701 
702  //
703  // Expedite registers.
704  //
705 
706  // Grab the register context.
707  NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
708  // Expedite all registers in the first register set (i.e. should be GPRs)
709  // that are not contained in other registers.
710  const RegisterSet *reg_set_p;
711  if (reg_ctx.GetRegisterSetCount() > 0 &&
712  ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
713  if (log)
714  log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
715  "from set '%s' (registers set count: %zu)",
716  __FUNCTION__,
717  reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
718  reg_set_p->num_registers);
719 
720  for (const uint32_t *reg_num_p = reg_set_p->registers;
721  *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
722  const RegisterInfo *const reg_info_p =
723  reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
724  if (reg_info_p == nullptr) {
725  if (log)
726  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
727  "register info for register set '%s', register index "
728  "%" PRIu32,
729  __FUNCTION__,
730  reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
731  *reg_num_p);
732  } else if (reg_info_p->value_regs == nullptr) {
733  // Only expediate registers that are not contained in other registers.
734  RegisterValue reg_value;
735  Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
736  if (error.Success()) {
737  response.Printf("%.02x:", *reg_num_p);
738  WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
739  &reg_value, lldb::eByteOrderBig);
740  response.PutChar(';');
741  } else {
742  if (log)
743  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
744  "register '%s' index %" PRIu32 ": %s",
745  __FUNCTION__,
746  reg_info_p->name ? reg_info_p->name
747  : "<unnamed-register>",
748  *reg_num_p, error.AsCString());
749  }
750  }
751  }
752  }
753 
754  const char *reason_str = GetStopReasonString(tid_stop_info.reason);
755  if (reason_str != nullptr) {
756  response.Printf("reason:%s;", reason_str);
757  }
758 
759  if (!description.empty()) {
760  // Description may contains special chars, send as hex bytes.
761  response.PutCString("description:");
762  response.PutStringAsRawHex8(description);
763  response.PutChar(';');
764  } else if ((tid_stop_info.reason == eStopReasonException) &&
765  tid_stop_info.details.exception.type) {
766  response.PutCString("metype:");
767  response.PutHex64(tid_stop_info.details.exception.type);
768  response.PutCString(";mecount:");
769  response.PutHex32(tid_stop_info.details.exception.data_count);
770  response.PutChar(';');
771 
772  for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
773  response.PutCString("medata:");
774  response.PutHex64(tid_stop_info.details.exception.data[i]);
775  response.PutChar(';');
776  }
777  }
778 
779  return SendPacketNoLock(response.GetString());
780 }
781 
782 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
783  NativeProcessProtocol *process) {
784  assert(process && "process cannot be NULL");
785 
787  if (log)
788  log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
789 
791  if (result != PacketResult::Success) {
792  if (log)
793  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
794  "notification for PID %" PRIu64 ", state: eStateExited",
795  __FUNCTION__, process->GetID());
796  }
797 
798  // Close the pipe to the inferior terminal i/o if we launched it and set one
799  // up.
800  MaybeCloseInferiorTerminalConnection();
801 
802  // We are ready to exit the debug monitor.
803  m_exit_now = true;
805 }
806 
807 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
808  NativeProcessProtocol *process) {
809  assert(process && "process cannot be NULL");
810 
812  if (log)
813  log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
814 
815  // Send the stop reason unless this is the stop after the launch or attach.
816  switch (m_inferior_prev_state) {
817  case eStateLaunching:
818  case eStateAttaching:
819  // Don't send anything per debugserver behavior.
820  break;
821  default:
822  // In all other cases, send the stop reason.
824  if (result != PacketResult::Success) {
825  if (log)
826  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
827  "notification for PID %" PRIu64 ", state: eStateExited",
828  __FUNCTION__, process->GetID());
829  }
830  break;
831  }
832 }
833 
835  NativeProcessProtocol *process, lldb::StateType state) {
836  assert(process && "process cannot be NULL");
838  if (log) {
839  log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
840  "NativeProcessProtocol pid %" PRIu64 ", state: %s",
841  __FUNCTION__, process->GetID(), StateAsCString(state));
842  }
843 
844  switch (state) {
846  StartSTDIOForwarding();
847  break;
848 
850  // Make sure we get all of the pending stdout/stderr from the inferior and
851  // send it to the lldb host before we send the state change notification
852  SendProcessOutput();
853  // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
854  // does not interfere with our protocol.
855  StopSTDIOForwarding();
856  HandleInferiorState_Stopped(process);
857  break;
858 
860  // Same as above
861  SendProcessOutput();
862  StopSTDIOForwarding();
863  HandleInferiorState_Exited(process);
864  break;
865 
866  default:
867  if (log) {
868  log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
869  "change for pid %" PRIu64 ", new state: %s",
870  __FUNCTION__, process->GetID(), StateAsCString(state));
871  }
872  break;
873  }
874 
875  // Remember the previous state reported to us.
876  m_inferior_prev_state = state;
877 }
878 
880  ClearProcessSpecificData();
881 }
882 
883 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
885 
886  if (!m_handshake_completed) {
887  if (!HandshakeWithClient()) {
888  if (log)
889  log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
890  "client failed, exiting",
891  __FUNCTION__);
893  return;
894  }
895  m_handshake_completed = true;
896  }
897 
898  bool interrupt = false;
899  bool done = false;
900  Status error;
901  while (true) {
902  const PacketResult result = GetPacketAndSendResponse(
903  std::chrono::microseconds(0), error, interrupt, done);
904  if (result == PacketResult::ErrorReplyTimeout)
905  break; // No more packets in the queue
906 
907  if ((result != PacketResult::Success)) {
908  if (log)
909  log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
910  "failed: %s",
911  __FUNCTION__, error.AsCString());
913  break;
914  }
915  }
916 }
917 
919  std::unique_ptr<Connection> &&connection) {
920  IOObjectSP read_object_sp = connection->GetReadObject();
921  GDBRemoteCommunicationServer::SetConnection(connection.release());
922 
923  Status error;
925  read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
926  error);
927  return error;
928 }
929 
932  uint32_t len) {
933  if ((buffer == nullptr) || (len == 0)) {
934  // Nothing to send.
935  return PacketResult::Success;
936  }
937 
938  StreamString response;
939  response.PutChar('O');
940  response.PutBytesAsRawHex8(buffer, len);
941 
942  return SendPacketNoLock(response.GetString());
943 }
944 
946  Status error;
947 
948  // Set up the reading/handling of process I/O
949  std::unique_ptr<ConnectionFileDescriptor> conn_up(
950  new ConnectionFileDescriptor(fd, true));
951  if (!conn_up) {
952  error.SetErrorString("failed to create ConnectionFileDescriptor");
953  return error;
954  }
955 
957  m_stdio_communication.SetConnection(conn_up.release());
959  error.SetErrorString(
960  "failed to set connection for inferior I/O communication");
961  return error;
962  }
963 
964  return Status();
965 }
966 
967 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
968  // Don't forward if not connected (e.g. when attaching).
970  return;
971 
972  Status error;
976  [this](MainLoopBase &) { SendProcessOutput(); }, error);
977 
978  if (!m_stdio_handle_up) {
979  // Not much we can do about the failure. Log it and continue without
980  // forwarding.
982  log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
983  "forwarding: %s",
984  __FUNCTION__, error.AsCString());
985  }
986 }
987 
988 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
989  m_stdio_handle_up.reset();
990 }
991 
992 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
993  char buffer[1024];
994  ConnectionStatus status;
995  Status error;
996  while (true) {
997  size_t bytes_read = m_stdio_communication.Read(
998  buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
999  switch (status) {
1001  SendONotification(buffer, bytes_read);
1002  break;
1008  log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1009  "forwarding as communication returned status %d (error: "
1010  "%s)",
1011  __FUNCTION__, status, error.AsCString());
1012  m_stdio_handle_up.reset();
1013  return;
1014 
1017  return;
1018  }
1019  }
1020 }
1021 
1024  StringExtractorGDBRemote &packet) {
1026  // Fail if we don't have a current process.
1027  if (!m_debugged_process_up ||
1029  return SendErrorResponse(68);
1030 
1031  if (!packet.ConsumeFront("jTraceStart:"))
1032  return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1033 
1034  TraceOptions options;
1035  uint64_t type = std::numeric_limits<uint64_t>::max();
1036  uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1038  uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1039 
1040  auto json_object = StructuredData::ParseJSON(packet.Peek());
1041 
1042  if (!json_object ||
1043  json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1044  return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1045 
1046  auto json_dict = json_object->GetAsDictionary();
1047 
1048  json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1049  options.setMetaDataBufferSize(metabuffersize);
1050 
1051  json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1052  options.setTraceBufferSize(buffersize);
1053 
1054  json_dict->GetValueForKeyAsInteger("type", type);
1055  options.setType(static_cast<lldb::TraceType>(type));
1056 
1057  json_dict->GetValueForKeyAsInteger("threadid", tid);
1058  options.setThreadID(tid);
1059 
1060  StructuredData::ObjectSP custom_params_sp =
1061  json_dict->GetValueForKey("params");
1062  if (custom_params_sp &&
1063  custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1064  return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1065 
1066  options.setTraceParams(
1067  static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1068 
1069  if (buffersize == std::numeric_limits<uint64_t>::max() ||
1071  LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1072  type);
1073  return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1074  }
1075 
1076  Status error;
1078  uid = m_debugged_process_up->StartTrace(options, error);
1079  LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1080  if (error.Fail())
1081  return SendErrorResponse(error);
1082 
1083  StreamGDBRemote response;
1084  response.Printf("%" PRIx64, uid);
1085  return SendPacketNoLock(response.GetString());
1086 }
1087 
1090  StringExtractorGDBRemote &packet) {
1091  // Fail if we don't have a current process.
1092  if (!m_debugged_process_up ||
1094  return SendErrorResponse(68);
1095 
1096  if (!packet.ConsumeFront("jTraceStop:"))
1097  return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1098 
1101 
1102  auto json_object = StructuredData::ParseJSON(packet.Peek());
1103 
1104  if (!json_object ||
1105  json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1106  return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1107 
1108  auto json_dict = json_object->GetAsDictionary();
1109 
1110  if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1111  return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1112 
1113  json_dict->GetValueForKeyAsInteger("threadid", tid);
1114 
1115  Status error = m_debugged_process_up->StopTrace(uid, tid);
1116 
1117  if (error.Fail())
1118  return SendErrorResponse(error);
1119 
1120  return SendOKResponse();
1121 }
1122 
1125  StringExtractorGDBRemote &packet) {
1126 
1127  // Fail if we don't have a current process.
1128  if (!m_debugged_process_up ||
1130  return SendErrorResponse(68);
1131 
1132  if (!packet.ConsumeFront("jTraceConfigRead:"))
1133  return SendIllFormedResponse(packet,
1134  "jTraceConfigRead: Ill formed packet ");
1135 
1138 
1139  auto json_object = StructuredData::ParseJSON(packet.Peek());
1140 
1141  if (!json_object ||
1142  json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1143  return SendIllFormedResponse(packet,
1144  "jTraceConfigRead: Ill formed packet ");
1145 
1146  auto json_dict = json_object->GetAsDictionary();
1147 
1148  if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1149  return SendIllFormedResponse(packet,
1150  "jTraceConfigRead: Ill formed packet ");
1151 
1152  json_dict->GetValueForKeyAsInteger("threadid", threadid);
1153 
1154  TraceOptions options;
1155  StreamGDBRemote response;
1156 
1157  options.setThreadID(threadid);
1158  Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1159 
1160  if (error.Fail())
1161  return SendErrorResponse(error);
1162 
1163  StreamGDBRemote escaped_response;
1164  StructuredData::Dictionary json_packet;
1165 
1166  json_packet.AddIntegerItem("type", options.getType());
1167  json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1168  json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1169 
1170  StructuredData::DictionarySP custom_params = options.getTraceParams();
1171  if (custom_params)
1172  json_packet.AddItem("params", custom_params);
1173 
1174  StreamString json_string;
1175  json_packet.Dump(json_string, false);
1176  escaped_response.PutEscapedBytes(json_string.GetData(),
1177  json_string.GetSize());
1178  return SendPacketNoLock(escaped_response.GetString());
1179 }
1180 
1183  StringExtractorGDBRemote &packet) {
1184 
1185  // Fail if we don't have a current process.
1186  if (!m_debugged_process_up ||
1188  return SendErrorResponse(68);
1189 
1190  enum PacketType { MetaData, BufferData };
1191  PacketType tracetype = MetaData;
1192 
1193  if (packet.ConsumeFront("jTraceBufferRead:"))
1194  tracetype = BufferData;
1195  else if (packet.ConsumeFront("jTraceMetaRead:"))
1196  tracetype = MetaData;
1197  else {
1198  return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1199  }
1200 
1202 
1203  uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1205  uint64_t offset = std::numeric_limits<uint64_t>::max();
1206 
1207  auto json_object = StructuredData::ParseJSON(packet.Peek());
1208 
1209  if (!json_object ||
1210  json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1211  return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1212 
1213  auto json_dict = json_object->GetAsDictionary();
1214 
1215  if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1216  !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1217  !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1218  return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1219 
1220  json_dict->GetValueForKeyAsInteger("threadid", tid);
1221 
1222  // Allocate the response buffer.
1223  std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1224  if (!buffer)
1225  return SendErrorResponse(0x78);
1226 
1227  StreamGDBRemote response;
1228  Status error;
1229  llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1230 
1231  if (tracetype == BufferData)
1232  error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1233  else if (tracetype == MetaData)
1234  error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1235 
1236  if (error.Fail())
1237  return SendErrorResponse(error);
1238 
1239  for (auto i : buf)
1240  response.PutHex8(i);
1241 
1242  StreamGDBRemote escaped_response;
1243  escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1244  return SendPacketNoLock(escaped_response.GetString());
1245 }
1246 
1249  StringExtractorGDBRemote &packet) {
1250  // Fail if we don't have a current process.
1251  if (!m_debugged_process_up ||
1253  return SendErrorResponse(68);
1254 
1255  lldb::pid_t pid = m_debugged_process_up->GetID();
1256 
1257  if (pid == LLDB_INVALID_PROCESS_ID)
1258  return SendErrorResponse(1);
1259 
1260  ProcessInstanceInfo proc_info;
1261  if (!Host::GetProcessInfo(pid, proc_info))
1262  return SendErrorResponse(1);
1263 
1264  StreamString response;
1265  CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1266  return SendPacketNoLock(response.GetString());
1267 }
1268 
1271  // Fail if we don't have a current process.
1272  if (!m_debugged_process_up ||
1274  return SendErrorResponse(68);
1275 
1276  // Make sure we set the current thread so g and p packets return the data the
1277  // gdb will expect.
1278  lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1279  SetCurrentThreadID(tid);
1280 
1281  NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1282  if (!thread)
1283  return SendErrorResponse(69);
1284 
1285  StreamString response;
1286  response.Printf("QC%" PRIx64, thread->GetID());
1287 
1288  return SendPacketNoLock(response.GetString());
1289 }
1290 
1294 
1295  StopSTDIOForwarding();
1296 
1297  if (!m_debugged_process_up) {
1298  LLDB_LOG(log, "No debugged process found.");
1299  return PacketResult::Success;
1300  }
1301 
1302  Status error = m_debugged_process_up->Kill();
1303  if (error.Fail())
1304  LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1305  m_debugged_process_up->GetID(), error);
1306 
1307  // No OK response for kill packet.
1308  // return SendOKResponse ();
1309  return PacketResult::Success;
1310 }
1311 
1314  StringExtractorGDBRemote &packet) {
1315  packet.SetFilePos(::strlen("QSetDisableASLR:"));
1316  if (packet.GetU32(0))
1317  m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1318  else
1319  m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1320  return SendOKResponse();
1321 }
1322 
1325  StringExtractorGDBRemote &packet) {
1326  packet.SetFilePos(::strlen("QSetWorkingDir:"));
1327  std::string path;
1328  packet.GetHexByteString(path);
1330  return SendOKResponse();
1331 }
1332 
1335  StringExtractorGDBRemote &packet) {
1337  if (working_dir) {
1338  StreamString response;
1339  response.PutStringAsRawHex8(working_dir.GetCString());
1340  return SendPacketNoLock(response.GetString());
1341  }
1342 
1343  return SendErrorResponse(14);
1344 }
1345 
1349  if (log)
1350  log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1351 
1352  // Ensure we have a native process.
1353  if (!m_debugged_process_up) {
1354  if (log)
1355  log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1356  "shared pointer",
1357  __FUNCTION__);
1358  return SendErrorResponse(0x36);
1359  }
1360 
1361  // Pull out the signal number.
1362  packet.SetFilePos(::strlen("C"));
1363  if (packet.GetBytesLeft() < 1) {
1364  // Shouldn't be using a C without a signal.
1365  return SendIllFormedResponse(packet, "C packet specified without signal.");
1366  }
1367  const uint32_t signo =
1368  packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1369  if (signo == std::numeric_limits<uint32_t>::max())
1370  return SendIllFormedResponse(packet, "failed to parse signal number");
1371 
1372  // Handle optional continue address.
1373  if (packet.GetBytesLeft() > 0) {
1374  // FIXME add continue at address support for $C{signo}[;{continue-address}].
1375  if (*packet.Peek() == ';')
1376  return SendUnimplementedResponse(packet.GetStringRef().c_str());
1377  else
1378  return SendIllFormedResponse(
1379  packet, "unexpected content after $C{signal-number}");
1380  }
1381 
1382  ResumeActionList resume_actions(StateType::eStateRunning, 0);
1383  Status error;
1384 
1385  // We have two branches: what to do if a continue thread is specified (in
1386  // which case we target sending the signal to that thread), or when we don't
1387  // have a continue thread set (in which case we send a signal to the
1388  // process).
1389 
1390  // TODO discuss with Greg Clayton, make sure this makes sense.
1391 
1392  lldb::tid_t signal_tid = GetContinueThreadID();
1393  if (signal_tid != LLDB_INVALID_THREAD_ID) {
1394  // The resume action for the continue thread (or all threads if a continue
1395  // thread is not set).
1397  static_cast<int>(signo)};
1398 
1399  // Add the action for the continue thread (or all threads when the continue
1400  // thread isn't present).
1401  resume_actions.Append(action);
1402  } else {
1403  // Send the signal to the process since we weren't targeting a specific
1404  // continue thread with the signal.
1405  error = m_debugged_process_up->Signal(signo);
1406  if (error.Fail()) {
1407  LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1408  m_debugged_process_up->GetID(), error);
1409 
1410  return SendErrorResponse(0x52);
1411  }
1412  }
1413 
1414  // Resume the threads.
1415  error = m_debugged_process_up->Resume(resume_actions);
1416  if (error.Fail()) {
1417  LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1418  m_debugged_process_up->GetID(), error);
1419 
1420  return SendErrorResponse(0x38);
1421  }
1422 
1423  // Don't send an "OK" packet; response is the stopped/exited message.
1424  return PacketResult::Success;
1425 }
1426 
1430  if (log)
1431  log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1432 
1433  packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1434 
1435  // For now just support all continue.
1436  const bool has_continue_address = (packet.GetBytesLeft() > 0);
1437  if (has_continue_address) {
1438  LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1439  packet.Peek());
1440  return SendUnimplementedResponse(packet.GetStringRef().c_str());
1441  }
1442 
1443  // Ensure we have a native process.
1444  if (!m_debugged_process_up) {
1445  if (log)
1446  log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1447  "shared pointer",
1448  __FUNCTION__);
1449  return SendErrorResponse(0x36);
1450  }
1451 
1452  // Build the ResumeActionList
1454 
1455  Status error = m_debugged_process_up->Resume(actions);
1456  if (error.Fail()) {
1457  LLDB_LOG(log, "c failed for process {0}: {1}",
1458  m_debugged_process_up->GetID(), error);
1459  return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1460  }
1461 
1462  LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1463  // No response required from continue.
1464  return PacketResult::Success;
1465 }
1466 
1469  StringExtractorGDBRemote &packet) {
1470  StreamString response;
1471  response.Printf("vCont;c;C;s;S");
1472 
1473  return SendPacketNoLock(response.GetString());
1474 }
1475 
1478  StringExtractorGDBRemote &packet) {
1480  if (log)
1481  log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1482  __FUNCTION__);
1483 
1484  packet.SetFilePos(::strlen("vCont"));
1485 
1486  if (packet.GetBytesLeft() == 0) {
1487  if (log)
1488  log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1489  "vCont package",
1490  __FUNCTION__);
1491  return SendIllFormedResponse(packet, "Missing action from vCont package");
1492  }
1493 
1494  // Check if this is all continue (no options or ";c").
1495  if (::strcmp(packet.Peek(), ";c") == 0) {
1496  // Move past the ';', then do a simple 'c'.
1497  packet.SetFilePos(packet.GetFilePos() + 1);
1498  return Handle_c(packet);
1499  } else if (::strcmp(packet.Peek(), ";s") == 0) {
1500  // Move past the ';', then do a simple 's'.
1501  packet.SetFilePos(packet.GetFilePos() + 1);
1502  return Handle_s(packet);
1503  }
1504 
1505  // Ensure we have a native process.
1506  if (!m_debugged_process_up) {
1507  LLDB_LOG(log, "no debugged process");
1508  return SendErrorResponse(0x36);
1509  }
1510 
1511  ResumeActionList thread_actions;
1512 
1513  while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1514  // Skip the semi-colon.
1515  packet.GetChar();
1516 
1517  // Build up the thread action.
1518  ResumeAction thread_action;
1519  thread_action.tid = LLDB_INVALID_THREAD_ID;
1520  thread_action.state = eStateInvalid;
1521  thread_action.signal = 0;
1522 
1523  const char action = packet.GetChar();
1524  switch (action) {
1525  case 'C':
1526  thread_action.signal = packet.GetHexMaxU32(false, 0);
1527  if (thread_action.signal == 0)
1528  return SendIllFormedResponse(
1529  packet, "Could not parse signal in vCont packet C action");
1530  LLVM_FALLTHROUGH;
1531 
1532  case 'c':
1533  // Continue
1534  thread_action.state = eStateRunning;
1535  break;
1536 
1537  case 'S':
1538  thread_action.signal = packet.GetHexMaxU32(false, 0);
1539  if (thread_action.signal == 0)
1540  return SendIllFormedResponse(
1541  packet, "Could not parse signal in vCont packet S action");
1542  LLVM_FALLTHROUGH;
1543 
1544  case 's':
1545  // Step
1546  thread_action.state = eStateStepping;
1547  break;
1548 
1549  default:
1550  return SendIllFormedResponse(packet, "Unsupported vCont action");
1551  break;
1552  }
1553 
1554  // Parse out optional :{thread-id} value.
1555  if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1556  // Consume the separator.
1557  packet.GetChar();
1558 
1559  thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1560  if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1561  return SendIllFormedResponse(
1562  packet, "Could not parse thread number in vCont packet");
1563  }
1564 
1565  thread_actions.Append(thread_action);
1566  }
1567 
1568  Status error = m_debugged_process_up->Resume(thread_actions);
1569  if (error.Fail()) {
1570  LLDB_LOG(log, "vCont failed for process {0}: {1}",
1571  m_debugged_process_up->GetID(), error);
1572  return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1573  }
1574 
1575  LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1576  // No response required from vCont.
1577  return PacketResult::Success;
1578 }
1579 
1582  LLDB_LOG(log, "setting current thread id to {0}", tid);
1583 
1584  m_current_tid = tid;
1586  m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1587 }
1588 
1591  LLDB_LOG(log, "setting continue thread id to {0}", tid);
1592 
1593  m_continue_tid = tid;
1594 }
1595 
1598  StringExtractorGDBRemote &packet) {
1599  // Handle the $? gdbremote command.
1600 
1601  // If no process, indicate error
1602  if (!m_debugged_process_up)
1603  return SendErrorResponse(02);
1604 
1605  return SendStopReasonForState(m_debugged_process_up->GetState());
1606 }
1607 
1610  lldb::StateType process_state) {
1612 
1613  switch (process_state) {
1614  case eStateAttaching:
1615  case eStateLaunching:
1616  case eStateRunning:
1617  case eStateStepping:
1618  case eStateDetached:
1619  // NOTE: gdb protocol doc looks like it should return $OK
1620  // when everything is running (i.e. no stopped result).
1621  return PacketResult::Success; // Ignore
1622 
1623  case eStateSuspended:
1624  case eStateStopped:
1625  case eStateCrashed: {
1626  lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1627  // Make sure we set the current thread so g and p packets return the data
1628  // the gdb will expect.
1629  SetCurrentThreadID(tid);
1630  return SendStopReplyPacketForThread(tid);
1631  }
1632 
1633  case eStateInvalid:
1634  case eStateUnloaded:
1635  case eStateExited:
1636  return SendWResponse(m_debugged_process_up.get());
1637 
1638  default:
1639  LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1640  m_debugged_process_up->GetID(), process_state);
1641  break;
1642  }
1643 
1644  return SendErrorResponse(0);
1645 }
1646 
1649  StringExtractorGDBRemote &packet) {
1650  // Fail if we don't have a current process.
1651  if (!m_debugged_process_up ||
1653  return SendErrorResponse(68);
1654 
1655  // Ensure we have a thread.
1656  NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1657  if (!thread)
1658  return SendErrorResponse(69);
1659 
1660  // Get the register context for the first thread.
1661  NativeRegisterContext &reg_context = thread->GetRegisterContext();
1662 
1663  // Parse out the register number from the request.
1664  packet.SetFilePos(strlen("qRegisterInfo"));
1665  const uint32_t reg_index =
1666  packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1667  if (reg_index == std::numeric_limits<uint32_t>::max())
1668  return SendErrorResponse(69);
1669 
1670  // Return the end of registers response if we've iterated one past the end of
1671  // the register set.
1672  if (reg_index >= reg_context.GetUserRegisterCount())
1673  return SendErrorResponse(69);
1674 
1675  const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1676  if (!reg_info)
1677  return SendErrorResponse(69);
1678 
1679  // Build the reginfos response.
1680  StreamGDBRemote response;
1681 
1682  response.PutCString("name:");
1683  response.PutCString(reg_info->name);
1684  response.PutChar(';');
1685 
1686  if (reg_info->alt_name && reg_info->alt_name[0]) {
1687  response.PutCString("alt-name:");
1688  response.PutCString(reg_info->alt_name);
1689  response.PutChar(';');
1690  }
1691 
1692  response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1693  reg_info->byte_size * 8, reg_info->byte_offset);
1694 
1695  switch (reg_info->encoding) {
1696  case eEncodingUint:
1697  response.PutCString("encoding:uint;");
1698  break;
1699  case eEncodingSint:
1700  response.PutCString("encoding:sint;");
1701  break;
1702  case eEncodingIEEE754:
1703  response.PutCString("encoding:ieee754;");
1704  break;
1705  case eEncodingVector:
1706  response.PutCString("encoding:vector;");
1707  break;
1708  default:
1709  break;
1710  }
1711 
1712  switch (reg_info->format) {
1713  case eFormatBinary:
1714  response.PutCString("format:binary;");
1715  break;
1716  case eFormatDecimal:
1717  response.PutCString("format:decimal;");
1718  break;
1719  case eFormatHex:
1720  response.PutCString("format:hex;");
1721  break;
1722  case eFormatFloat:
1723  response.PutCString("format:float;");
1724  break;
1725  case eFormatVectorOfSInt8:
1726  response.PutCString("format:vector-sint8;");
1727  break;
1728  case eFormatVectorOfUInt8:
1729  response.PutCString("format:vector-uint8;");
1730  break;
1731  case eFormatVectorOfSInt16:
1732  response.PutCString("format:vector-sint16;");
1733  break;
1734  case eFormatVectorOfUInt16:
1735  response.PutCString("format:vector-uint16;");
1736  break;
1737  case eFormatVectorOfSInt32:
1738  response.PutCString("format:vector-sint32;");
1739  break;
1740  case eFormatVectorOfUInt32:
1741  response.PutCString("format:vector-uint32;");
1742  break;
1744  response.PutCString("format:vector-float32;");
1745  break;
1746  case eFormatVectorOfUInt64:
1747  response.PutCString("format:vector-uint64;");
1748  break;
1750  response.PutCString("format:vector-uint128;");
1751  break;
1752  default:
1753  break;
1754  };
1755 
1756  const char *const register_set_name =
1757  reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1758  if (register_set_name) {
1759  response.PutCString("set:");
1760  response.PutCString(register_set_name);
1761  response.PutChar(';');
1762  }
1763 
1764  if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1766  response.Printf("ehframe:%" PRIu32 ";",
1767  reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1768 
1769  if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1770  response.Printf("dwarf:%" PRIu32 ";",
1771  reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1772 
1773  switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1775  response.PutCString("generic:pc;");
1776  break;
1778  response.PutCString("generic:sp;");
1779  break;
1781  response.PutCString("generic:fp;");
1782  break;
1784  response.PutCString("generic:ra;");
1785  break;
1787  response.PutCString("generic:flags;");
1788  break;
1790  response.PutCString("generic:arg1;");
1791  break;
1793  response.PutCString("generic:arg2;");
1794  break;
1796  response.PutCString("generic:arg3;");
1797  break;
1799  response.PutCString("generic:arg4;");
1800  break;
1802  response.PutCString("generic:arg5;");
1803  break;
1805  response.PutCString("generic:arg6;");
1806  break;
1808  response.PutCString("generic:arg7;");
1809  break;
1811  response.PutCString("generic:arg8;");
1812  break;
1813  default:
1814  break;
1815  }
1816 
1817  if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1818  response.PutCString("container-regs:");
1819  int i = 0;
1820  for (const uint32_t *reg_num = reg_info->value_regs;
1821  *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1822  if (i > 0)
1823  response.PutChar(',');
1824  response.Printf("%" PRIx32, *reg_num);
1825  }
1826  response.PutChar(';');
1827  }
1828 
1829  if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1830  response.PutCString("invalidate-regs:");
1831  int i = 0;
1832  for (const uint32_t *reg_num = reg_info->invalidate_regs;
1833  *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1834  if (i > 0)
1835  response.PutChar(',');
1836  response.Printf("%" PRIx32, *reg_num);
1837  }
1838  response.PutChar(';');
1839  }
1840 
1841  if (reg_info->dynamic_size_dwarf_expr_bytes) {
1842  const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1843  response.PutCString("dynamic_size_dwarf_expr_bytes:");
1844  for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1845  response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1846  response.PutChar(';');
1847  }
1848  return SendPacketNoLock(response.GetString());
1849 }
1850 
1853  StringExtractorGDBRemote &packet) {
1855 
1856  // Fail if we don't have a current process.
1857  if (!m_debugged_process_up ||
1859  LLDB_LOG(log, "no process ({0}), returning OK",
1860  m_debugged_process_up ? "invalid process id"
1861  : "null m_debugged_process_up");
1862  return SendOKResponse();
1863  }
1864 
1865  StreamGDBRemote response;
1866  response.PutChar('m');
1867 
1868  LLDB_LOG(log, "starting thread iteration");
1869  NativeThreadProtocol *thread;
1870  uint32_t thread_index;
1871  for (thread_index = 0,
1872  thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1873  thread; ++thread_index,
1874  thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1875  LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1876  thread->GetID());
1877  if (thread_index > 0)
1878  response.PutChar(',');
1879  response.Printf("%" PRIx64, thread->GetID());
1880  }
1881 
1882  LLDB_LOG(log, "finished thread iteration");
1883  return SendPacketNoLock(response.GetString());
1884 }
1885 
1888  StringExtractorGDBRemote &packet) {
1889  // FIXME for now we return the full thread list in the initial packet and
1890  // always do nothing here.
1891  return SendPacketNoLock("l");
1892 }
1893 
1897 
1898  // Parse out the register number from the request.
1899  packet.SetFilePos(strlen("p"));
1900  const uint32_t reg_index =
1901  packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1902  if (reg_index == std::numeric_limits<uint32_t>::max()) {
1903  if (log)
1904  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1905  "parse register number from request \"%s\"",
1906  __FUNCTION__, packet.GetStringRef().c_str());
1907  return SendErrorResponse(0x15);
1908  }
1909 
1910  // Get the thread to use.
1911  NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1912  if (!thread) {
1913  LLDB_LOG(log, "failed, no thread available");
1914  return SendErrorResponse(0x15);
1915  }
1916 
1917  // Get the thread's register context.
1918  NativeRegisterContext &reg_context = thread->GetRegisterContext();
1919 
1920  // Return the end of registers response if we've iterated one past the end of
1921  // the register set.
1922  if (reg_index >= reg_context.GetUserRegisterCount()) {
1923  if (log)
1924  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1925  "register %" PRIu32 " beyond register count %" PRIu32,
1926  __FUNCTION__, reg_index,
1927  reg_context.GetUserRegisterCount());
1928  return SendErrorResponse(0x15);
1929  }
1930 
1931  const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1932  if (!reg_info) {
1933  if (log)
1934  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1935  "register %" PRIu32 " returned NULL",
1936  __FUNCTION__, reg_index);
1937  return SendErrorResponse(0x15);
1938  }
1939 
1940  // Build the reginfos response.
1941  StreamGDBRemote response;
1942 
1943  // Retrieve the value
1944  RegisterValue reg_value;
1945  Status error = reg_context.ReadRegister(reg_info, reg_value);
1946  if (error.Fail()) {
1947  if (log)
1948  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1949  "requested register %" PRIu32 " (%s) failed: %s",
1950  __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1951  return SendErrorResponse(0x15);
1952  }
1953 
1954  const uint8_t *const data =
1955  reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1956  if (!data) {
1957  if (log)
1958  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1959  "bytes from requested register %" PRIu32,
1960  __FUNCTION__, reg_index);
1961  return SendErrorResponse(0x15);
1962  }
1963 
1964  // FIXME flip as needed to get data in big/little endian format for this host.
1965  for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1966  response.PutHex8(data[i]);
1967 
1968  return SendPacketNoLock(response.GetString());
1969 }
1970 
1974 
1975  // Ensure there is more content.
1976  if (packet.GetBytesLeft() < 1)
1977  return SendIllFormedResponse(packet, "Empty P packet");
1978 
1979  // Parse out the register number from the request.
1980  packet.SetFilePos(strlen("P"));
1981  const uint32_t reg_index =
1982  packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1983  if (reg_index == std::numeric_limits<uint32_t>::max()) {
1984  if (log)
1985  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1986  "parse register number from request \"%s\"",
1987  __FUNCTION__, packet.GetStringRef().c_str());
1988  return SendErrorResponse(0x29);
1989  }
1990 
1991  // Note debugserver would send an E30 here.
1992  if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
1993  return SendIllFormedResponse(
1994  packet, "P packet missing '=' char after register number");
1995 
1996  // Parse out the value.
1997  uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1998  size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
1999 
2000  // Get the thread to use.
2001  NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2002  if (!thread) {
2003  if (log)
2004  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2005  "available (thread index 0)",
2006  __FUNCTION__);
2007  return SendErrorResponse(0x28);
2008  }
2009 
2010  // Get the thread's register context.
2011  NativeRegisterContext &reg_context = thread->GetRegisterContext();
2012  const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2013  if (!reg_info) {
2014  if (log)
2015  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2016  "register %" PRIu32 " returned NULL",
2017  __FUNCTION__, reg_index);
2018  return SendErrorResponse(0x48);
2019  }
2020 
2021  // Return the end of registers response if we've iterated one past the end of
2022  // the register set.
2023  if (reg_index >= reg_context.GetUserRegisterCount()) {
2024  if (log)
2025  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2026  "register %" PRIu32 " beyond register count %" PRIu32,
2027  __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2028  return SendErrorResponse(0x47);
2029  }
2030 
2031  // The dwarf expression are evaluate on host site which may cause register
2032  // size to change Hence the reg_size may not be same as reg_info->bytes_size
2033  if ((reg_size != reg_info->byte_size) &&
2034  !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2035  return SendIllFormedResponse(packet, "P packet register size is incorrect");
2036  }
2037 
2038  // Build the reginfos response.
2039  StreamGDBRemote response;
2040 
2041  RegisterValue reg_value(
2042  reg_bytes, reg_size,
2043  m_debugged_process_up->GetArchitecture().GetByteOrder());
2044  Status error = reg_context.WriteRegister(reg_info, reg_value);
2045  if (error.Fail()) {
2046  if (log)
2047  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2048  "requested register %" PRIu32 " (%s) failed: %s",
2049  __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2050  return SendErrorResponse(0x32);
2051  }
2052 
2053  return SendOKResponse();
2054 }
2055 
2059 
2060  // Fail if we don't have a current process.
2061  if (!m_debugged_process_up ||
2063  if (log)
2064  log->Printf(
2065  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2066  __FUNCTION__);
2067  return SendErrorResponse(0x15);
2068  }
2069 
2070  // Parse out which variant of $H is requested.
2071  packet.SetFilePos(strlen("H"));
2072  if (packet.GetBytesLeft() < 1) {
2073  if (log)
2074  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2075  "missing {g,c} variant",
2076  __FUNCTION__);
2077  return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2078  }
2079 
2080  const char h_variant = packet.GetChar();
2081  switch (h_variant) {
2082  case 'g':
2083  break;
2084 
2085  case 'c':
2086  break;
2087 
2088  default:
2089  if (log)
2090  log->Printf(
2091  "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2092  __FUNCTION__, h_variant);
2093  return SendIllFormedResponse(packet,
2094  "H variant unsupported, should be c or g");
2095  }
2096 
2097  // Parse out the thread number.
2098  // FIXME return a parse success/fail value. All values are valid here.
2099  const lldb::tid_t tid =
2100  packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2101 
2102  // Ensure we have the given thread when not specifying -1 (all threads) or 0
2103  // (any thread).
2104  if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2105  NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2106  if (!thread) {
2107  if (log)
2108  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2109  " not found",
2110  __FUNCTION__, tid);
2111  return SendErrorResponse(0x15);
2112  }
2113  }
2114 
2115  // Now switch the given thread type.
2116  switch (h_variant) {
2117  case 'g':
2118  SetCurrentThreadID(tid);
2119  break;
2120 
2121  case 'c':
2122  SetContinueThreadID(tid);
2123  break;
2124 
2125  default:
2126  assert(false && "unsupported $H variant - shouldn't get here");
2127  return SendIllFormedResponse(packet,
2128  "H variant unsupported, should be c or g");
2129  }
2130 
2131  return SendOKResponse();
2132 }
2133 
2137 
2138  // Fail if we don't have a current process.
2139  if (!m_debugged_process_up ||
2141  if (log)
2142  log->Printf(
2143  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2144  __FUNCTION__);
2145  return SendErrorResponse(0x15);
2146  }
2147 
2148  packet.SetFilePos(::strlen("I"));
2149  uint8_t tmp[4096];
2150  for (;;) {
2151  size_t read = packet.GetHexBytesAvail(tmp);
2152  if (read == 0) {
2153  break;
2154  }
2155  // write directly to stdin *this might block if stdin buffer is full*
2156  // TODO: enqueue this block in circular buffer and send window size to
2157  // remote host
2158  ConnectionStatus status;
2159  Status error;
2160  m_stdio_communication.Write(tmp, read, status, &error);
2161  if (error.Fail()) {
2162  return SendErrorResponse(0x15);
2163  }
2164  }
2165 
2166  return SendOKResponse();
2167 }
2168 
2171  StringExtractorGDBRemote &packet) {
2173 
2174  // Fail if we don't have a current process.
2175  if (!m_debugged_process_up ||
2177  LLDB_LOG(log, "failed, no process available");
2178  return SendErrorResponse(0x15);
2179  }
2180 
2181  // Interrupt the process.
2182  Status error = m_debugged_process_up->Interrupt();
2183  if (error.Fail()) {
2184  LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2185  error);
2186  return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2187  }
2188 
2189  LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2190 
2191  // No response required from stop all.
2192  return PacketResult::Success;
2193 }
2194 
2197  StringExtractorGDBRemote &packet) {
2199 
2200  if (!m_debugged_process_up ||
2202  if (log)
2203  log->Printf(
2204  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2205  __FUNCTION__);
2206  return SendErrorResponse(0x15);
2207  }
2208 
2209  // Parse out the memory address.
2210  packet.SetFilePos(strlen("m"));
2211  if (packet.GetBytesLeft() < 1)
2212  return SendIllFormedResponse(packet, "Too short m packet");
2213 
2214  // Read the address. Punting on validation.
2215  // FIXME replace with Hex U64 read with no default value that fails on failed
2216  // read.
2217  const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2218 
2219  // Validate comma.
2220  if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2221  return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2222 
2223  // Get # bytes to read.
2224  if (packet.GetBytesLeft() < 1)
2225  return SendIllFormedResponse(packet, "Length missing in m packet");
2226 
2227  const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2228  if (byte_count == 0) {
2229  if (log)
2230  log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2231  "zero-length packet",
2232  __FUNCTION__);
2233  return SendOKResponse();
2234  }
2235 
2236  // Allocate the response buffer.
2237  std::string buf(byte_count, '\0');
2238  if (buf.empty())
2239  return SendErrorResponse(0x78);
2240 
2241  // Retrieve the process memory.
2242  size_t bytes_read = 0;
2243  Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2244  read_addr, &buf[0], byte_count, bytes_read);
2245  if (error.Fail()) {
2246  if (log)
2247  log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2248  " mem 0x%" PRIx64 ": failed to read. Error: %s",
2249  __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2250  error.AsCString());
2251  return SendErrorResponse(0x08);
2252  }
2253 
2254  if (bytes_read == 0) {
2255  if (log)
2256  log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2257  " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2258  __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2259  byte_count);
2260  return SendErrorResponse(0x08);
2261  }
2262 
2263  StreamGDBRemote response;
2264  packet.SetFilePos(0);
2265  char kind = packet.GetChar('?');
2266  if (kind == 'x')
2267  response.PutEscapedBytes(buf.data(), byte_count);
2268  else {
2269  assert(kind == 'm');
2270  for (size_t i = 0; i < bytes_read; ++i)
2271  response.PutHex8(buf[i]);
2272  }
2273 
2274  return SendPacketNoLock(response.GetString());
2275 }
2276 
2280 
2281  if (!m_debugged_process_up ||
2283  if (log)
2284  log->Printf(
2285  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2286  __FUNCTION__);
2287  return SendErrorResponse(0x15);
2288  }
2289 
2290  // Parse out the memory address.
2291  packet.SetFilePos(strlen("M"));
2292  if (packet.GetBytesLeft() < 1)
2293  return SendIllFormedResponse(packet, "Too short M packet");
2294 
2295  // Read the address. Punting on validation.
2296  // FIXME replace with Hex U64 read with no default value that fails on failed
2297  // read.
2298  const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2299 
2300  // Validate comma.
2301  if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2302  return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2303 
2304  // Get # bytes to read.
2305  if (packet.GetBytesLeft() < 1)
2306  return SendIllFormedResponse(packet, "Length missing in M packet");
2307 
2308  const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2309  if (byte_count == 0) {
2310  LLDB_LOG(log, "nothing to write: zero-length packet");
2311  return PacketResult::Success;
2312  }
2313 
2314  // Validate colon.
2315  if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2316  return SendIllFormedResponse(
2317  packet, "Comma sep missing in M packet after byte length");
2318 
2319  // Allocate the conversion buffer.
2320  std::vector<uint8_t> buf(byte_count, 0);
2321  if (buf.empty())
2322  return SendErrorResponse(0x78);
2323 
2324  // Convert the hex memory write contents to bytes.
2325  StreamGDBRemote response;
2326  const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2327  if (convert_count != byte_count) {
2328  LLDB_LOG(log,
2329  "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2330  "to convert.",
2331  m_debugged_process_up->GetID(), write_addr, byte_count,
2332  convert_count);
2333  return SendIllFormedResponse(packet, "M content byte length specified did "
2334  "not match hex-encoded content "
2335  "length");
2336  }
2337 
2338  // Write the process memory.
2339  size_t bytes_written = 0;
2340  Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2341  byte_count, bytes_written);
2342  if (error.Fail()) {
2343  LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2344  m_debugged_process_up->GetID(), write_addr, error);
2345  return SendErrorResponse(0x09);
2346  }
2347 
2348  if (bytes_written == 0) {
2349  LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2350  m_debugged_process_up->GetID(), write_addr, byte_count);
2351  return SendErrorResponse(0x09);
2352  }
2353 
2354  return SendOKResponse();
2355 }
2356 
2359  StringExtractorGDBRemote &packet) {
2361 
2362  // Currently only the NativeProcessProtocol knows if it can handle a
2363  // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2364  // attached to a process. For now we'll assume the client only asks this
2365  // when a process is being debugged.
2366 
2367  // Ensure we have a process running; otherwise, we can't figure this out
2368  // since we won't have a NativeProcessProtocol.
2369  if (!m_debugged_process_up ||
2371  if (log)
2372  log->Printf(
2373  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2374  __FUNCTION__);
2375  return SendErrorResponse(0x15);
2376  }
2377 
2378  // Test if we can get any region back when asking for the region around NULL.
2379  MemoryRegionInfo region_info;
2380  const Status error =
2381  m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2382  if (error.Fail()) {
2383  // We don't support memory region info collection for this
2384  // NativeProcessProtocol.
2385  return SendUnimplementedResponse("");
2386  }
2387 
2388  return SendOKResponse();
2389 }
2390 
2393  StringExtractorGDBRemote &packet) {
2395 
2396  // Ensure we have a process.
2397  if (!m_debugged_process_up ||
2399  if (log)
2400  log->Printf(
2401  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2402  __FUNCTION__);
2403  return SendErrorResponse(0x15);
2404  }
2405 
2406  // Parse out the memory address.
2407  packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2408  if (packet.GetBytesLeft() < 1)
2409  return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2410 
2411  // Read the address. Punting on validation.
2412  const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2413 
2414  StreamGDBRemote response;
2415 
2416  // Get the memory region info for the target address.
2417  MemoryRegionInfo region_info;
2418  const Status error =
2419  m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2420  if (error.Fail()) {
2421  // Return the error message.
2422 
2423  response.PutCString("error:");
2424  response.PutStringAsRawHex8(error.AsCString());
2425  response.PutChar(';');
2426  } else {
2427  // Range start and size.
2428  response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2429  region_info.GetRange().GetRangeBase(),
2430  region_info.GetRange().GetByteSize());
2431 
2432  // Permissions.
2433  if (region_info.GetReadable() || region_info.GetWritable() ||
2434  region_info.GetExecutable()) {
2435  // Write permissions info.
2436  response.PutCString("permissions:");
2437 
2438  if (region_info.GetReadable())
2439  response.PutChar('r');
2440  if (region_info.GetWritable())
2441  response.PutChar('w');
2442  if (region_info.GetExecutable())
2443  response.PutChar('x');
2444 
2445  response.PutChar(';');
2446  }
2447 
2448  // Name
2449  ConstString name = region_info.GetName();
2450  if (name) {
2451  response.PutCString("name:");
2452  response.PutStringAsRawHex8(name.AsCString());
2453  response.PutChar(';');
2454  }
2455  }
2456 
2457  return SendPacketNoLock(response.GetString());
2458 }
2459 
2462  // Ensure we have a process.
2463  if (!m_debugged_process_up ||
2466  LLDB_LOG(log, "failed, no process available");
2467  return SendErrorResponse(0x15);
2468  }
2469 
2470  // Parse out software or hardware breakpoint or watchpoint requested.
2471  packet.SetFilePos(strlen("Z"));
2472  if (packet.GetBytesLeft() < 1)
2473  return SendIllFormedResponse(
2474  packet, "Too short Z packet, missing software/hardware specifier");
2475 
2476  bool want_breakpoint = true;
2477  bool want_hardware = false;
2478  uint32_t watch_flags = 0;
2479 
2480  const GDBStoppointType stoppoint_type =
2482  switch (stoppoint_type) {
2483  case eBreakpointSoftware:
2484  want_hardware = false;
2485  want_breakpoint = true;
2486  break;
2487  case eBreakpointHardware:
2488  want_hardware = true;
2489  want_breakpoint = true;
2490  break;
2491  case eWatchpointWrite:
2492  watch_flags = 1;
2493  want_hardware = true;
2494  want_breakpoint = false;
2495  break;
2496  case eWatchpointRead:
2497  watch_flags = 2;
2498  want_hardware = true;
2499  want_breakpoint = false;
2500  break;
2501  case eWatchpointReadWrite:
2502  watch_flags = 3;
2503  want_hardware = true;
2504  want_breakpoint = false;
2505  break;
2506  case eStoppointInvalid:
2507  return SendIllFormedResponse(
2508  packet, "Z packet had invalid software/hardware specifier");
2509  }
2510 
2511  if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2512  return SendIllFormedResponse(
2513  packet, "Malformed Z packet, expecting comma after stoppoint type");
2514 
2515  // Parse out the stoppoint address.
2516  if (packet.GetBytesLeft() < 1)
2517  return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2518  const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2519 
2520  if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2521  return SendIllFormedResponse(
2522  packet, "Malformed Z packet, expecting comma after address");
2523 
2524  // Parse out the stoppoint size (i.e. size hint for opcode size).
2525  const uint32_t size =
2526  packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2527  if (size == std::numeric_limits<uint32_t>::max())
2528  return SendIllFormedResponse(
2529  packet, "Malformed Z packet, failed to parse size argument");
2530 
2531  if (want_breakpoint) {
2532  // Try to set the breakpoint.
2533  const Status error =
2534  m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2535  if (error.Success())
2536  return SendOKResponse();
2538  LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2539  m_debugged_process_up->GetID(), error);
2540  return SendErrorResponse(0x09);
2541  } else {
2542  // Try to set the watchpoint.
2543  const Status error = m_debugged_process_up->SetWatchpoint(
2544  addr, size, watch_flags, want_hardware);
2545  if (error.Success())
2546  return SendOKResponse();
2548  LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2549  m_debugged_process_up->GetID(), error);
2550  return SendErrorResponse(0x09);
2551  }
2552 }
2553 
2556  // Ensure we have a process.
2557  if (!m_debugged_process_up ||
2560  LLDB_LOG(log, "failed, no process available");
2561  return SendErrorResponse(0x15);
2562  }
2563 
2564  // Parse out software or hardware breakpoint or watchpoint requested.
2565  packet.SetFilePos(strlen("z"));
2566  if (packet.GetBytesLeft() < 1)
2567  return SendIllFormedResponse(
2568  packet, "Too short z packet, missing software/hardware specifier");
2569 
2570  bool want_breakpoint = true;
2571  bool want_hardware = false;
2572 
2573  const GDBStoppointType stoppoint_type =
2575  switch (stoppoint_type) {
2576  case eBreakpointHardware:
2577  want_breakpoint = true;
2578  want_hardware = true;
2579  break;
2580  case eBreakpointSoftware:
2581  want_breakpoint = true;
2582  break;
2583  case eWatchpointWrite:
2584  want_breakpoint = false;
2585  break;
2586  case eWatchpointRead:
2587  want_breakpoint = false;
2588  break;
2589  case eWatchpointReadWrite:
2590  want_breakpoint = false;
2591  break;
2592  default:
2593  return SendIllFormedResponse(
2594  packet, "z packet had invalid software/hardware specifier");
2595  }
2596 
2597  if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2598  return SendIllFormedResponse(
2599  packet, "Malformed z packet, expecting comma after stoppoint type");
2600 
2601  // Parse out the stoppoint address.
2602  if (packet.GetBytesLeft() < 1)
2603  return SendIllFormedResponse(packet, "Too short z packet, missing address");
2604  const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2605 
2606  if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2607  return SendIllFormedResponse(
2608  packet, "Malformed z packet, expecting comma after address");
2609 
2610  /*
2611  // Parse out the stoppoint size (i.e. size hint for opcode size).
2612  const uint32_t size = packet.GetHexMaxU32 (false,
2613  std::numeric_limits<uint32_t>::max ());
2614  if (size == std::numeric_limits<uint32_t>::max ())
2615  return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2616  size argument");
2617  */
2618 
2619  if (want_breakpoint) {
2620  // Try to clear the breakpoint.
2621  const Status error =
2622  m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2623  if (error.Success())
2624  return SendOKResponse();
2626  LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2627  m_debugged_process_up->GetID(), error);
2628  return SendErrorResponse(0x09);
2629  } else {
2630  // Try to clear the watchpoint.
2631  const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2632  if (error.Success())
2633  return SendOKResponse();
2635  LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2636  m_debugged_process_up->GetID(), error);
2637  return SendErrorResponse(0x09);
2638  }
2639 }
2640 
2644 
2645  // Ensure we have a process.
2646  if (!m_debugged_process_up ||
2648  if (log)
2649  log->Printf(
2650  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2651  __FUNCTION__);
2652  return SendErrorResponse(0x32);
2653  }
2654 
2655  // We first try to use a continue thread id. If any one or any all set, use
2656  // the current thread. Bail out if we don't have a thread id.
2658  if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2659  tid = GetCurrentThreadID();
2660  if (tid == LLDB_INVALID_THREAD_ID)
2661  return SendErrorResponse(0x33);
2662 
2663  // Double check that we have such a thread.
2664  // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2665  NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2666  if (!thread)
2667  return SendErrorResponse(0x33);
2668 
2669  // Create the step action for the given thread.
2670  ResumeAction action = {tid, eStateStepping, 0};
2671 
2672  // Setup the actions list.
2673  ResumeActionList actions;
2674  actions.Append(action);
2675 
2676  // All other threads stop while we're single stepping a thread.
2678  Status error = m_debugged_process_up->Resume(actions);
2679  if (error.Fail()) {
2680  if (log)
2681  log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2682  " tid %" PRIu64 " Resume() failed with error: %s",
2683  __FUNCTION__, m_debugged_process_up->GetID(), tid,
2684  error.AsCString());
2685  return SendErrorResponse(0x49);
2686  }
2687 
2688  // No response here - the stop or exit will come from the resulting action.
2689  return PacketResult::Success;
2690 }
2691 
2694  StringExtractorGDBRemote &packet) {
2695 // *BSD impls should be able to do this too.
2696 #if defined(__linux__) || defined(__NetBSD__)
2698 
2699  // Parse out the offset.
2700  packet.SetFilePos(strlen("qXfer:auxv:read::"));
2701  if (packet.GetBytesLeft() < 1)
2702  return SendIllFormedResponse(packet,
2703  "qXfer:auxv:read:: packet missing offset");
2704 
2705  const uint64_t auxv_offset =
2706  packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2707  if (auxv_offset == std::numeric_limits<uint64_t>::max())
2708  return SendIllFormedResponse(packet,
2709  "qXfer:auxv:read:: packet missing offset");
2710 
2711  // Parse out comma.
2712  if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2713  return SendIllFormedResponse(
2714  packet, "qXfer:auxv:read:: packet missing comma after offset");
2715 
2716  // Parse out the length.
2717  const uint64_t auxv_length =
2718  packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2719  if (auxv_length == std::numeric_limits<uint64_t>::max())
2720  return SendIllFormedResponse(packet,
2721  "qXfer:auxv:read:: packet missing length");
2722 
2723  // Grab the auxv data if we need it.
2724  if (!m_active_auxv_buffer_up) {
2725  // Make sure we have a valid process.
2726  if (!m_debugged_process_up ||
2728  if (log)
2729  log->Printf(
2730  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2731  __FUNCTION__);
2732  return SendErrorResponse(0x10);
2733  }
2734 
2735  // Grab the auxv data.
2736  auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2737  if (!buffer_or_error) {
2738  std::error_code ec = buffer_or_error.getError();
2739  LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2740  return SendErrorResponse(ec.value());
2741  }
2742  m_active_auxv_buffer_up = std::move(*buffer_or_error);
2743  }
2744 
2745  StreamGDBRemote response;
2746  bool done_with_buffer = false;
2747 
2748  llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2749  if (auxv_offset >= buffer.size()) {
2750  // We have nothing left to send. Mark the buffer as complete.
2751  response.PutChar('l');
2752  done_with_buffer = true;
2753  } else {
2754  // Figure out how many bytes are available starting at the given offset.
2755  buffer = buffer.drop_front(auxv_offset);
2756 
2757  // Mark the response type according to whether we're reading the remainder
2758  // of the auxv data.
2759  if (auxv_length >= buffer.size()) {
2760  // There will be nothing left to read after this
2761  response.PutChar('l');
2762  done_with_buffer = true;
2763  } else {
2764  // There will still be bytes to read after this request.
2765  response.PutChar('m');
2766  buffer = buffer.take_front(auxv_length);
2767  }
2768 
2769  // Now write the data in encoded binary form.
2770  response.PutEscapedBytes(buffer.data(), buffer.size());
2771  }
2772 
2773  if (done_with_buffer)
2774  m_active_auxv_buffer_up.reset();
2775 
2776  return SendPacketNoLock(response.GetString());
2777 #else
2778  return SendUnimplementedResponse("not implemented on this platform");
2779 #endif
2780 }
2781 
2784  StringExtractorGDBRemote &packet) {
2786 
2787  // Move past packet name.
2788  packet.SetFilePos(strlen("QSaveRegisterState"));
2789 
2790  // Get the thread to use.
2791  NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2792  if (!thread) {
2794  return SendIllFormedResponse(
2795  packet, "No thread specified in QSaveRegisterState packet");
2796  else
2797  return SendIllFormedResponse(packet,
2798  "No thread was is set with the Hg packet");
2799  }
2800 
2801  // Grab the register context for the thread.
2802  NativeRegisterContext& reg_context = thread->GetRegisterContext();
2803 
2804  // Save registers to a buffer.
2805  DataBufferSP register_data_sp;
2806  Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2807  if (error.Fail()) {
2808  LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2809  m_debugged_process_up->GetID(), error);
2810  return SendErrorResponse(0x75);
2811  }
2812 
2813  // Allocate a new save id.
2814  const uint32_t save_id = GetNextSavedRegistersID();
2815  assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2816  "GetNextRegisterSaveID() returned an existing register save id");
2817 
2818  // Save the register data buffer under the save id.
2819  {
2820  std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2821  m_saved_registers_map[save_id] = register_data_sp;
2822  }
2823 
2824  // Write the response.
2825  StreamGDBRemote response;
2826  response.Printf("%" PRIu32, save_id);
2827  return SendPacketNoLock(response.GetString());
2828 }
2829 
2832  StringExtractorGDBRemote &packet) {
2834 
2835  // Parse out save id.
2836  packet.SetFilePos(strlen("QRestoreRegisterState:"));
2837  if (packet.GetBytesLeft() < 1)
2838  return SendIllFormedResponse(
2839  packet, "QRestoreRegisterState packet missing register save id");
2840 
2841  const uint32_t save_id = packet.GetU32(0);
2842  if (save_id == 0) {
2843  LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2844  "expecting decimal uint32_t");
2845  return SendErrorResponse(0x76);
2846  }
2847 
2848  // Get the thread to use.
2849  NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2850  if (!thread) {
2852  return SendIllFormedResponse(
2853  packet, "No thread specified in QRestoreRegisterState packet");
2854  else
2855  return SendIllFormedResponse(packet,
2856  "No thread was is set with the Hg packet");
2857  }
2858 
2859  // Grab the register context for the thread.
2860  NativeRegisterContext &reg_context = thread->GetRegisterContext();
2861 
2862  // Retrieve register state buffer, then remove from the list.
2863  DataBufferSP register_data_sp;
2864  {
2865  std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2866 
2867  // Find the register set buffer for the given save id.
2868  auto it = m_saved_registers_map.find(save_id);
2869  if (it == m_saved_registers_map.end()) {
2870  LLDB_LOG(log,
2871  "pid {0} does not have a register set save buffer for id {1}",
2872  m_debugged_process_up->GetID(), save_id);
2873  return SendErrorResponse(0x77);
2874  }
2875  register_data_sp = it->second;
2876 
2877  // Remove it from the map.
2878  m_saved_registers_map.erase(it);
2879  }
2880 
2881  Status error = reg_context.WriteAllRegisterValues(register_data_sp);
2882  if (error.Fail()) {
2883  LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2884  m_debugged_process_up->GetID(), error);
2885  return SendErrorResponse(0x77);
2886  }
2887 
2888  return SendOKResponse();
2889 }
2890 
2893  StringExtractorGDBRemote &packet) {
2895 
2896  // Consume the ';' after vAttach.
2897  packet.SetFilePos(strlen("vAttach"));
2898  if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2899  return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2900 
2901  // Grab the PID to which we will attach (assume hex encoding).
2902  lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2903  if (pid == LLDB_INVALID_PROCESS_ID)
2904  return SendIllFormedResponse(packet,
2905  "vAttach failed to parse the process id");
2906 
2907  // Attempt to attach.
2908  if (log)
2909  log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2910  "pid %" PRIu64,
2911  __FUNCTION__, pid);
2912 
2913  Status error = AttachToProcess(pid);
2914 
2915  if (error.Fail()) {
2916  if (log)
2917  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2918  "pid %" PRIu64 ": %s\n",
2919  __FUNCTION__, pid, error.AsCString());
2920  return SendErrorResponse(error);
2921  }
2922 
2923  // Notify we attached by sending a stop packet.
2924  return SendStopReasonForState(m_debugged_process_up->GetState());
2925 }
2926 
2930 
2931  StopSTDIOForwarding();
2932 
2933  // Fail if we don't have a current process.
2934  if (!m_debugged_process_up ||
2936  if (log)
2937  log->Printf(
2938  "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2939  __FUNCTION__);
2940  return SendErrorResponse(0x15);
2941  }
2942 
2944 
2945  // Consume the ';' after D.
2946  packet.SetFilePos(1);
2947  if (packet.GetBytesLeft()) {
2948  if (packet.GetChar() != ';')
2949  return SendIllFormedResponse(packet, "D missing expected ';'");
2950 
2951  // Grab the PID from which we will detach (assume hex encoding).
2952  pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2953  if (pid == LLDB_INVALID_PROCESS_ID)
2954  return SendIllFormedResponse(packet, "D failed to parse the process id");
2955  }
2956 
2957  if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
2958  return SendIllFormedResponse(packet, "Invalid pid");
2959  }
2960 
2961  const Status error = m_debugged_process_up->Detach();
2962  if (error.Fail()) {
2963  if (log)
2964  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2965  "pid %" PRIu64 ": %s\n",
2966  __FUNCTION__, m_debugged_process_up->GetID(),
2967  error.AsCString());
2968  return SendErrorResponse(0x01);
2969  }
2970 
2971  return SendOKResponse();
2972 }
2973 
2976  StringExtractorGDBRemote &packet) {
2978 
2979  packet.SetFilePos(strlen("qThreadStopInfo"));
2980  const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2981  if (tid == LLDB_INVALID_THREAD_ID) {
2982  if (log)
2983  log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2984  "parse thread id from request \"%s\"",
2985  __FUNCTION__, packet.GetStringRef().c_str());
2986  return SendErrorResponse(0x15);
2987  }
2988  return SendStopReplyPacketForThread(tid);
2989 }
2990 
2995 
2996  // Ensure we have a debugged process.
2997  if (!m_debugged_process_up ||
2999  return SendErrorResponse(50);
3000  LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3001 
3002  StreamString response;
3003  const bool threads_with_valid_stop_info_only = false;
3004  JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3005  *m_debugged_process_up, threads_with_valid_stop_info_only);
3006  if (!threads_array_sp) {
3007  LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3008  m_debugged_process_up->GetID());
3009  return SendErrorResponse(52);
3010  }
3011 
3012  threads_array_sp->Write(response);
3013  StreamGDBRemote escaped_response;
3014  escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3015  return SendPacketNoLock(escaped_response.GetString());
3016 }
3017 
3020  StringExtractorGDBRemote &packet) {
3021  // Fail if we don't have a current process.
3022  if (!m_debugged_process_up ||
3024  return SendErrorResponse(68);
3025 
3026  packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3027  if (packet.GetBytesLeft() == 0)
3028  return SendOKResponse();
3029  if (packet.GetChar() != ':')
3030  return SendErrorResponse(67);
3031 
3032  auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3033 
3034  StreamGDBRemote response;
3035  if (hw_debug_cap == llvm::None)
3036  response.Printf("num:0;");
3037  else
3038  response.Printf("num:%d;", hw_debug_cap->second);
3039 
3040  return SendPacketNoLock(response.GetString());
3041 }
3042 
3045  StringExtractorGDBRemote &packet) {
3046  // Fail if we don't have a current process.
3047  if (!m_debugged_process_up ||
3049  return SendErrorResponse(67);
3050 
3051  packet.SetFilePos(strlen("qFileLoadAddress:"));
3052  if (packet.GetBytesLeft() == 0)
3053  return SendErrorResponse(68);
3054 
3055  std::string file_name;
3056  packet.GetHexByteString(file_name);
3057 
3058  lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3059  Status error =
3060  m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3061  if (error.Fail())
3062  return SendErrorResponse(69);
3063 
3064  if (file_load_address == LLDB_INVALID_ADDRESS)
3065  return SendErrorResponse(1); // File not loaded
3066 
3067  StreamGDBRemote response;
3068  response.PutHex64(file_load_address);
3069  return SendPacketNoLock(response.GetString());
3070 }
3071 
3074  StringExtractorGDBRemote &packet) {
3075  std::vector<int> signals;
3076  packet.SetFilePos(strlen("QPassSignals:"));
3077 
3078  // Read sequence of hex signal numbers divided by a semicolon and optionally
3079  // spaces.
3080  while (packet.GetBytesLeft() > 0) {
3081  int signal = packet.GetS32(-1, 16);
3082  if (signal < 0)
3083  return SendIllFormedResponse(packet, "Failed to parse signal number.");
3084  signals.push_back(signal);
3085 
3086  packet.SkipSpaces();
3087  char separator = packet.GetChar();
3088  if (separator == '\0')
3089  break; // End of string
3090  if (separator != ';')
3091  return SendIllFormedResponse(packet, "Invalid separator,"
3092  " expected semicolon.");
3093  }
3094 
3095  // Fail if we don't have a current process.
3096  if (!m_debugged_process_up)
3097  return SendErrorResponse(68);
3098 
3099  Status error = m_debugged_process_up->IgnoreSignals(signals);
3100  if (error.Fail())
3101  return SendErrorResponse(69);
3102 
3103  return SendOKResponse();
3104 }
3105 
3106 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3108 
3109  // Tell the stdio connection to shut down.
3111  auto connection = m_stdio_communication.GetConnection();
3112  if (connection) {
3113  Status error;
3114  connection->Disconnect(&error);
3115 
3116  if (error.Success()) {
3117  if (log)
3118  log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3119  "terminal stdio - SUCCESS",
3120  __FUNCTION__);
3121  } else {
3122  if (log)
3123  log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3124  "terminal stdio - FAIL: %s",
3125  __FUNCTION__, error.AsCString());
3126  }
3127  }
3128  }
3129 }
3130 
3131 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3132  StringExtractorGDBRemote &packet) {
3133  // We have no thread if we don't have a process.
3134  if (!m_debugged_process_up ||
3136  return nullptr;
3137 
3138  // If the client hasn't asked for thread suffix support, there will not be a
3139  // thread suffix. Use the current thread in that case.
3141  const lldb::tid_t current_tid = GetCurrentThreadID();
3142  if (current_tid == LLDB_INVALID_THREAD_ID)
3143  return nullptr;
3144  else if (current_tid == 0) {
3145  // Pick a thread.
3146  return m_debugged_process_up->GetThreadAtIndex(0);
3147  } else
3148  return m_debugged_process_up->GetThreadByID(current_tid);
3149  }
3150 
3152 
3153  // Parse out the ';'.
3154  if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3155  if (log)
3156  log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3157  "error: expected ';' prior to start of thread suffix: packet "
3158  "contents = '%s'",
3159  __FUNCTION__, packet.GetStringRef().c_str());
3160  return nullptr;
3161  }
3162 
3163  if (!packet.GetBytesLeft())
3164  return nullptr;
3165 
3166  // Parse out thread: portion.
3167  if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3168  if (log)
3169  log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3170  "error: expected 'thread:' but not found, packet contents = "
3171  "'%s'",
3172  __FUNCTION__, packet.GetStringRef().c_str());
3173  return nullptr;
3174  }
3175  packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3176  const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3177  if (tid != 0)
3178  return m_debugged_process_up->GetThreadByID(tid);
3179 
3180  return nullptr;
3181 }
3182 
3185  // Use whatever the debug process says is the current thread id since the
3186  // protocol either didn't specify or specified we want any/all threads
3187  // marked as the current thread.
3188  if (!m_debugged_process_up)
3189  return LLDB_INVALID_THREAD_ID;
3190  return m_debugged_process_up->GetCurrentThreadID();
3191  }
3192  // Use the specific current thread id set by the gdb remote protocol.
3193  return m_current_tid;
3194 }
3195 
3196 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3197  std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3198  return m_next_saved_registers_id++;
3199 }
3200 
3201 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3203 
3204  LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3205  m_active_auxv_buffer_up.reset();
3206 }
3207 
3208 FileSpec
3210  const ArchSpec &arch) {
3211  if (m_debugged_process_up) {
3212  FileSpec file_spec;
3214  ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3215  .Success()) {
3216  if (FileSystem::Instance().Exists(file_spec))
3217  return file_spec;
3218  }
3219  }
3220 
3221  return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
3222 }
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:61
uint32_t ConvertRegisterKindToRegisterNumber(uint32_t kind, uint32_t num) const
#define LLDB_REGNUM_GENERIC_PC
Definition: lldb-defines.h:63
#define LLDB_REGNUM_GENERIC_ARG6
Definition: lldb-defines.h:78
static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread)
virtual NativeRegisterContext & GetRegisterContext()=0
#define LIBLLDB_LOG_PROCESS
Definition: Logging.h:15
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:224
Definition: Debugger.h:71
#define GDBR_LOG_COMM
virtual llvm::Optional< WaitStatus > GetExitStatus()
#define lldbassert(x)
Definition: LLDBAssert.h:15
Process is currently trying to attach.
static void CreateProcessInfoResponse_DebugServerStyle(const ProcessInstanceInfo &proc_info, StreamString &response)
void setMetaDataBufferSize(uint64_t size)
Definition: TraceOptions.h:40
virtual Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp)=0
#define LLDB_REGNUM_GENERIC_RA
Definition: lldb-defines.h:66
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:92
void SetConnection(Connection *connection)
Sets the connection that it to be used by this class.
void Dump(Stream &s, bool pretty_print=true) const override
void setType(lldb::TraceType type)
Definition: TraceOptions.h:36
uint64_t GetFilePos() const
llvm::Error Error
void ProcessStateChanged(NativeProcessProtocol *process, lldb::StateType state) override
bool ConsumeFront(const llvm::StringRef &str)
int32_t GetS32(int32_t fail_value, int base=0)
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.cpp:254
void setTraceParams(const StructuredData::DictionarySP &dict_obj)
Definition: TraceOptions.h:32
OptionalBool GetReadable() const
#define LLDB_REGNUM_GENERIC_ARG4
Definition: lldb-defines.h:74
virtual const RegisterInfo * GetRegisterInfoAtIndex(uint32_t reg) const =0
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
Status LaunchProcess() override
Launch a process with the current launch settings.
#define LLDB_REGNUM_GENERIC_ARG2
Definition: lldb-defines.h:70
virtual FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch)
size_t GetHexByteString(std::string &str)
void AddItem(llvm::StringRef key, ObjectSP value_sp)
#define LLDB_REGNUM_GENERIC_SP
Definition: lldb-defines.h:64
Process or thread is stopped and can be examined.
const char * GetData() const
Definition: StreamString.h:43
#define LLDB_INVALID_UID
Definition: lldb-defines.h:91
#define LLDB_REGNUM_GENERIC_ARG7
Definition: lldb-defines.h:80
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:100
#define LIBLLDB_LOG_WATCHPOINTS
Definition: Logging.h:20
#define LLDB_LOG(log,...)
Definition: Log.h:209
#define LLDB_REGNUM_GENERIC_ARG5
Definition: lldb-defines.h:76
static FileSystem & Instance()
Process or thread has crashed and can be examined.
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx. ...
Definition: Args.cpp:256
static void AppendHexValue(StreamString &response, const uint8_t *buf, uint32_t buf_size, bool swap)
void swap(AdaptedConstIterator< C, E, A > &lhs, AdaptedConstIterator< C, E, A > &rhs)
Definition: Iterable.h:147
std::shared_ptr< JSONArray > SP
Definition: JSON.h:224
#define LLDB_REGNUM_GENERIC_ARG1
Definition: lldb-defines.h:68
lldb_private::Connection * GetConnection()
uint32_t GetU32(uint32_t fail_value, int base=0)
PacketResult SendIllFormedResponse(const StringExtractorGDBRemote &packet, const char *error_message)
std::shared_ptr< Dictionary > DictionarySP
const StructuredData::DictionarySP & getTraceParams() const
Definition: TraceOptions.h:22
Process has exited and can&#39;t be examined.
static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged)
ValueType Clear(ValueType mask=~(ValueType) 0)
Clear one or more flags.
Definition: Flags.h:72
OptionalBool GetWritable() const
#define LLDB_REGNUM_GENERIC_FP
Definition: lldb-defines.h:65
virtual Status ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
void Format(const char *format, Args &&... args)
Definition: Stream.h:422
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition: Stream.cpp:432
uint64_t user_id_t
Definition: lldb-types.h:84
static void WriteRegisterValueInHexFixedWidth(StreamString &response, NativeRegisterContext &reg_ctx, const RegisterInfo &reg_info, const RegisterValue *reg_value_p, lldb::ByteOrder byte_order)
virtual bool GetStopReason(ThreadStopInfo &stop_info, std::string &description)=0
virtual std::string GetName()=0
lldb::StateType state
Definition: Debug.h:23
#define LIBLLDB_LOG_THREAD
Definition: Logging.h:16
void setThreadID(lldb::tid_t thread_id)
Definition: TraceOptions.h:42
std::unordered_map< uint32_t, lldb::DataBufferSP > m_saved_registers_map
#define LIBLLDB_LOG_BREAKPOINTS
Definition: Logging.h:19
void RegisterPacketHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketHandler handler)
void SetFilePos(uint32_t idx)
Process has been detached and can&#39;t be examined.
uint64_t GetHexMaxU64(bool little_endian, uint64_t fail_value)
FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch) override
const char * GetRegisterSetNameForRegisterAtIndex(uint32_t reg_index) const
void SetLaunchInSeparateProcessGroup(bool separate)
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
Process is in the process of launching.
uint64_t tid_t
Definition: lldb-types.h:86
static ObjectSP ParseJSON(std::string json_text)
llvm::StringRef GetString() const
uint64_t getTraceBufferSize() const
Definition: TraceOptions.h:28
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
const void * GetBytes() const
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:306
uint64_t getMetaDataBufferSize() const
Definition: TraceOptions.h:30
size_t GetHexBytesAvail(llvm::MutableArrayRef< uint8_t > dest)
struct lldb_private::ThreadStopInfo::@11::@13 exception
virtual lldb::IOObjectSP GetReadObject()
Returns the underlying IOObject used by the Connection.
Definition: Connection.h:176
#define LLDB_REGNUM_GENERIC_FLAGS
Definition: lldb-defines.h:67
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
const FileAction * GetFileActionForFD(int fd) const
bool Success() const
Test for success condition.
Definition: Status.cpp:287
size_t GetBytesLeft()
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:322
Process or thread is in the process of stepping and can not be examined.
virtual llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate, MainLoop &mainloop) const =0
Launch a process for debugging.
bool SetDefaultThreadActionIfNeeded(lldb::StateType action, int signal)
Definition: Debug.h:98
ValueType Set(ValueType mask)
Set one or more flags by logical OR&#39;ing mask with the current flags.
Definition: Flags.h:84
static const char * GetStopReasonString(StopReason stop_reason)
Process is object is valid, but not currently loaded.
void RequestTermination() override
Definition: MainLoop.h:66
bool IsConnected() const
Check if the connection is valid.
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr)
Read bytes from the current connection.
virtual llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Attach(lldb::pid_t pid, NativeDelegate &native_delegate, MainLoop &mainloop) const =0
Attach to an existing process.
std::shared_ptr< JSONObject > SP
Definition: JSON.h:197
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
lldb::StopReason reason
Definition: Debug.h:134
virtual uint32_t GetUserRegisterCount() const =0
size_t PutChar(char ch)
Definition: Stream.cpp:103
void Append(const ResumeAction &action)
Definition: Debug.h:54
#define LLDB_INVALID_THREAD_ID
Definition: lldb-defines.h:93
uint64_t addr_t
Definition: lldb-types.h:83
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
Definition: Stream.cpp:284
A uniqued constant string class.
Definition: ConstString.h:38
#define LLDB_REGNUM_GENERIC_ARG8
Definition: lldb-defines.h:82
const FileSpec & GetWorkingDirectory() const
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
void SetWorkingDirectory(const FileSpec &working_dir)
void setTraceBufferSize(uint64_t size)
Definition: TraceOptions.h:38
Log * GetLogIfAnyCategoriesSet(uint32_t mask)
Definition: Logging.cpp:61
const char * Peek()
#define LLDB_REGNUM_GENERIC_ARG3
Definition: lldb-defines.h:72
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition: SBAddress.h:15
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
void RegisterMemberFunctionHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketResult(T::*handler)(StringExtractorGDBRemote &packet))
lldb::TraceType getType() const
Definition: TraceOptions.h:26
uint64_t pid_t
Definition: lldb-types.h:85
PacketResult GetPacketAndSendResponse(Timeout< std::micro > timeout, Status &error, bool &interrupt, bool &quit)
std::shared_ptr< Object > ObjectSP
uint32_t GetHexMaxU32(bool little_endian, uint32_t fail_value)
std::string & GetStringRef()
virtual const RegisterSet * GetRegisterSet(uint32_t set_index) const =0
lldb::ByteOrder InlHostByteOrder()
Definition: Endian.h:25
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
ValueType GetError() const
Access the error value.
Definition: Status.cpp:174
SizeType GetByteSize() const
Definition: RangeMap.h:71
virtual Status ReadAllRegisterValues(lldb::DataBufferSP &data_sp)=0
virtual Status WriteRegister(const RegisterInfo *reg_info, const RegisterValue &reg_value)=0
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
virtual uint32_t GetRegisterSetCount() const =0
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:406
struct lldb_private::ThreadStopInfo::@11::@12 signal
ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp, const Callback &callback, Status &error) override
Definition: MainLoop.cpp:269
char GetChar(char fail_value='\0')
void AddIntegerItem(llvm::StringRef key, uint64_t value)
union lldb_private::ThreadStopInfo::@11 details
An error handling class.
Definition: Status.h:44
OptionalBool GetExecutable() const
BaseType GetRangeBase() const
Definition: RangeMap.h:46
size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, Status *error_ptr)
The actual write function that attempts to write to the communications protocol.
NativeThreadProtocol * GetThreadAtIndex(uint32_t idx)
Process or thread is running and can&#39;t be examined.
#define LLDB_INVALID_REGNUM
Definition: lldb-defines.h:90