[Go to site: main page, start]

LLDB mainline
GDBRemoteCommunicationServerLLGS.cpp
Go to the documentation of this file.
1//===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <cerrno>
10
11#include "lldb/Host/Config.h"
12
13#include <chrono>
14#include <cstring>
15#include <limits>
16#include <optional>
17#include <thread>
18#include <variant>
19
22#include "lldb/Host/Debug.h"
23#include "lldb/Host/File.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Host/HostInfo.h"
28#include "lldb/Host/PosixApi.h"
29#include "lldb/Host/Socket.h"
35#include "lldb/Utility/Args.h"
37#include "lldb/Utility/Endian.h"
41#include "lldb/Utility/Log.h"
43#include "lldb/Utility/State.h"
47#include "llvm/ADT/StringSwitch.h"
48#include "llvm/Support/ErrorExtras.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/JSON.h"
51#include "llvm/Support/ScopedPrinter.h"
52#include "llvm/TargetParser/Triple.h"
53
54#include "ProcessGDBRemote.h"
55#include "ProcessGDBRemoteLog.h"
57
58using namespace lldb;
59using namespace lldb_private;
60using namespace lldb_private::lldb_server;
62using namespace llvm;
63
64// GDBRemote Errors
65
66namespace {
67enum GDBRemoteServerError {
68 // Set to the first unused error number in literal form below
69 eErrorFirst = 29,
70 eErrorNoProcess = eErrorFirst,
71 eErrorResume,
72 eErrorExitStatus
73};
74}
75
76// GDBRemoteCommunicationServerLLGS constructor
84
209
233 eServerPacketType_jAcceleratorPluginBreakpointHit,
236
239
243
247
249 [this](StringExtractorGDBRemote packet, Status &error,
250 bool &interrupt, bool &quit) {
251 quit = true;
252 return this->Handle_k(packet);
253 });
254
258
262
275}
276
280
283
284 if (!m_process_launch_info.GetArguments().GetArgumentCount())
286 "%s: no process command line specified to launch", __FUNCTION__);
287
288 const bool should_forward_stdio =
289 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
290 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
291 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
292 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
293 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
294
295 if (should_forward_stdio) {
296#if defined(_WIN32)
298 m_process_launch_info.GetSTDIOWindowSize();
299 if (m_process_launch_info.IsSTDIOWindowSizeExplicit() &&
300 win_size.cols == 0 && win_size.rows == 0) {
301 if (llvm::Error Err = m_process_launch_info.SetUpPipeRedirection())
302 return Status::FromError(std::move(Err));
303 } else {
304 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
305 return Status::FromError(std::move(Err));
306 }
307#else
308 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
309 return Status::FromError(std::move(Err));
310#endif
311 }
312
313 {
314 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
315 assert(m_debugged_processes.empty() && "lldb-server creating debugged "
316 "process but one already exists");
317 auto process_or = m_process_manager.Launch(m_process_launch_info, *this);
318 if (!process_or)
319 return Status::FromError(process_or.takeError());
320 m_continue_process = m_current_process = process_or->get();
321 m_debugged_processes.emplace(
322 m_current_process->GetID(),
323 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
324 }
325
326 SetEnabledExtensions(*m_current_process);
327
328 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
329 // needed. llgs local-process debugging may specify PTY paths, which will
330 // make these file actions non-null process launch -i/e/o will also make
331 // these file actions non-null nullptr means that the traffic is expected to
332 // flow over gdb-remote protocol
333 if (should_forward_stdio) {
334 // nullptr means it's not redirected to file or pty (in case of LLGS local)
335 // at least one of stdio will be transferred pty<->gdb-remote we need to
336 // give the pty primary handle to this object to read and/or write
337 LLDB_LOG(log,
338 "pid = {0}: setting up stdout/stderr redirection via $O "
339 "gdb-remote commands",
340 m_current_process->GetID());
341
342 // Setup stdout/stderr mapping from inferior to $O
343 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
344 if (terminal_fd >= 0) {
345 LLDB_LOGF(log,
346 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
347 "inferior STDIO fd to %d",
348 __FUNCTION__, terminal_fd);
349 Status status = SetSTDIOFileDescriptor(terminal_fd);
350 if (status.Fail())
351 return status;
352 } else {
353 LLDB_LOGF(log,
354 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
355 "inferior STDIO since terminal fd reported as %d",
356 __FUNCTION__, terminal_fd);
357 }
358 } else {
359 LLDB_LOG(log,
360 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
361 "will communicate over client-provided file descriptors",
362 m_current_process->GetID());
363 }
364
365 printf("Launched '%s' as process %" PRIu64 "...\n",
366 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
367 m_current_process->GetID());
368
369 return Status();
370}
371
374 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
375 __FUNCTION__, pid);
376
377 // Before we try to attach, make sure we aren't already monitoring something
378 // else.
379 if (!m_debugged_processes.empty())
381 "cannot attach to process %" PRIu64
382 " when another process with pid %" PRIu64 " is being debugged.",
383 pid, m_current_process->GetID());
384
385 // Try to attach.
386 auto process_or = m_process_manager.Attach(pid, *this);
387 if (!process_or) {
388 Status status = Status::FromError(process_or.takeError());
389 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
390 status);
391 return status;
392 }
393 m_continue_process = m_current_process = process_or->get();
394 m_debugged_processes.emplace(
395 m_current_process->GetID(),
396 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
397 SetEnabledExtensions(*m_current_process);
398
399 // Setup stdout/stderr mapping from inferior.
400 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
401 if (terminal_fd >= 0) {
402 LLDB_LOGF(log,
403 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
404 "inferior STDIO fd to %d",
405 __FUNCTION__, terminal_fd);
406 Status status = SetSTDIOFileDescriptor(terminal_fd);
407 if (status.Fail())
408 return status;
409 } else {
410 LLDB_LOGF(log,
411 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
412 "inferior STDIO since terminal fd reported as %d",
413 __FUNCTION__, terminal_fd);
414 }
415
416 printf("Attached to process %" PRIu64 "...\n", pid);
417 return Status();
418}
419
421 llvm::StringRef process_name, bool include_existing) {
423
424 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
425
426 // Create the matcher used to search the process list.
427 ProcessInstanceInfoList exclusion_list;
428 ProcessInstanceInfoMatch match_info;
430 process_name, llvm::sys::path::Style::native);
432
433 if (include_existing) {
434 LLDB_LOG(log, "including existing processes in search");
435 } else {
436 // Create the excluded process list before polling begins.
437 Host::FindProcesses(match_info, exclusion_list);
438 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
439 exclusion_list.size());
440 }
441
442 LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
443
444 auto is_in_exclusion_list =
445 [&exclusion_list](const ProcessInstanceInfo &info) {
446 for (auto &excluded : exclusion_list) {
447 if (excluded.GetProcessID() == info.GetProcessID())
448 return true;
449 }
450 return false;
451 };
452
453 ProcessInstanceInfoList loop_process_list;
454 while (true) {
455 loop_process_list.clear();
456 if (Host::FindProcesses(match_info, loop_process_list)) {
457 // Remove all the elements that are in the exclusion list.
458 llvm::erase_if(loop_process_list, is_in_exclusion_list);
459
460 // One match! We found the desired process.
461 if (loop_process_list.size() == 1) {
462 auto matching_process_pid = loop_process_list[0].GetProcessID();
463 LLDB_LOG(log, "found pid {0}", matching_process_pid);
464 return AttachToProcess(matching_process_pid);
465 }
466
467 // Multiple matches! Return an error reporting the PIDs we found.
468 if (loop_process_list.size() > 1) {
469 StreamString error_stream;
470 error_stream.Format(
471 "Multiple executables with name: '{0}' found. Pids: ",
472 process_name);
473 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
474 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
475 }
476 error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
477
479 error = Status(error_stream.GetString().str());
480 return error;
481 }
482 }
483 // No matches, we have not found the process. Sleep until next poll.
484 LLDB_LOG(log, "sleep {0} seconds", polling_interval);
485 std::this_thread::sleep_for(polling_interval);
486 }
487}
488
490 NativeProcessProtocol *process) {
491 assert(process && "process cannot be NULL");
493 LLDB_LOGF(log,
494 "GDBRemoteCommunicationServerLLGS::%s called with "
495 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
496 __FUNCTION__, process->GetID(),
497 StateAsCString(process->GetState()));
498}
499
502 NativeProcessProtocol *process) {
503 assert(process && "process cannot be NULL");
505
506 // send W notification
507 auto wait_status = process->GetExitStatus();
508 if (!wait_status) {
509 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
510 process->GetID());
511
512 StreamGDBRemote response;
513 response.PutChar('E');
514 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
515 return SendPacketNoLock(response.GetString());
516 }
517
518 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
519 *wait_status);
520
521 // If the process was killed through vKill, return "OK".
522 if (bool(m_debugged_processes.at(process->GetID()).flags &
524 return SendOKResponse();
525
526 StreamGDBRemote response;
527 response.Format("{0:g}", *wait_status);
528 if (bool(m_extensions_supported &
530 response.Format(";process:{0:x-}", process->GetID());
531 if (m_non_stop)
533 response.GetString());
534 return SendPacketNoLock(response.GetString());
535}
536
537static void AppendHexValue(StreamString &response, const uint8_t *buf,
538 uint32_t buf_size, bool swap) {
539 int64_t i;
540 if (swap) {
541 for (i = buf_size - 1; i >= 0; i--)
542 response.PutHex8(buf[i]);
543 } else {
544 for (i = 0; i < buf_size; i++)
545 response.PutHex8(buf[i]);
546 }
547}
548
549static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo &reg_info) {
550 switch (reg_info.encoding) {
551 case eEncodingUint:
552 return "uint";
553 case eEncodingSint:
554 return "sint";
555 case eEncodingIEEE754:
556 return "ieee754";
557 case eEncodingVector:
558 return "vector";
559 default:
560 return "";
561 }
562}
563
564static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo &reg_info) {
565 switch (reg_info.format) {
566 case eFormatDefault:
567 return "";
568 case eFormatBoolean:
569 return "boolean";
570 case eFormatBinary:
571 return "binary";
572 case eFormatBytes:
573 return "bytes";
575 return "bytes-with-ascii";
576 case eFormatChar:
577 return "char";
579 return "char-printable";
580 case eFormatComplex:
581 return "complex";
582 case eFormatCString:
583 return "cstring";
584 case eFormatDecimal:
585 return "decimal";
586 case eFormatEnum:
587 return "enum";
588 case eFormatHex:
589 return "hex";
591 return "hex-uppercase";
592 case eFormatFloat:
593 return "float";
594 case eFormatOctal:
595 return "octal";
596 case eFormatOSType:
597 return "ostype";
598 case eFormatUnicode16:
599 return "unicode16";
600 case eFormatUnicode32:
601 return "unicode32";
602 case eFormatUnsigned:
603 return "unsigned";
604 case eFormatPointer:
605 return "pointer";
607 return "vector-char";
609 return "vector-sint64";
611 return "vector-float16";
613 return "vector-float64";
615 return "vector-sint8";
617 return "vector-uint8";
619 return "vector-sint16";
621 return "vector-uint16";
623 return "vector-sint32";
625 return "vector-uint32";
627 return "vector-float32";
629 return "vector-uint64";
631 return "vector-uint128";
633 return "complex-integer";
634 case eFormatCharArray:
635 return "char-array";
637 return "address-info";
638 case eFormatHexFloat:
639 return "hex-float";
641 return "instruction";
642 case eFormatVoid:
643 return "void";
644 case eFormatUnicode8:
645 return "unicode8";
646 case eFormatFloat128:
647 return "float128";
648 default:
649 llvm_unreachable("Unknown register format");
650 };
651}
652
653static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo &reg_info) {
654 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
656 return "pc";
658 return "sp";
660 return "fp";
662 return "ra";
664 return "flags";
666 return "arg1";
668 return "arg2";
670 return "arg3";
672 return "arg4";
674 return "arg5";
676 return "arg6";
678 return "arg7";
680 return "arg8";
682 return "tp";
683 default:
684 return "";
685 }
686}
687
688static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
689 bool usehex) {
690 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
691 if (i > 0)
692 response.PutChar(',');
693 if (usehex)
694 response.Printf("%" PRIx32, *reg_num);
695 else
696 response.Printf("%" PRIu32, *reg_num);
697 }
698}
699
701 StreamString &response, NativeRegisterContext &reg_ctx,
702 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
703 lldb::ByteOrder byte_order) {
704 RegisterValue reg_value;
705 if (!reg_value_p) {
706 Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
707 if (error.Success())
708 reg_value_p = &reg_value;
709 // else log.
710 }
711
712 if (reg_value_p) {
713 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
714 reg_value_p->GetByteSize(),
715 byte_order == lldb::eByteOrderLittle);
716 } else {
717 // Zero-out any unreadable values.
718 if (reg_info.byte_size > 0) {
719 std::vector<uint8_t> zeros(reg_info.byte_size, '\0');
720 AppendHexValue(response, zeros.data(), zeros.size(), false);
721 }
722 }
723}
724
725static std::optional<json::Object>
727 Log *log = GetLog(LLDBLog::Thread);
728
729 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
730
731 json::Object register_object;
732
733#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
734 const auto expedited_regs =
736#else
737 const auto expedited_regs =
739#endif
740 if (expedited_regs.empty())
741 return std::nullopt;
742
743 for (auto &reg_num : expedited_regs) {
744 const RegisterInfo *const reg_info_p =
745 reg_ctx.GetRegisterInfoAtIndex(reg_num);
746 if (reg_info_p == nullptr) {
747 LLDB_LOGF(log,
748 "%s failed to get register info for register index %" PRIu32,
749 __FUNCTION__, reg_num);
750 continue;
751 }
752
753 if (reg_info_p->value_regs != nullptr)
754 continue; // Only expedite registers that are not contained in other
755 // registers.
756
757 RegisterValue reg_value;
758 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
759 if (error.Fail()) {
760 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
761 __FUNCTION__,
762 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
763 reg_num, error.AsCString());
764 continue;
765 }
766
767 StreamString stream;
768 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
769 &reg_value, lldb::eByteOrderBig);
770
771 register_object.try_emplace(llvm::to_string(reg_num),
772 stream.GetString().str());
773 }
774
775 return register_object;
776}
777
778static const char *GetStopReasonString(StopReason stop_reason) {
779 switch (stop_reason) {
780 case eStopReasonTrace:
781 return "trace";
783 return "breakpoint";
785 return "watchpoint";
787 return "signal";
789 return "exception";
790 case eStopReasonExec:
791 return "exec";
793 return "processor trace";
794 case eStopReasonFork:
795 return "fork";
796 case eStopReasonVFork:
797 return "vfork";
799 return "vforkdone";
801 return "async interrupt";
807 case eStopReasonNone:
808 break; // ignored
809 }
810 return nullptr;
811}
812
813static llvm::Expected<json::Array>
816
817 json::Array threads_array;
818
819 // Ensure we can get info on the given thread.
820 for (NativeThreadProtocol &thread : process.Threads()) {
821 lldb::tid_t tid = thread.GetID();
822 // Grab the reason this thread stopped.
823 struct ThreadStopInfo tid_stop_info;
824 std::string description;
825 if (!thread.GetStopReason(tid_stop_info, description))
826 return llvm::createStringError("failed to get stop reason");
827
828 const int signum = tid_stop_info.signo;
829 LLDB_LOGF(log,
830 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
831 " tid %" PRIu64
832 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
833 __FUNCTION__, process.GetID(), tid, signum, tid_stop_info.reason,
834 tid_stop_info.details.exception.type);
835
836 json::Object thread_obj;
837
838 if (!abridged) {
839 if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))
840 thread_obj.try_emplace("registers", std::move(*registers));
841 }
842
843 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
844
845 if (signum != 0)
846 thread_obj.try_emplace("signal", signum);
847
848 const std::string thread_name = thread.GetName();
849 if (!thread_name.empty())
850 thread_obj.try_emplace("name", thread_name);
851
852 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
853 if (stop_reason)
854 thread_obj.try_emplace("reason", stop_reason);
855
856 if (!description.empty())
857 thread_obj.try_emplace("description", description);
858
859 if ((tid_stop_info.reason == eStopReasonException) &&
860 tid_stop_info.details.exception.type) {
861 thread_obj.try_emplace(
862 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
863
864 json::Array medata_array;
865 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
866 ++i) {
867 medata_array.push_back(
868 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
869 }
870 thread_obj.try_emplace("medata", std::move(medata_array));
871 }
872 threads_array.push_back(std::move(thread_obj));
873 }
874 return threads_array;
875}
876
877StreamString
879 NativeThreadProtocol &thread) {
881
882 NativeProcessProtocol &process = thread.GetProcess();
883
884 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
885 thread.GetID());
886
887 // Grab the reason this thread stopped.
888 StreamString response;
889 struct ThreadStopInfo tid_stop_info;
890 std::string description;
891 if (!thread.GetStopReason(tid_stop_info, description))
892 return response;
893
894 // FIXME implement register handling for exec'd inferiors.
895 // if (tid_stop_info.reason == eStopReasonExec) {
896 // const bool force = true;
897 // InitializeRegisters(force);
898 // }
899
900 // Output the T packet with the thread
901 response.PutChar('T');
902 int signum = tid_stop_info.signo;
903 LLDB_LOG(
904 log,
905 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
906 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
907 tid_stop_info.details.exception.type);
908
909 // Print the signal number.
910 response.PutHex8(signum & 0xff);
911
912 // Include the (pid and) tid.
913 response.PutCString("thread:");
914 AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
915 response.PutChar(';');
916
917 // Include the thread name if there is one.
918 const std::string thread_name = thread.GetName();
919 if (!thread_name.empty()) {
920 size_t thread_name_len = thread_name.length();
921
922 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
923 response.PutCString("name:");
924 response.PutCString(thread_name);
925 } else {
926 // The thread name contains special chars, send as hex bytes.
927 response.PutCString("hexname:");
928 response.PutStringAsRawHex8(thread_name);
929 }
930 response.PutChar(';');
931 }
932
933 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
934 // send all thread IDs back in the "threads" key whose value is a list of hex
935 // thread IDs separated by commas:
936 // "threads:10a,10b,10c;"
937 // This will save the debugger from having to send a pair of qfThreadInfo and
938 // qsThreadInfo packets, but it also might take a lot of room in the stop
939 // reply packet, so it must be enabled only on systems where there are no
940 // limits on packet lengths.
942 response.PutCString("threads:");
943
944 uint32_t thread_num = 0;
945 for (NativeThreadProtocol &listed_thread : process.Threads()) {
946 if (thread_num > 0)
947 response.PutChar(',');
948 response.Printf("%" PRIx64, listed_thread.GetID());
949 ++thread_num;
950 }
951 response.PutChar(';');
952
953 // Include JSON info that describes the stop reason for any threads that
954 // actually have stop reasons. We use the new "jstopinfo" key whose values
955 // is hex ascii JSON that contains the thread IDs thread stop info only for
956 // threads that have stop reasons. Only send this if we have more than one
957 // thread otherwise this packet has all the info it needs.
958 if (thread_num > 1) {
959 const bool threads_with_valid_stop_info_only = true;
960 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
961 *m_current_process, threads_with_valid_stop_info_only);
962 if (threads_info) {
963 response.PutCString("jstopinfo:");
964 StreamString unescaped_response;
965 unescaped_response.AsRawOstream() << std::move(*threads_info);
966 response.PutStringAsRawHex8(unescaped_response.GetData());
967 response.PutChar(';');
968 } else {
969 LLDB_LOG_ERROR(log, threads_info.takeError(),
970 "failed to prepare a jstopinfo field for pid {1}: {0}",
971 process.GetID());
972 }
973 }
974
975 response.PutCString("thread-pcs");
976 char delimiter = ':';
977 for (NativeThreadProtocol &thread : process.Threads()) {
978 NativeRegisterContext &reg_ctx = thread.GetRegisterContext();
979
980 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
982 const RegisterInfo *const reg_info_p =
983 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
984
985 RegisterValue reg_value;
986 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
987 if (error.Fail()) {
988 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
989 __FUNCTION__,
990 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
991 reg_to_read, error.AsCString());
992 continue;
993 }
994
995 response.PutChar(delimiter);
996 delimiter = ',';
997 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
998 &reg_value, endian::InlHostByteOrder());
999 }
1000
1001 response.PutChar(';');
1002 }
1003
1004 //
1005 // Expedite registers.
1006 //
1007
1008 // Grab the register context.
1009 NativeRegisterContext &reg_ctx = thread.GetRegisterContext();
1010 const auto expedited_regs =
1012
1013 for (auto &reg_num : expedited_regs) {
1014 const RegisterInfo *const reg_info_p =
1015 reg_ctx.GetRegisterInfoAtIndex(reg_num);
1016 // Only expediate registers that are not contained in other registers.
1017 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
1018 RegisterValue reg_value;
1019 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
1020 if (error.Success()) {
1021 response.Printf("%.02x:", reg_num);
1022 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
1023 &reg_value, lldb::eByteOrderBig);
1024 response.PutChar(';');
1025 } else {
1026 LLDB_LOGF(log,
1027 "GDBRemoteCommunicationServerLLGS::%s failed to read "
1028 "register '%s' index %" PRIu32 ": %s",
1029 __FUNCTION__,
1030 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
1031 reg_num, error.AsCString());
1032 }
1033 }
1034 }
1035
1036 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
1037 if (reason_str != nullptr) {
1038 response.Printf("reason:%s;", reason_str);
1039 }
1040
1041 if (!description.empty()) {
1042 // Description may contains special chars, send as hex bytes.
1043 response.PutCString("description:");
1044 response.PutStringAsRawHex8(description);
1045 response.PutChar(';');
1046 } else if ((tid_stop_info.reason == eStopReasonException) &&
1047 tid_stop_info.details.exception.type) {
1048 response.PutCString("metype:");
1049 response.PutHex64(tid_stop_info.details.exception.type);
1050 response.PutCString(";mecount:");
1051 response.PutHex32(tid_stop_info.details.exception.data_count);
1052 response.PutChar(';');
1053
1054 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
1055 response.PutCString("medata:");
1056 response.PutHex64(tid_stop_info.details.exception.data[i]);
1057 response.PutChar(';');
1058 }
1059 }
1060
1061 // Include child process PID/TID for forks.
1062 if (tid_stop_info.reason == eStopReasonFork ||
1063 tid_stop_info.reason == eStopReasonVFork) {
1064 assert(bool(m_extensions_supported &
1066 if (tid_stop_info.reason == eStopReasonFork)
1067 assert(bool(m_extensions_supported &
1069 if (tid_stop_info.reason == eStopReasonVFork)
1070 assert(bool(m_extensions_supported &
1072 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
1073 tid_stop_info.details.fork.child_pid,
1074 tid_stop_info.details.fork.child_tid);
1075 }
1076
1077 if (process.HasPendingLibraryEvents()) {
1078 // 1 is an arbitrary value here. The parameter is ignored.
1079 response.PutCString("library:1;");
1080 }
1081
1082 return response;
1083}
1084
1087 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1088 // Ensure we can get info on the given thread.
1089 NativeThreadProtocol *thread = process.GetThreadByID(tid);
1090 if (!thread)
1091 return SendErrorResponse(51);
1092
1094 if (response.Empty())
1095 return SendErrorResponse(42);
1096
1097 if (m_non_stop && !force_synchronous) {
1099 "Stop", m_stop_notification_queue, response.GetString());
1100 // Queue notification events for the remaining threads.
1102 return ret;
1103 }
1104
1105 return SendPacketNoLock(response.GetString());
1106}
1107
1109 lldb::tid_t thread_to_skip) {
1110 if (!m_non_stop)
1111 return;
1112
1113 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1114 if (listed_thread.GetID() != thread_to_skip) {
1115 StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1116 if (!stop_reply.Empty())
1117 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1118 }
1119 }
1120}
1121
1123 NativeProcessProtocol *process) {
1124 assert(process && "process cannot be NULL");
1125
1126 Log *log = GetLog(LLDBLog::Process);
1127 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1128
1130 *process, StateType::eStateExited, /*force_synchronous=*/false);
1131 if (result != PacketResult::Success) {
1132 LLDB_LOGF(log,
1133 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1134 "notification for PID %" PRIu64 ", state: eStateExited",
1135 __FUNCTION__, process->GetID());
1136 }
1137
1138 if (m_current_process == process)
1139 m_current_process = nullptr;
1140 if (m_continue_process == process)
1141 m_continue_process = nullptr;
1142
1143 lldb::pid_t pid = process->GetID();
1144 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1145 auto find_it = m_debugged_processes.find(pid);
1146 assert(find_it != m_debugged_processes.end());
1147 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1148 m_debugged_processes.erase(find_it);
1149 // Terminate the main loop only if vKill has not been used.
1150 // When running in non-stop mode, wait for the vStopped to clear
1151 // the notification queue.
1152 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1153 // Close the pipe to the inferior terminal i/o if we launched it and set
1154 // one up.
1156
1157 // We are ready to exit the debug monitor.
1158 m_exit_now = true;
1159 loop.RequestTermination();
1160 }
1161 });
1162}
1163
1165 NativeProcessProtocol *process) {
1166 assert(process && "process cannot be NULL");
1167
1168 Log *log = GetLog(LLDBLog::Process);
1169 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1170
1172 *process, StateType::eStateStopped, /*force_synchronous=*/false);
1173 if (result != PacketResult::Success) {
1174 LLDB_LOGF(log,
1175 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1176 "notification for PID %" PRIu64 ", state: eStateExited",
1177 __FUNCTION__, process->GetID());
1178 }
1179}
1180
1182 NativeProcessProtocol *process, lldb::StateType state) {
1183 assert(process && "process cannot be NULL");
1184 Log *log = GetLog(LLDBLog::Process);
1185 LLDB_LOGF(log,
1186 "GDBRemoteCommunicationServerLLGS::%s called with "
1187 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1188 __FUNCTION__, process->GetID(), StateAsCString(state));
1189
1190 switch (state) {
1192 break;
1193
1195 // Make sure we get all of the pending stdout/stderr from the inferior and
1196 // send it to the lldb host before we send the state change notification
1198 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1199 // does not interfere with our protocol.
1200 if (!m_non_stop)
1203 break;
1204
1206 // Same as above
1208 if (!m_non_stop)
1211 break;
1212
1213 default:
1214 LLDB_LOGF(log,
1215 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1216 "change for pid %" PRIu64 ", new state: %s",
1217 __FUNCTION__, process->GetID(), StateAsCString(state));
1218 break;
1219 }
1220}
1221
1225
1227 NativeProcessProtocol *parent_process,
1228 std::unique_ptr<NativeProcessProtocol> child_process) {
1229 lldb::pid_t child_pid = child_process->GetID();
1230 assert(child_pid != LLDB_INVALID_PROCESS_ID);
1231 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1232 m_debugged_processes.emplace(
1233 child_pid,
1234 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1235}
1236
1238 llvm::StringRef data) {
1239 if (data.empty())
1240 return;
1241
1242 {
1243 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
1244 m_pending_output_buffer.append(data.begin(), data.end());
1245 }
1246 m_mainloop.AddPendingCallback(
1247 [this](MainLoopBase &) { FlushPendingProcessOutput(); });
1248}
1249
1252 return;
1253
1254 std::string out;
1255 {
1256 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
1257 if (m_pending_output_buffer.empty())
1258 return;
1259 out.swap(m_pending_output_buffer);
1260 }
1261 SendONotification(out.data(), out.size());
1262}
1263
1265 Log *log = GetLog(GDBRLog::Comm);
1266
1267 bool interrupt = false;
1268 bool done = false;
1269 Status error;
1270 while (true) {
1272 std::chrono::microseconds(0), error, interrupt, done);
1273 if (result == PacketResult::ErrorReplyTimeout)
1274 break; // No more packets in the queue
1275
1276 if ((result != PacketResult::Success)) {
1277 LLDB_LOGF(log,
1278 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1279 "failed: %s",
1280 __FUNCTION__, error.AsCString());
1281 m_mainloop.RequestTermination();
1282 break;
1283 }
1284 }
1285}
1286
1288 std::unique_ptr<Connection> connection) {
1289 IOObjectSP read_object_sp = connection->GetReadObject();
1290 GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1291
1292 Status error;
1293 m_network_handle_up = m_mainloop.RegisterReadObject(
1294 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1295 error);
1296 return error;
1297}
1298
1301 const llvm::json::Value &value) {
1302 std::string json_string;
1303 raw_string_ostream os(json_string);
1304 os << value;
1305
1306 StreamGDBRemote escaped_response;
1307 escaped_response.PutCString("JSON-async:");
1308 escaped_response.PutEscapedBytes(json_string.c_str(), json_string.size());
1309 return SendPacketNoLock(escaped_response.GetString());
1310}
1311
1314 uint32_t len) {
1315 if ((buffer == nullptr) || (len == 0)) {
1316 // Nothing to send.
1317 return PacketResult::Success;
1318 }
1319
1320 StreamString response;
1321 response.PutChar('O');
1322 response.PutBytesAsRawHex8(buffer, len);
1323
1324 if (m_non_stop)
1326 response.GetString());
1327 return SendPacketNoLock(response.GetString());
1328}
1329
1331 Status error;
1332
1333 // Set up the reading/handling of process I/O
1334 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1335 new ConnectionFileDescriptor(fd, true));
1336 if (!conn_up) {
1337 error =
1338 Status::FromErrorString("failed to create ConnectionFileDescriptor");
1339 return error;
1340 }
1341
1342 m_stdio_communication.SetCloseOnEOF(false);
1343 m_stdio_communication.SetConnection(std::move(conn_up));
1344 if (!m_stdio_communication.IsConnected()) {
1346 "failed to set connection for inferior I/O communication");
1347 return error;
1348 }
1349
1350 return Status();
1351}
1352
1354 // Don't forward if not connected (e.g. when attaching).
1355 if (!m_stdio_communication.IsConnected())
1356 return;
1357
1358 Status error;
1359 assert(!m_stdio_handle_up);
1360 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1361 m_stdio_communication.GetConnection()->GetReadObject(),
1362 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1363
1364 if (!m_stdio_handle_up) {
1365 // Not much we can do about the failure. Log it and continue without
1366 // forwarding.
1367 if (Log *log = GetLog(LLDBLog::Process))
1368 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1369 }
1370}
1371
1375
1377 char buffer[1024];
1378 ConnectionStatus status;
1379 Status error;
1380 while (true) {
1381 size_t bytes_read = m_stdio_communication.Read(
1382 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1383 switch (status) {
1385 SendONotification(buffer, bytes_read);
1386 break;
1391 if (Log *log = GetLog(LLDBLog::Process))
1392 LLDB_LOGF(log,
1393 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1394 "forwarding as communication returned status %d (error: "
1395 "%s)",
1396 __FUNCTION__, status, error.AsCString());
1397 m_stdio_handle_up.reset();
1398 return;
1399
1402 return;
1403 }
1404 }
1405}
1406
1409 StringExtractorGDBRemote &packet) {
1410
1411 // Fail if we don't have a current process.
1412 if (!m_current_process ||
1414 return SendErrorResponse(Status::FromErrorString("Process not running."));
1415
1416 return SendJSONResponse(m_current_process->TraceSupported());
1417}
1418
1421 StringExtractorGDBRemote &packet) {
1422 // Fail if we don't have a current process.
1423 if (!m_current_process ||
1425 return SendErrorResponse(Status::FromErrorString("Process not running."));
1426
1427 packet.ConsumeFront("jLLDBTraceStop:");
1428 Expected<TraceStopRequest> stop_request =
1429 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1430 if (!stop_request)
1431 return SendErrorResponse(stop_request.takeError());
1432
1433 if (Error err = m_current_process->TraceStop(*stop_request))
1434 return SendErrorResponse(std::move(err));
1435
1436 return SendOKResponse();
1437}
1438
1441 StringExtractorGDBRemote &packet) {
1442
1443 // Fail if we don't have a current process.
1444 if (!m_current_process ||
1446 return SendErrorResponse(Status::FromErrorString("Process not running."));
1447
1448 packet.ConsumeFront("jLLDBTraceStart:");
1449 Expected<TraceStartRequest> request =
1450 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1451 if (!request)
1452 return SendErrorResponse(request.takeError());
1453
1454 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1455 return SendErrorResponse(std::move(err));
1456
1457 return SendOKResponse();
1458}
1459
1462 StringExtractorGDBRemote &packet) {
1463
1464 // Fail if we don't have a current process.
1465 if (!m_current_process ||
1467 return SendErrorResponse(Status::FromErrorString("Process not running."));
1468
1469 packet.ConsumeFront("jLLDBTraceGetState:");
1470 Expected<TraceGetStateRequest> request =
1471 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1472 if (!request)
1473 return SendErrorResponse(request.takeError());
1474
1475 return SendJSONResponse(m_current_process->TraceGetState(request->type));
1476}
1477
1480 StringExtractorGDBRemote &packet) {
1481
1482 // Fail if we don't have a current process.
1483 if (!m_current_process ||
1485 return SendErrorResponse(Status::FromErrorString("Process not running."));
1486
1487 packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1488 llvm::Expected<TraceGetBinaryDataRequest> request =
1489 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1490 "TraceGetBinaryDataRequest");
1491 if (!request)
1492 return SendErrorResponse(Status::FromError(request.takeError()));
1493
1494 if (Expected<std::vector<uint8_t>> bytes =
1495 m_current_process->TraceGetBinaryData(*request)) {
1496 StreamGDBRemote response;
1497 response.PutEscapedBytes(bytes->data(), bytes->size());
1498 return SendPacketNoLock(response.GetString());
1499 } else
1500 return SendErrorResponse(bytes.takeError());
1501}
1502
1505 StringExtractorGDBRemote &packet) {
1506 // Fail if we don't have a current process.
1507 if (!m_current_process ||
1509 return SendErrorResponse(68);
1510
1511 std::vector<std::string> structured_data_plugins =
1512 m_current_process->GetStructuredDataPlugins();
1513
1514 return SendJSONResponse(
1515 llvm::json::Value(llvm::json::Array(structured_data_plugins)));
1516}
1517
1520 StringExtractorGDBRemote &packet) {
1521 // Fail if we don't have a current process.
1522 if (!m_current_process ||
1524 return SendErrorResponse(68);
1525
1526 lldb::pid_t pid = m_current_process->GetID();
1527
1528 if (pid == LLDB_INVALID_PROCESS_ID)
1529 return SendErrorResponse(1);
1530
1531 ProcessInstanceInfo proc_info;
1532 if (!Host::GetProcessInfo(pid, proc_info))
1533 return SendErrorResponse(1);
1534
1535 StreamString response;
1536 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1537 return SendPacketNoLock(response.GetString());
1538}
1539
1542 // Fail if we don't have a current process.
1543 if (!m_current_process ||
1545 return SendErrorResponse(68);
1546
1547 // Make sure we set the current thread so g and p packets return the data the
1548 // gdb will expect.
1549 lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1550 SetCurrentThreadID(tid);
1551
1552 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1553 if (!thread)
1554 return SendErrorResponse(69);
1555
1556 StreamString response;
1557 response.PutCString("QC");
1559 thread->GetID());
1560
1561 return SendPacketNoLock(response.GetString());
1562}
1563
1566 Log *log = GetLog(LLDBLog::Process);
1567
1568 if (!m_non_stop)
1570
1571 if (m_debugged_processes.empty()) {
1572 LLDB_LOG(log, "No debugged process found.");
1573 return PacketResult::Success;
1574 }
1575
1576 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1577 ++it) {
1578 LLDB_LOG(log, "Killing process {0}", it->first);
1579 Status error = it->second.process_up->Kill();
1580 if (error.Fail())
1581 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1582 error);
1583 }
1584
1585 // The response to kill packet is undefined per the spec. LLDB
1586 // follows the same rules as for continue packets, i.e. no response
1587 // in all-stop mode, and "OK" in non-stop mode; in both cases this
1588 // is followed by the actual stop reason.
1590}
1591
1594 StringExtractorGDBRemote &packet) {
1595 if (!m_non_stop)
1597
1598 packet.SetFilePos(6); // vKill;
1599 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1600 if (pid == LLDB_INVALID_PROCESS_ID)
1601 return SendIllFormedResponse(packet,
1602 "vKill failed to parse the process id");
1603
1604 auto it = m_debugged_processes.find(pid);
1605 if (it == m_debugged_processes.end())
1606 return SendErrorResponse(42);
1607
1608 Status error = it->second.process_up->Kill();
1609 if (error.Fail())
1610 return SendErrorResponse(error.ToError());
1611
1612 // OK response is sent when the process dies.
1613 it->second.flags |= DebuggedProcess::Flag::vkilled;
1614 return PacketResult::Success;
1615}
1616
1619 StringExtractorGDBRemote &packet) {
1620 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1621 if (packet.GetU32(0))
1622 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1623 else
1624 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1625 return SendOKResponse();
1626}
1627
1630 StringExtractorGDBRemote &packet) {
1631 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1632 std::string path;
1633 packet.GetHexByteString(path);
1634 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1635 return SendOKResponse();
1636}
1637
1640 StringExtractorGDBRemote &packet) {
1641 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1642 if (working_dir) {
1643 StreamString response;
1644 response.PutStringAsRawHex8(working_dir.GetPath().c_str());
1645 return SendPacketNoLock(response.GetString());
1646 }
1647
1648 return SendErrorResponse(14);
1649}
1650
1657
1664
1667 NativeProcessProtocol &process, const ResumeActionList &actions) {
1669
1670 // In non-stop protocol mode, the process could be running already.
1671 // We do not support resuming threads independently, so just error out.
1672 if (!process.CanResume()) {
1673 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1674 process.GetState());
1675 return SendErrorResponse(0x37);
1676 }
1677
1678 Status error = process.Resume(actions);
1679 if (error.Fail()) {
1680 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1681 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1682 }
1683
1684 LLDB_LOG(log, "process {0} resumed", process.GetID());
1685
1686 return PacketResult::Success;
1687}
1688
1692 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1693
1694 // Ensure we have a native process.
1695 if (!m_continue_process) {
1696 LLDB_LOGF(log,
1697 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1698 "shared pointer",
1699 __FUNCTION__);
1700 return SendErrorResponse(0x36);
1701 }
1702
1703 // Pull out the signal number.
1704 packet.SetFilePos(::strlen("C"));
1705 if (packet.GetBytesLeft() < 1) {
1706 // Shouldn't be using a C without a signal.
1707 return SendIllFormedResponse(packet, "C packet specified without signal.");
1708 }
1709 const uint32_t signo =
1710 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1711 if (signo == std::numeric_limits<uint32_t>::max())
1712 return SendIllFormedResponse(packet, "failed to parse signal number");
1713
1714 // Handle optional continue address.
1715 if (packet.GetBytesLeft() > 0) {
1716 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1717 if (*packet.Peek() == ';')
1718 return SendUnimplementedResponse(packet.GetStringRef().data());
1719 else
1720 return SendIllFormedResponse(
1721 packet, "unexpected content after $C{signal-number}");
1722 }
1723
1724 // In non-stop protocol mode, the process could be running already.
1725 // We do not support resuming threads independently, so just error out.
1726 if (!m_continue_process->CanResume()) {
1727 LLDB_LOG(log, "process cannot be resumed (state={0})",
1728 m_continue_process->GetState());
1729 return SendErrorResponse(0x37);
1730 }
1731
1734 Status error;
1735
1736 // We have two branches: what to do if a continue thread is specified (in
1737 // which case we target sending the signal to that thread), or when we don't
1738 // have a continue thread set (in which case we send a signal to the
1739 // process).
1740
1741 // TODO discuss with Greg Clayton, make sure this makes sense.
1742
1743 lldb::tid_t signal_tid = GetContinueThreadID();
1744 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1745 // The resume action for the continue thread (or all threads if a continue
1746 // thread is not set).
1748 static_cast<int>(signo)};
1749
1750 // Add the action for the continue thread (or all threads when the continue
1751 // thread isn't present).
1752 resume_actions.Append(action);
1753 } else {
1754 // Send the signal to the process since we weren't targeting a specific
1755 // continue thread with the signal.
1756 error = m_continue_process->Signal(signo);
1757 if (error.Fail()) {
1758 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1759 m_continue_process->GetID(), error);
1760
1761 return SendErrorResponse(0x52);
1762 }
1763 }
1764
1765 // NB: this checks CanResume() twice but using a single code path for
1766 // resuming still seems worth it.
1767 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1768 if (resume_res != PacketResult::Success)
1769 return resume_res;
1770
1771 // Don't send an "OK" packet, except in non-stop mode;
1772 // otherwise, the response is the stopped/exited message.
1774}
1775
1779 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1780
1781 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1782
1783 // For now just support all continue.
1784 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1785 if (has_continue_address) {
1786 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1787 packet.Peek());
1788 return SendUnimplementedResponse(packet.GetStringRef().data());
1789 }
1790
1791 // Ensure we have a native process.
1792 if (!m_continue_process) {
1793 LLDB_LOGF(log,
1794 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1795 "shared pointer",
1796 __FUNCTION__);
1797 return SendErrorResponse(0x36);
1798 }
1799
1800 // Build the ResumeActionList
1803
1804 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1805 if (resume_res != PacketResult::Success)
1806 return resume_res;
1807
1809}
1810
1813 StringExtractorGDBRemote &packet) {
1814 StreamString response;
1815 response.Printf("vCont;c;C;s;S;t");
1816
1817 return SendPacketNoLock(response.GetString());
1818}
1819
1821 // We're doing a stop-all if and only if our only action is a "t" for all
1822 // threads.
1823 if (const ResumeAction *default_action =
1825 if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1826 return true;
1827 }
1828
1829 return false;
1830}
1831
1834 StringExtractorGDBRemote &packet) {
1835 Log *log = GetLog(LLDBLog::Process);
1836 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1837 __FUNCTION__);
1838
1839 packet.SetFilePos(::strlen("vCont"));
1840
1841 if (packet.GetBytesLeft() == 0) {
1842 LLDB_LOGF(log,
1843 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1844 "vCont package",
1845 __FUNCTION__);
1846 return SendIllFormedResponse(packet, "Missing action from vCont package");
1847 }
1848
1849 if (::strcmp(packet.Peek(), ";s") == 0) {
1850 // Move past the ';', then do a simple 's'.
1851 packet.SetFilePos(packet.GetFilePos() + 1);
1852 return Handle_s(packet);
1853 }
1854
1855 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1856
1857 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1858 // Skip the semi-colon.
1859 packet.GetChar();
1860
1861 // Build up the thread action.
1862 ResumeAction thread_action;
1863 thread_action.tid = LLDB_INVALID_THREAD_ID;
1864 thread_action.state = eStateInvalid;
1865 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1866
1867 const char action = packet.GetChar();
1868 switch (action) {
1869 case 'C':
1870 thread_action.signal = packet.GetHexMaxU32(false, 0);
1871 if (thread_action.signal == 0)
1872 return SendIllFormedResponse(
1873 packet, "Could not parse signal in vCont packet C action");
1874 [[fallthrough]];
1875
1876 case 'c':
1877 // Continue
1878 thread_action.state = eStateRunning;
1879 break;
1880
1881 case 'S':
1882 thread_action.signal = packet.GetHexMaxU32(false, 0);
1883 if (thread_action.signal == 0)
1884 return SendIllFormedResponse(
1885 packet, "Could not parse signal in vCont packet S action");
1886 [[fallthrough]];
1887
1888 case 's':
1889 // Step
1890 thread_action.state = eStateStepping;
1891 break;
1892
1893 case 't':
1894 // Stop
1895 thread_action.state = eStateSuspended;
1896 break;
1897
1898 default:
1899 return SendIllFormedResponse(packet, "Unsupported vCont action");
1900 break;
1901 }
1902
1903 // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".
1906
1907 // Parse out optional :{thread-id} value.
1908 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1909 // Consume the separator.
1910 packet.GetChar();
1911
1912 auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);
1913 if (!pid_tid)
1914 return SendIllFormedResponse(packet, "Malformed thread-id");
1915
1916 pid = pid_tid->first;
1917 tid = pid_tid->second;
1918 }
1919
1920 if (thread_action.state == eStateSuspended &&
1922 return SendIllFormedResponse(
1923 packet, "'t' action not supported for individual threads");
1924 }
1925
1926 // If we get TID without PID, it's the current process.
1927 if (pid == LLDB_INVALID_PROCESS_ID) {
1928 if (!m_continue_process) {
1929 LLDB_LOG(log, "no process selected via Hc");
1930 return SendErrorResponse(0x36);
1931 }
1932 pid = m_continue_process->GetID();
1933 }
1934
1935 assert(pid != LLDB_INVALID_PROCESS_ID);
1938 thread_action.tid = tid;
1939
1941 if (tid != LLDB_INVALID_THREAD_ID)
1942 return SendIllFormedResponse(
1943 packet, "vCont: p-1 is not valid with a specific tid");
1944 for (auto &process_it : m_debugged_processes)
1945 thread_actions[process_it.first].Append(thread_action);
1946 } else
1947 thread_actions[pid].Append(thread_action);
1948 }
1949
1950 assert(thread_actions.size() >= 1);
1951 if (thread_actions.size() > 1 && !m_non_stop)
1952 return SendIllFormedResponse(
1953 packet,
1954 "Resuming multiple processes is supported in non-stop mode only");
1955
1956 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1957 auto process_it = m_debugged_processes.find(x.first);
1958 if (process_it == m_debugged_processes.end()) {
1959 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1960 x.first);
1961 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1962 }
1963
1964 // There are four possible scenarios here. These are:
1965 // 1. vCont on a stopped process that resumes at least one thread.
1966 // In this case, we call Resume().
1967 // 2. vCont on a stopped process that leaves all threads suspended.
1968 // A no-op.
1969 // 3. vCont on a running process that requests suspending all
1970 // running threads. In this case, we call Interrupt().
1971 // 4. vCont on a running process that requests suspending a subset
1972 // of running threads or resuming a subset of suspended threads.
1973 // Since we do not support full nonstop mode, this is unsupported
1974 // and we return an error.
1975
1976 assert(process_it->second.process_up);
1977 if (ResumeActionListStopsAllThreads(x.second)) {
1978 if (process_it->second.process_up->IsRunning()) {
1979 assert(m_non_stop);
1980
1981 Status error = process_it->second.process_up->Interrupt();
1982 if (error.Fail()) {
1983 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1984 error);
1985 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1986 }
1987
1988 LLDB_LOG(log, "halted process {0}", x.first);
1989
1990 // hack to avoid enabling stdio forwarding after stop
1991 // TODO: remove this when we improve stdio forwarding for nonstop
1992 assert(thread_actions.size() == 1);
1993 return SendOKResponse();
1994 }
1995 } else {
1996 PacketResult resume_res =
1997 ResumeProcess(*process_it->second.process_up, x.second);
1998 if (resume_res != PacketResult::Success)
1999 return resume_res;
2000 }
2001 }
2002
2004}
2005
2007 Log *log = GetLog(LLDBLog::Thread);
2008 LLDB_LOG(log, "setting current thread id to {0}", tid);
2009
2010 m_current_tid = tid;
2012 m_current_process->SetCurrentThreadID(m_current_tid);
2013}
2014
2016 Log *log = GetLog(LLDBLog::Thread);
2017 LLDB_LOG(log, "setting continue thread id to {0}", tid);
2018
2019 m_continue_tid = tid;
2020}
2021
2024 StringExtractorGDBRemote &packet) {
2025 // Handle the $? gdbremote command.
2026
2027 if (m_non_stop) {
2028 // Clear the notification queue first, except for pending exit
2029 // notifications.
2030 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
2031 return x.front() != 'W' && x.front() != 'X';
2032 });
2033
2034 if (m_current_process) {
2035 // Queue stop reply packets for all active threads. Start with
2036 // the current thread (for clients that don't actually support multiple
2037 // stop reasons).
2038 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
2039 if (thread) {
2040 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
2041 if (!stop_reply.Empty())
2042 m_stop_notification_queue.push_back(stop_reply.GetString().str());
2043 }
2044 EnqueueStopReplyPackets(thread ? thread->GetID()
2046 }
2047
2048 // If the notification queue is empty (i.e. everything is running), send OK.
2049 if (m_stop_notification_queue.empty())
2050 return SendOKResponse();
2051
2052 // Send the first item from the new notification queue synchronously.
2054 }
2055
2056 // If no process, indicate error
2057 if (!m_current_process)
2058 return SendErrorResponse(02);
2059
2061 m_current_process->GetState(),
2062 /*force_synchronous=*/true);
2063}
2064
2067 NativeProcessProtocol &process, lldb::StateType process_state,
2068 bool force_synchronous) {
2069 Log *log = GetLog(LLDBLog::Process);
2070
2071 {
2072 std::string out;
2073 {
2074 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
2075 out.swap(m_pending_output_buffer);
2076 }
2077 if (!out.empty())
2078 SendONotification(out.data(), out.size());
2079 }
2080
2082 // Check if we are waiting for any more processes to stop. If we are,
2083 // do not send the OK response yet.
2084 for (const auto &it : m_debugged_processes) {
2085 if (it.second.process_up->IsRunning())
2086 return PacketResult::Success;
2087 }
2088
2089 // If all expected processes were stopped after a QNonStop:0 request,
2090 // send the OK response.
2091 m_disabling_non_stop = false;
2092 return SendOKResponse();
2093 }
2094
2095 switch (process_state) {
2096 case eStateAttaching:
2097 case eStateLaunching:
2098 case eStateRunning:
2099 case eStateStepping:
2100 case eStateDetached:
2101 // NOTE: gdb protocol doc looks like it should return $OK
2102 // when everything is running (i.e. no stopped result).
2103 return PacketResult::Success; // Ignore
2104
2105 case eStateSuspended:
2106 case eStateStopped:
2107 case eStateCrashed: {
2108 lldb::tid_t tid = process.GetCurrentThreadID();
2109 // Make sure we set the current thread so g and p packets return the data
2110 // the gdb will expect.
2111 SetCurrentThreadID(tid);
2112 return SendStopReplyPacketForThread(process, tid, force_synchronous);
2113 }
2114
2115 case eStateInvalid:
2116 case eStateUnloaded:
2117 case eStateExited:
2118 return SendWResponse(&process);
2119
2120 default:
2121 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
2122 process.GetID(), process_state);
2123 break;
2124 }
2125
2126 return SendErrorResponse(0);
2127}
2128
2131 StringExtractorGDBRemote &packet) {
2132 // Fail if we don't have a current process.
2133 if (!m_current_process ||
2135 return SendErrorResponse(68);
2136
2137 // Ensure we have a thread.
2138 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
2139 if (!thread)
2140 return SendErrorResponse(69);
2141
2142 // Get the register context for the first thread.
2143 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2144
2145 // Parse out the register number from the request.
2146 packet.SetFilePos(strlen("qRegisterInfo"));
2147 const uint32_t reg_index =
2148 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2149 if (reg_index == std::numeric_limits<uint32_t>::max())
2150 return SendErrorResponse(69);
2151
2152 // Return the end of registers response if we've iterated one past the end of
2153 // the register set.
2154 if (reg_index >= reg_context.GetUserRegisterCount())
2155 return SendErrorResponse(69);
2156
2157 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2158 if (!reg_info)
2159 return SendErrorResponse(69);
2160
2161 // Build the reginfos response.
2162 StreamGDBRemote response;
2163
2164 response.PutCString("name:");
2165 response.PutCString(reg_info->name);
2166 response.PutChar(';');
2167
2168 if (reg_info->alt_name && reg_info->alt_name[0]) {
2169 response.PutCString("alt-name:");
2170 response.PutCString(reg_info->alt_name);
2171 response.PutChar(';');
2172 }
2173
2174 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2175
2176 if (!reg_context.RegisterOffsetIsDynamic())
2177 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2178
2179 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2180 if (!encoding.empty())
2181 response << "encoding:" << encoding << ';';
2182
2183 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2184 if (!format.empty())
2185 response << "format:" << format << ';';
2186
2187 const char *const register_set_name =
2188 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2189 if (register_set_name)
2190 response << "set:" << register_set_name << ';';
2191
2194 response.Printf("ehframe:%" PRIu32 ";",
2196
2198 response.Printf("dwarf:%" PRIu32 ";",
2200
2201 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2202 if (!kind_generic.empty())
2203 response << "generic:" << kind_generic << ';';
2204
2205 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2206 response.PutCString("container-regs:");
2207 CollectRegNums(reg_info->value_regs, response, true);
2208 response.PutChar(';');
2209 }
2210
2211 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2212 response.PutCString("invalidate-regs:");
2213 CollectRegNums(reg_info->invalidate_regs, response, true);
2214 response.PutChar(';');
2215 }
2216
2217 return SendPacketNoLock(response.GetString());
2218}
2219
2221 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2222 Log *log = GetLog(LLDBLog::Thread);
2223
2224 lldb::pid_t pid = process.GetID();
2225 if (pid == LLDB_INVALID_PROCESS_ID)
2226 return;
2227
2228 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2229 for (NativeThreadProtocol &thread : process.Threads()) {
2230 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2231 response.PutChar(had_any ? ',' : 'm');
2232 AppendThreadIDToResponse(response, pid, thread.GetID());
2233 had_any = true;
2234 }
2235}
2236
2239 StringExtractorGDBRemote &packet) {
2240 assert(m_debugged_processes.size() <= 1 ||
2243
2244 bool had_any = false;
2245 StreamGDBRemote response;
2246
2247 for (auto &pid_ptr : m_debugged_processes)
2248 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2249
2250 if (!had_any)
2251 return SendOKResponse();
2252 return SendPacketNoLock(response.GetString());
2253}
2254
2257 StringExtractorGDBRemote &packet) {
2258 // FIXME for now we return the full thread list in the initial packet and
2259 // always do nothing here.
2260 return SendPacketNoLock("l");
2261}
2262
2265 Log *log = GetLog(LLDBLog::Thread);
2266
2267 // Move past packet name.
2268 packet.SetFilePos(strlen("g"));
2269
2270 // Get the thread to use.
2271 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2272 if (!thread) {
2273 LLDB_LOG(log, "failed, no thread available");
2274 return SendErrorResponse(0x15);
2275 }
2276
2277 // Get the thread's register context.
2278 NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
2279
2280 std::vector<uint8_t> regs_buffer;
2281 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2282 ++reg_num) {
2283 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2284
2285 if (reg_info == nullptr) {
2286 LLDB_LOG(log, "failed to get register info for register index {0}",
2287 reg_num);
2288 return SendErrorResponse(0x15);
2289 }
2290
2291 if (reg_info->value_regs != nullptr)
2292 continue; // skip registers that are contained in other registers
2293
2294 RegisterValue reg_value;
2295 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2296 if (error.Fail()) {
2297 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2298 return SendErrorResponse(0x15);
2299 }
2300
2301 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2302 // Resize the buffer to guarantee it can store the register offsetted
2303 // data.
2304 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2305
2306 // Copy the register offsetted data to the buffer.
2307 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2308 reg_info->byte_size);
2309 }
2310
2311 // Write the response.
2312 StreamGDBRemote response;
2313 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2314
2315 return SendPacketNoLock(response.GetString());
2316}
2317
2320 Log *log = GetLog(LLDBLog::Thread);
2321
2322 // Parse out the register number from the request.
2323 packet.SetFilePos(strlen("p"));
2324 const uint32_t reg_index =
2325 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2326 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2327 LLDB_LOGF(log,
2328 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2329 "parse register number from request \"%s\"",
2330 __FUNCTION__, packet.GetStringRef().data());
2331 return SendErrorResponse(0x15);
2332 }
2333
2334 // Get the thread to use.
2335 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2336 if (!thread) {
2337 LLDB_LOG(log, "failed, no thread available");
2338 return SendErrorResponse(0x15);
2339 }
2340
2341 // Get the thread's register context.
2342 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2343
2344 // Return the end of registers response if we've iterated one past the end of
2345 // the register set.
2346 if (reg_index >= reg_context.GetUserRegisterCount()) {
2347 LLDB_LOGF(log,
2348 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2349 "register %" PRIu32 " beyond register count %" PRIu32,
2350 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2351 return SendErrorResponse(0x15);
2352 }
2353
2354 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2355 if (!reg_info) {
2356 LLDB_LOGF(log,
2357 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2358 "register %" PRIu32 " returned NULL",
2359 __FUNCTION__, reg_index);
2360 return SendErrorResponse(0x15);
2361 }
2362
2363 // Build the reginfos response.
2364 StreamGDBRemote response;
2365
2366 // Retrieve the value
2367 RegisterValue reg_value;
2368 Status error = reg_context.ReadRegister(reg_info, reg_value);
2369 if (error.Fail()) {
2370 LLDB_LOGF(log,
2371 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2372 "requested register %" PRIu32 " (%s) failed: %s",
2373 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2374 return SendErrorResponse(0x15);
2375 }
2376
2377 const uint8_t *const data =
2378 static_cast<const uint8_t *>(reg_value.GetBytes());
2379 if (!data) {
2380 LLDB_LOGF(log,
2381 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2382 "bytes from requested register %" PRIu32,
2383 __FUNCTION__, reg_index);
2384 return SendErrorResponse(0x15);
2385 }
2386
2387 // FIXME flip as needed to get data in big/little endian format for this host.
2388 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2389 response.PutHex8(data[i]);
2390
2391 return SendPacketNoLock(response.GetString());
2392}
2393
2396 Log *log = GetLog(LLDBLog::Thread);
2397
2398 // Ensure there is more content.
2399 if (packet.GetBytesLeft() < 1)
2400 return SendIllFormedResponse(packet, "Empty P packet");
2401
2402 // Parse out the register number from the request.
2403 packet.SetFilePos(strlen("P"));
2404 const uint32_t reg_index =
2405 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2406 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2407 LLDB_LOGF(log,
2408 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2409 "parse register number from request \"%s\"",
2410 __FUNCTION__, packet.GetStringRef().data());
2411 return SendErrorResponse(0x29);
2412 }
2413
2414 // Note debugserver would send an E30 here.
2415 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2416 return SendIllFormedResponse(
2417 packet, "P packet missing '=' char after register number");
2418
2419 // Parse out the value.
2420 size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);
2421
2422 // Get the thread to use.
2423 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2424 if (!thread) {
2425 LLDB_LOGF(log,
2426 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2427 "available (thread index 0)",
2428 __FUNCTION__);
2429 return SendErrorResponse(0x28);
2430 }
2431
2432 // Get the thread's register context.
2433 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2434 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2435 if (!reg_info) {
2436 LLDB_LOGF(log,
2437 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2438 "register %" PRIu32 " returned NULL",
2439 __FUNCTION__, reg_index);
2440 return SendErrorResponse(0x48);
2441 }
2442
2443 // Return the end of registers response if we've iterated one past the end of
2444 // the register set.
2445 if (reg_index >= reg_context.GetUserRegisterCount()) {
2446 LLDB_LOGF(log,
2447 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2448 "register %" PRIu32 " beyond register count %" PRIu32,
2449 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2450 return SendErrorResponse(0x47);
2451 }
2452
2453 if (reg_size != reg_info->byte_size)
2454 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2455
2456 // Build the reginfos response.
2457 StreamGDBRemote response;
2458
2459 RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),
2460 m_current_process->GetArchitecture().GetByteOrder());
2461 Status error = reg_context.WriteRegister(reg_info, reg_value);
2462 if (error.Fail()) {
2463 LLDB_LOGF(log,
2464 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2465 "requested register %" PRIu32 " (%s) failed: %s",
2466 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2467 return SendErrorResponse(0x32);
2468 }
2469
2470 return SendOKResponse();
2471}
2472
2475 Log *log = GetLog(LLDBLog::Thread);
2476
2477 // Parse out which variant of $H is requested.
2478 packet.SetFilePos(strlen("H"));
2479 if (packet.GetBytesLeft() < 1) {
2480 LLDB_LOGF(log,
2481 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2482 "missing {g,c} variant",
2483 __FUNCTION__);
2484 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2485 }
2486
2487 const char h_variant = packet.GetChar();
2488 NativeProcessProtocol *default_process;
2489 switch (h_variant) {
2490 case 'g':
2491 default_process = m_current_process;
2492 break;
2493
2494 case 'c':
2495 default_process = m_continue_process;
2496 break;
2497
2498 default:
2499 LLDB_LOGF(
2500 log,
2501 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2502 __FUNCTION__, h_variant);
2503 return SendIllFormedResponse(packet,
2504 "H variant unsupported, should be c or g");
2505 }
2506
2507 // Parse out the thread number.
2508 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2510 if (!pid_tid)
2511 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
2512
2513 lldb::pid_t pid = pid_tid->first;
2514 lldb::tid_t tid = pid_tid->second;
2515
2517 return SendUnimplementedResponse("Selecting all processes not supported");
2518 if (pid == LLDB_INVALID_PROCESS_ID)
2519 return SendErrorResponse(
2520 llvm::createStringError("no current process and no PID provided"));
2521
2522 // Check the process ID and find respective process instance.
2523 auto new_process_it = m_debugged_processes.find(pid);
2524 if (new_process_it == m_debugged_processes.end())
2525 return SendErrorResponse(
2526 llvm::createStringErrorV("no process with PID {0} debugged", pid));
2527
2528 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2529 // (any thread).
2530 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2531 NativeThreadProtocol *thread =
2532 new_process_it->second.process_up->GetThreadByID(tid);
2533 if (!thread) {
2534 LLDB_LOGF(log,
2535 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2536 " not found",
2537 __FUNCTION__, tid);
2538 return SendErrorResponse(0x15);
2539 }
2540 }
2541
2542 // Now switch the given process and thread type.
2543 switch (h_variant) {
2544 case 'g':
2545 m_current_process = new_process_it->second.process_up.get();
2546 SetCurrentThreadID(tid);
2547 break;
2548
2549 case 'c':
2550 m_continue_process = new_process_it->second.process_up.get();
2552 break;
2553
2554 default:
2555 assert(false && "unsupported $H variant - shouldn't get here");
2556 return SendIllFormedResponse(packet,
2557 "H variant unsupported, should be c or g");
2558 }
2559
2560 return SendOKResponse();
2561}
2562
2565 Log *log = GetLog(LLDBLog::Thread);
2566
2567 // Fail if we don't have a current process.
2568 if (!m_current_process ||
2570 LLDB_LOGF(
2571 log,
2572 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2573 __FUNCTION__);
2574 return SendErrorResponse(0x15);
2575 }
2576
2577 packet.SetFilePos(::strlen("I"));
2578 uint8_t tmp[4096];
2579 for (;;) {
2580 size_t read = packet.GetHexBytesAvail(tmp);
2581 if (read == 0) {
2582 break;
2583 }
2584 // write directly to stdin *this might block if stdin buffer is full*
2585 // TODO: enqueue this block in circular buffer and send window size to
2586 // remote host
2587 Status error;
2588
2589#if defined(_WIN32)
2590 // On Windows the inferior's stdio is owned by NativeProcessWindows (which
2591 // holds the ConPTY). Route stdin through NativeProcessProtocol::WriteStdin
2592 // rather than m_stdio_communication, which is unconnected on Windows.
2593 if (m_current_process->WriteStdin(tmp, read, error) != read || error.Fail())
2594 return SendErrorResponse(0x15);
2595#else
2596 ConnectionStatus status;
2597 m_stdio_communication.WriteAll(tmp, read, status, &error);
2598 if (error.Fail()) {
2599 return SendErrorResponse(0x15);
2600 }
2601#endif
2602 }
2603
2604 return SendOKResponse();
2605}
2606
2609 StringExtractorGDBRemote &packet) {
2611
2612 // Fail if we don't have a current process.
2613 if (!m_current_process ||
2615 LLDB_LOG(log, "failed, no process available");
2616 return SendErrorResponse(0x15);
2617 }
2618
2619 // Interrupt the process.
2620 Status error = m_current_process->Interrupt();
2621 if (error.Fail()) {
2622 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2623 error);
2624 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2625 }
2626
2627 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2628
2629 // No response required from stop all.
2630 return PacketResult::Success;
2631}
2632
2635 StringExtractorGDBRemote &packet) {
2636 Log *log = GetLog(LLDBLog::Process);
2637
2638 if (!m_current_process ||
2640 LLDB_LOGF(
2641 log,
2642 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2643 __FUNCTION__);
2644 return SendErrorResponse(0x15);
2645 }
2646
2647 // Parse out the memory address.
2648 packet.SetFilePos(strlen("m"));
2649 if (packet.GetBytesLeft() < 1)
2650 return SendIllFormedResponse(packet, "Too short m packet");
2651
2652 // Read the address. Punting on validation.
2653 // FIXME replace with Hex U64 read with no default value that fails on failed
2654 // read.
2655 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2656
2657 // Validate comma.
2658 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2659 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2660
2661 // Get # bytes to read.
2662 if (packet.GetBytesLeft() < 1)
2663 return SendIllFormedResponse(packet, "Length missing in m packet");
2664
2665 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2666 if (byte_count == 0) {
2667 LLDB_LOGF(log,
2668 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2669 "zero-length packet",
2670 __FUNCTION__);
2671 return SendOKResponse();
2672 }
2673
2674 // Allocate the response buffer.
2675 std::string buf(byte_count, '\0');
2676 if (buf.empty())
2677 return SendErrorResponse(0x78);
2678
2679 // Retrieve the process memory.
2680 size_t bytes_read = 0;
2681 Status error = m_current_process->ReadMemoryWithoutTrap(
2682 read_addr, &buf[0], byte_count, bytes_read);
2683 LLDB_LOG(
2684 log,
2685 "ReadMemoryWithoutTrap({0}) read {1} of {2} requested bytes (error: {3})",
2686 read_addr, byte_count, bytes_read, error);
2687 if (bytes_read == 0)
2688 return SendErrorResponse(0x08);
2689
2690 StreamGDBRemote response;
2691 packet.SetFilePos(0);
2692 char kind = packet.GetChar('?');
2693 if (kind == 'x')
2694 response.PutEscapedBytes(buf.data(), bytes_read);
2695 else {
2696 assert(kind == 'm');
2697 for (size_t i = 0; i < bytes_read; ++i)
2698 response.PutHex8(buf[i]);
2699 }
2700
2701 return SendPacketNoLock(response.GetString());
2702}
2703
2706 Log *log = GetLog(LLDBLog::Process);
2707
2708 if (!m_current_process ||
2710 LLDB_LOGF(
2711 log,
2712 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2713 __FUNCTION__);
2714 return SendErrorResponse(0x15);
2715 }
2716
2717 // Parse out the memory address.
2718 packet.SetFilePos(strlen("_M"));
2719 if (packet.GetBytesLeft() < 1)
2720 return SendIllFormedResponse(packet, "Too short _M packet");
2721
2722 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2723 if (size == LLDB_INVALID_ADDRESS)
2724 return SendIllFormedResponse(packet, "Address not valid");
2725 if (packet.GetChar() != ',')
2726 return SendIllFormedResponse(packet, "Bad packet");
2727 Permissions perms = {};
2728 while (packet.GetBytesLeft() > 0) {
2729 switch (packet.GetChar()) {
2730 case 'r':
2731 perms |= ePermissionsReadable;
2732 break;
2733 case 'w':
2734 perms |= ePermissionsWritable;
2735 break;
2736 case 'x':
2737 perms |= ePermissionsExecutable;
2738 break;
2739 default:
2740 return SendIllFormedResponse(packet, "Bad permissions");
2741 }
2742 }
2743
2744 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2745 if (!addr)
2746 return SendErrorResponse(addr.takeError());
2747
2748 StreamGDBRemote response;
2749 response.PutHex64(*addr);
2750 return SendPacketNoLock(response.GetString());
2751}
2752
2755 Log *log = GetLog(LLDBLog::Process);
2756
2757 if (!m_current_process ||
2759 LLDB_LOGF(
2760 log,
2761 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2762 __FUNCTION__);
2763 return SendErrorResponse(0x15);
2764 }
2765
2766 // Parse out the memory address.
2767 packet.SetFilePos(strlen("_m"));
2768 if (packet.GetBytesLeft() < 1)
2769 return SendIllFormedResponse(packet, "Too short m packet");
2770
2771 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2772 if (addr == LLDB_INVALID_ADDRESS)
2773 return SendIllFormedResponse(packet, "Address not valid");
2774
2775 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2776 return SendErrorResponse(std::move(Err));
2777
2778 return SendOKResponse();
2779}
2780
2783 Log *log = GetLog(LLDBLog::Process);
2784
2785 if (!m_current_process ||
2787 LLDB_LOGF(
2788 log,
2789 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2790 __FUNCTION__);
2791 return SendErrorResponse(0x15);
2792 }
2793
2794 // Parse out the memory address.
2795 packet.SetFilePos(strlen("M"));
2796 if (packet.GetBytesLeft() < 1)
2797 return SendIllFormedResponse(packet, "Too short M packet");
2798
2799 // Read the address. Punting on validation.
2800 // FIXME replace with Hex U64 read with no default value that fails on failed
2801 // read.
2802 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2803
2804 // Validate comma.
2805 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2806 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2807
2808 // Get # bytes to read.
2809 if (packet.GetBytesLeft() < 1)
2810 return SendIllFormedResponse(packet, "Length missing in M packet");
2811
2812 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2813 if (byte_count == 0) {
2814 LLDB_LOG(log, "nothing to write: zero-length packet");
2815 return PacketResult::Success;
2816 }
2817
2818 // Validate colon.
2819 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2820 return SendIllFormedResponse(
2821 packet, "Comma sep missing in M packet after byte length");
2822
2823 // Allocate the conversion buffer.
2824 std::vector<uint8_t> buf(byte_count, 0);
2825 if (buf.empty())
2826 return SendErrorResponse(0x78);
2827
2828 // Convert the hex memory write contents to bytes.
2829 StreamGDBRemote response;
2830 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2831 if (convert_count != byte_count) {
2832 LLDB_LOG(log,
2833 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2834 "to convert.",
2835 m_current_process->GetID(), write_addr, byte_count, convert_count);
2836 return SendIllFormedResponse(packet, "M content byte length specified did "
2837 "not match hex-encoded content "
2838 "length");
2839 }
2840
2841 // Write the process memory.
2842 size_t bytes_written = 0;
2843 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2844 bytes_written);
2845 if (error.Fail()) {
2846 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2847 m_current_process->GetID(), write_addr, error);
2848 return SendErrorResponse(0x09);
2849 }
2850
2851 if (bytes_written == 0) {
2852 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2853 m_current_process->GetID(), write_addr, byte_count);
2854 return SendErrorResponse(0x09);
2855 }
2856
2857 return SendOKResponse();
2858}
2859
2862 StringExtractorGDBRemote &packet) {
2863 Log *log = GetLog(LLDBLog::Process);
2864
2865 // Currently only the NativeProcessProtocol knows if it can handle a
2866 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2867 // attached to a process. For now we'll assume the client only asks this
2868 // when a process is being debugged.
2869
2870 // Ensure we have a process running; otherwise, we can't figure this out
2871 // since we won't have a NativeProcessProtocol.
2872 if (!m_current_process ||
2874 LLDB_LOGF(
2875 log,
2876 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2877 __FUNCTION__);
2878 return SendErrorResponse(0x15);
2879 }
2880
2881 // Test if we can get any region back when asking for the region around NULL.
2882 MemoryRegionInfo region_info;
2883 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2884 if (error.Fail()) {
2885 // We don't support memory region info collection for this
2886 // NativeProcessProtocol.
2887 return SendUnimplementedResponse("");
2888 }
2889
2890 return SendOKResponse();
2891}
2892
2895 StringExtractorGDBRemote &packet) {
2896 Log *log = GetLog(LLDBLog::Process);
2897
2898 // Ensure we have a process.
2899 if (!m_current_process ||
2901 LLDB_LOGF(
2902 log,
2903 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2904 __FUNCTION__);
2905 return SendErrorResponse(0x15);
2906 }
2907
2908 // Parse out the memory address.
2909 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2910 if (packet.GetBytesLeft() < 1)
2911 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2912
2913 // Read the address. Punting on validation.
2914 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2915
2916 StreamGDBRemote response;
2917
2918 // Get the memory region info for the target address.
2919 MemoryRegionInfo region_info;
2920 const Status error =
2921 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2922 if (error.Fail()) {
2923 // Return the error message.
2924
2925 response.PutCString("error:");
2926 response.PutStringAsRawHex8(error.AsCString());
2927 response.PutChar(';');
2928 } else {
2929 // Range start and size.
2930 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2931 region_info.GetRange().GetRangeBase(),
2932 region_info.GetRange().GetByteSize());
2933
2934 // Permissions.
2935 if (region_info.GetReadable() || region_info.GetWritable() ||
2936 region_info.GetExecutable()) {
2937 // Write permissions info.
2938 response.PutCString("permissions:");
2939
2940 if (region_info.GetReadable())
2941 response.PutChar('r');
2942 if (region_info.GetWritable())
2943 response.PutChar('w');
2944 if (region_info.GetExecutable())
2945 response.PutChar('x');
2946
2947 response.PutChar(';');
2948 }
2949
2950 // Flags
2951 LazyBool memory_tagged = region_info.GetMemoryTagged();
2952 LazyBool is_shadow_stack = region_info.IsShadowStack();
2953
2954 if (memory_tagged != eLazyBoolDontKnow ||
2955 is_shadow_stack != eLazyBoolDontKnow) {
2956 response.PutCString("flags:");
2957 // Space is the separator.
2958 if (memory_tagged == eLazyBoolYes)
2959 response.PutCString("mt ");
2960 if (is_shadow_stack == eLazyBoolYes)
2961 response.PutCString("ss ");
2962
2963 response.PutChar(';');
2964 }
2965
2966 // Name
2967 ConstString name = region_info.GetName();
2968 if (name) {
2969 response.PutCString("name:");
2970 response.PutStringAsRawHex8(name.GetStringRef());
2971 response.PutChar(';');
2972 }
2973
2974 if (std::optional<unsigned> protection_key = region_info.GetProtectionKey())
2975 response.Printf("protection-key:%" PRIu32 ";", *protection_key);
2976
2977 LazyBool is_stack = region_info.IsStackMemory();
2978 if (is_stack != eLazyBoolDontKnow)
2979 response.Printf("type: %s", is_stack ? "stack" : "heap");
2980 }
2981
2982 return SendPacketNoLock(response.GetString());
2983}
2984
2985namespace {
2986struct UseBreakpoint {
2987 bool want_hardware = false;
2988};
2989struct UseWatchpoint {
2990 uint32_t flags;
2991 static constexpr bool want_hardware = true;
2992};
2993struct InvalidStoppoint {};
2994
2995std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint>
2996getBreakpointKind(GDBStoppointType stoppoint_type) {
2997 switch (stoppoint_type) {
2999 return UseBreakpoint{/*want_hardware*/ false};
3001 return UseBreakpoint{/*want_hardware*/ true};
3002 case eWatchpointWrite:
3003 return UseWatchpoint{/*flags*/ 1};
3004 case eWatchpointRead:
3005 return UseWatchpoint{/*flags*/ 2};
3007 return UseWatchpoint{/*flags*/ 3};
3008 case eStoppointInvalid:
3009 return InvalidStoppoint();
3010 }
3011 llvm_unreachable("unhandled GDBStoppointType");
3012}
3013} // namespace
3014
3017 llvm::StringRef packet_str) {
3018 // Ensure we have a process.
3019 if (!m_current_process ||
3021 Log *log = GetLog(LLDBLog::Process);
3022 LLDB_LOG(log, "failed, no process available");
3023 return BreakpointError{0x15};
3024 }
3025
3026 StringExtractorGDBRemote packet(packet_str);
3027
3028 // Parse out software or hardware breakpoint or watchpoint requested.
3029 packet.SetFilePos(strlen("Z"));
3030 if (packet.GetBytesLeft() < 1)
3031 return BreakpointIllFormed{
3032 "Too short Z packet, missing software/hardware specifier"};
3033
3034 const GDBStoppointType stoppoint_type =
3036 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3037 getBreakpointKind(stoppoint_type);
3038 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3039 return BreakpointIllFormed{
3040 "Z packet had invalid software/hardware specifier"};
3041
3042 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3043 return BreakpointIllFormed{
3044 "Malformed Z packet, expecting comma after stoppoint type"};
3045
3046 // Parse out the stoppoint address.
3047 if (packet.GetBytesLeft() < 1)
3048 return BreakpointIllFormed{"Too short Z packet, missing address"};
3049 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3050
3051 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3052 return BreakpointIllFormed{
3053 "Malformed Z packet, expecting comma after address"};
3054
3055 // Parse out the stoppoint size (i.e. size hint for opcode size).
3056 const uint32_t size =
3057 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
3058 if (size == std::numeric_limits<uint32_t>::max())
3059 return BreakpointIllFormed{
3060 "Malformed Z packet, failed to parse size argument"};
3061
3062 // Try to set a breakpoint.
3063 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3064 const Status error =
3065 m_current_process->SetBreakpoint(addr, size, bp_kind->want_hardware);
3066 if (error.Success())
3067 return BreakpointOK();
3069 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
3070 m_current_process->GetID(), error);
3071 return BreakpointError{0x09};
3072 }
3073
3074 // Try to set a watchpoint.
3075 auto wp_kind = std::get<UseWatchpoint>(bp_variant);
3076 const Status error = m_current_process->SetWatchpoint(
3077 addr, size, wp_kind.flags, wp_kind.want_hardware);
3078 if (error.Success())
3079 return BreakpointOK();
3081 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
3082 m_current_process->GetID(), error);
3083 return BreakpointError{0x09};
3084}
3085
3088 llvm::StringRef packet_str) {
3089 // Ensure we have a process.
3090 if (!m_current_process ||
3092 Log *log = GetLog(LLDBLog::Process);
3093 LLDB_LOG(log, "failed, no process available");
3094 return BreakpointError{0x15};
3095 }
3096
3097 StringExtractorGDBRemote packet(packet_str);
3098
3099 // Parse out software or hardware breakpoint or watchpoint requested.
3100 packet.SetFilePos(strlen("z"));
3101 if (packet.GetBytesLeft() < 1)
3102 return BreakpointIllFormed{
3103 "Too short z packet, missing software/hardware specifier"};
3104
3105 const GDBStoppointType stoppoint_type =
3107 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3108 getBreakpointKind(stoppoint_type);
3109 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3110 return BreakpointIllFormed{
3111 "z packet had invalid software/hardware specifier"};
3112
3113 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3114 return BreakpointIllFormed{
3115 "Malformed z packet, expecting comma after stoppoint type"};
3116
3117 // Parse out the stoppoint address.
3118 if (packet.GetBytesLeft() < 1)
3119 return BreakpointIllFormed{"Too short z packet, missing address"};
3120 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3121
3122 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3123 return BreakpointIllFormed{
3124 "Malformed z packet, expecting comma after address"};
3125
3126 /*
3127 // Parse out the stoppoint size (i.e. size hint for opcode size).
3128 const uint32_t size = packet.GetHexMaxU32 (false,
3129 std::numeric_limits<uint32_t>::max ());
3130 if (size == std::numeric_limits<uint32_t>::max ())
3131 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
3132 size argument");
3133 */
3134
3135 // Try to clear the breakpoint.
3136 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3137 const Status error =
3138 m_current_process->RemoveBreakpoint(addr, bp_kind->want_hardware);
3139 if (error.Success())
3140 return BreakpointOK();
3142 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
3143 m_current_process->GetID(), error);
3144 return BreakpointError{0x09};
3145 }
3146 // Try to clear the watchpoint.
3147 const Status error = m_current_process->RemoveWatchpoint(addr);
3148 if (error.Success())
3149 return BreakpointOK();
3151 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3152 m_current_process->GetID(), error);
3153 return BreakpointError{0x09};
3154}
3155
3158 StringExtractorGDBRemote &packet, const BreakpointResult &result) {
3159 return std::visit(
3160 [&](auto &&arg) {
3161 using T = std::decay_t<decltype(arg)>;
3162 static_assert(std::is_same_v<T, BreakpointOK> ||
3163 std::is_same_v<T, BreakpointError> ||
3164 std::is_same_v<T, BreakpointIllFormed>,
3165 "non-exhaustive visitor!");
3166 if constexpr (std::is_same_v<T, BreakpointOK>)
3167 return SendOKResponse();
3168 else if constexpr (std::is_same_v<T, BreakpointError>)
3169 return SendErrorResponse(arg.error_code);
3170 else
3171 return SendIllFormedResponse(packet, arg.message.c_str());
3172 },
3173 result);
3174}
3175
3181
3187
3190 StringExtractorGDBRemote &packet) {
3191 llvm::StringRef packet_str = packet.GetStringRef();
3192 if (!packet_str.consume_front("jMultiBreakpoint:"))
3193 return SendIllFormedResponse(packet,
3194 "Invalid jMultiBreakpoint packet prefix");
3195
3196 llvm::Expected<llvm::json::Value> parsed = llvm::json::parse(packet_str);
3197 if (!parsed) {
3198 llvm::consumeError(parsed.takeError());
3199 return SendIllFormedResponse(packet,
3200 "jMultiBreakpoint did not contain valid JSON");
3201 }
3202 llvm::json::Object *request_dict = parsed->getAsObject();
3203 if (!request_dict)
3204 return SendIllFormedResponse(
3205 packet, "jMultiBreakpoint did not contain a JSON dictionary");
3206
3207 llvm::json::Array *request_array =
3208 request_dict->getArray("breakpoint_requests");
3209 if (!request_array)
3210 return SendIllFormedResponse(
3211 packet,
3212 "jMultiBreakpoint did not contain a valid 'breakpoint_requests' field");
3213
3214 llvm::json::Array reply_array;
3215 for (const llvm::json::Value &value : *request_array) {
3216 std::optional<llvm::StringRef> request = value.getAsString();
3217 if (!request)
3218 return SendIllFormedResponse(packet,
3219 "jMultiBreakpoint had a non-string entry");
3220 BreakpointResult result = request->starts_with("Z")
3221 ? ExecuteSetBreakpoint(*request)
3222 : ExecuteRemoveBreakpoint(*request);
3223 std::visit(
3224 [&](const auto &arg) {
3225 using T = std::decay_t<decltype(arg)>;
3226 static_assert(std::is_same_v<T, BreakpointOK> ||
3227 std::is_same_v<T, BreakpointError> ||
3228 std::is_same_v<T, BreakpointIllFormed>,
3229 "non-exhaustive visitor!");
3230 if constexpr (std::is_same_v<T, BreakpointOK>)
3231 reply_array.push_back("OK");
3232 else if constexpr (std::is_same_v<T, BreakpointError>)
3233 reply_array.push_back(
3234 llvm::formatv("E{0:X-2}", arg.error_code).str());
3235 else
3236 reply_array.push_back("E03");
3237 },
3238 result);
3239 }
3240
3241 llvm::json::Object dict;
3242 dict.try_emplace("results", std::move(reply_array));
3243
3244 StreamString stream;
3245 stream.AsRawOstream() << llvm::json::Value(std::move(dict));
3246 StringRef response_str = stream.GetString();
3247 StreamGDBRemote response;
3248 response.PutEscapedBytes(response_str.data(), response_str.size());
3249 return SendPacketNoLock(response.GetString());
3250}
3251
3255
3256 // Ensure we have a process.
3257 if (!m_continue_process ||
3259 LLDB_LOGF(
3260 log,
3261 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3262 __FUNCTION__);
3263 return SendErrorResponse(0x32);
3264 }
3265
3266 // We first try to use a continue thread id. If any one or any all set, use
3267 // the current thread. Bail out if we don't have a thread id.
3269 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3270 tid = GetCurrentThreadID();
3271 if (tid == LLDB_INVALID_THREAD_ID)
3272 return SendErrorResponse(0x33);
3273
3274 // Double check that we have such a thread.
3275 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3276 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3277 if (!thread)
3278 return SendErrorResponse(0x33);
3279
3280 // Create the step action for the given thread.
3282
3283 // Setup the actions list.
3284 ResumeActionList actions;
3285 actions.Append(action);
3286
3287 // All other threads stop while we're single stepping a thread.
3289
3290 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3291 if (resume_res != PacketResult::Success)
3292 return resume_res;
3293
3294 // No response here, unless in non-stop mode.
3295 // Otherwise, the stop or exit will come from the resulting action.
3297}
3298
3299llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3301 // Ensure we have a thread.
3302 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3303 if (!thread)
3304 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3305 "No thread available");
3306
3308 // Get the register context for the first thread.
3309 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3310
3311 StreamString response;
3312
3313 response.Printf("<?xml version=\"1.0\"?>\n");
3314 response.Printf("<target version=\"1.0\">\n");
3315 response.IndentMore();
3316
3317 response.Indent();
3318 const llvm::StringRef arch_name =
3319 m_current_process->GetArchitecture().GetTriple().getArchName();
3320 // Match gdbserver's expected architecture. We do the reverse when
3321 // decoding the architecture when receiving the target.xml
3322 // in ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess.
3323 const llvm::StringRef new_arch_name = StringSwitch<llvm::StringRef>(arch_name)
3324 .Case("x86_64", "i386:x86-64")
3325 .Case("riscv64", "riscv:rv64")
3326 .Case("riscv32", "riscv:rv32")
3327 .Default(arch_name);
3328 response.Format("<architecture>{}</architecture>\n", new_arch_name);
3329 response.Indent("<feature>\n");
3330
3331 const int registers_count = reg_context.GetUserRegisterCount();
3332 if (registers_count)
3333 response.IndentMore();
3334
3335 std::unordered_set<const RegisterType *> register_types_emitted;
3336 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3337 const RegisterInfo *reg_info =
3338 reg_context.GetRegisterInfoAtIndex(reg_index);
3339
3340 if (!reg_info) {
3341 LLDB_LOGF(log,
3342 "%s failed to get register info for register index %" PRIu32,
3343 "target.xml", reg_index);
3344 continue;
3345 }
3346
3347 if (reg_info->register_type)
3348 reg_info->register_type->ToXML(response, register_types_emitted);
3349
3350 response.Indent();
3351 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3352 "\" regnum=\"%d\" ",
3353 reg_info->name, reg_info->byte_size * 8, reg_index);
3354
3355 if (!reg_context.RegisterOffsetIsDynamic())
3356 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3357
3358 if (reg_info->alt_name && reg_info->alt_name[0])
3359 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3360
3361 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3362 if (!encoding.empty())
3363 response << "encoding=\"" << encoding << "\" ";
3364
3365 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3366 if (!format.empty())
3367 response << "format=\"" << format << "\" ";
3368
3369 if (reg_info->register_type)
3370 response << "type=\"" << reg_info->register_type->GetID() << "\" ";
3371
3372 const char *const register_set_name =
3373 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3374 if (register_set_name)
3375 response << "group=\"" << register_set_name << "\" ";
3376
3379 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3381
3382 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3384 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3386
3387 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3388 if (!kind_generic.empty())
3389 response << "generic=\"" << kind_generic << "\" ";
3390
3391 if (reg_info->value_regs &&
3392 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3393 response.PutCString("value_regnums=\"");
3394 CollectRegNums(reg_info->value_regs, response, false);
3395 response.Printf("\" ");
3396 }
3397
3398 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3399 response.PutCString("invalidate_regnums=\"");
3400 CollectRegNums(reg_info->invalidate_regs, response, false);
3401 response.Printf("\" ");
3402 }
3403
3404 response.Printf("/>\n");
3405 }
3406
3407 if (registers_count)
3408 response.IndentLess();
3409
3410 response.Indent("</feature>\n");
3411 response.IndentLess();
3412 response.Indent("</target>\n");
3413 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3414}
3415
3416llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3418 llvm::StringRef annex) {
3419 // Make sure we have a valid process.
3420 if (!m_current_process ||
3422 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3423 "No process available");
3424 }
3425
3426 if (object == "auxv") {
3427 // Grab the auxv data.
3428 auto buffer_or_error = m_current_process->GetAuxvData();
3429 if (!buffer_or_error)
3430 return llvm::errorCodeToError(buffer_or_error.getError());
3431 return std::move(*buffer_or_error);
3432 }
3433
3434 if (object == "siginfo") {
3435 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3436 if (!thread)
3437 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3438 "no current thread");
3439
3440 auto buffer_or_error = thread->GetSiginfo();
3441 if (!buffer_or_error)
3442 return buffer_or_error.takeError();
3443 return std::move(*buffer_or_error);
3444 }
3445
3446 if (object == "libraries-svr4") {
3447 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3448 if (!library_list)
3449 return library_list.takeError();
3450
3451 StreamString response;
3452 response.Printf("<library-list-svr4 version=\"1.0\">");
3453 for (auto const &library : *library_list) {
3454 response.Printf("<library name=\"%s\" ",
3455 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3456 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3457 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3458 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3459 }
3460 response.Printf("</library-list-svr4>");
3461 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3462 }
3463
3464 if (object == "libraries") {
3465 auto library_list = m_current_process->GetLoadedLibraries();
3466 if (!library_list)
3467 return library_list.takeError();
3468
3469 StreamString response;
3470 response.Printf("<library-list>");
3471 for (auto const &library : *library_list) {
3472 response.Printf("<library name=\"%s\">",
3473 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3474 response.Printf("<section address=\"0x%" PRIx64 "\"/>",
3475 library.base_addr);
3476 response.Printf("</library>");
3477 }
3478 response.Printf("</library-list>");
3479 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3480 }
3481
3482 if (object == "features" && annex == "target.xml")
3483 return BuildTargetXml();
3484
3485 return llvm::make_error<UnimplementedError>();
3486}
3487
3490 StringExtractorGDBRemote &packet) {
3491 SmallVector<StringRef, 5> fields;
3492 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3493 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3494 if (fields.size() != 5)
3495 return SendIllFormedResponse(packet, "malformed qXfer packet");
3496 StringRef &xfer_object = fields[1];
3497 StringRef &xfer_action = fields[2];
3498 StringRef &xfer_annex = fields[3];
3499 StringExtractor offset_data(fields[4]);
3500 if (xfer_action != "read")
3501 return SendUnimplementedResponse("qXfer action not supported");
3502 // Parse offset.
3503 const uint64_t xfer_offset =
3504 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3505 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3506 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3507 // Parse out comma.
3508 if (offset_data.GetChar() != ',')
3509 return SendIllFormedResponse(packet,
3510 "qXfer packet missing comma after offset");
3511 // Parse out the length.
3512 const uint64_t xfer_length =
3513 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3514 if (xfer_length == std::numeric_limits<uint64_t>::max())
3515 return SendIllFormedResponse(packet, "qXfer packet missing length");
3516
3517 // Get a previously constructed buffer if it exists or create it now.
3518 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3519 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3520 if (buffer_it == m_xfer_buffer_map.end()) {
3521 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3522 if (!buffer_up)
3523 return SendErrorResponse(buffer_up.takeError());
3524 buffer_it = m_xfer_buffer_map
3525 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3526 .first;
3527 }
3528
3529 // Send back the response
3530 StreamGDBRemote response;
3531 bool done_with_buffer = false;
3532 llvm::StringRef buffer = buffer_it->second->getBuffer();
3533 if (xfer_offset >= buffer.size()) {
3534 // We have nothing left to send. Mark the buffer as complete.
3535 response.PutChar('l');
3536 done_with_buffer = true;
3537 } else {
3538 // Figure out how many bytes are available starting at the given offset.
3539 buffer = buffer.drop_front(xfer_offset);
3540 // Mark the response type according to whether we're reading the remainder
3541 // of the data.
3542 if (xfer_length >= buffer.size()) {
3543 // There will be nothing left to read after this
3544 response.PutChar('l');
3545 done_with_buffer = true;
3546 } else {
3547 // There will still be bytes to read after this request.
3548 response.PutChar('m');
3549 buffer = buffer.take_front(xfer_length);
3550 }
3551 // Now write the data in encoded binary form.
3552 response.PutEscapedBytes(buffer.data(), buffer.size());
3553 }
3554
3555 if (done_with_buffer)
3556 m_xfer_buffer_map.erase(buffer_it);
3557
3558 return SendPacketNoLock(response.GetString());
3559}
3560
3563 StringExtractorGDBRemote &packet) {
3564 Log *log = GetLog(LLDBLog::Thread);
3565
3566 // Move past packet name.
3567 packet.SetFilePos(strlen("QSaveRegisterState"));
3568
3569 // Get the thread to use.
3570 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3571 if (!thread) {
3573 return SendIllFormedResponse(
3574 packet, "No thread specified in QSaveRegisterState packet");
3575 else
3576 return SendIllFormedResponse(packet,
3577 "No thread was is set with the Hg packet");
3578 }
3579
3580 // Grab the register context for the thread.
3581 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3582
3583 // Save registers to a buffer.
3584 WritableDataBufferSP register_data_sp;
3585 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3586 if (error.Fail()) {
3587 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3588 m_current_process->GetID(), error);
3589 return SendErrorResponse(0x75);
3590 }
3591
3592 // Allocate a new save id.
3593 const uint32_t save_id = GetNextSavedRegistersID();
3594 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3595 "GetNextRegisterSaveID() returned an existing register save id");
3596
3597 // Save the register data buffer under the save id.
3598 {
3599 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3600 m_saved_registers_map[save_id] = register_data_sp;
3601 }
3602
3603 // Write the response.
3604 StreamGDBRemote response;
3605 response.Printf("%" PRIu32, save_id);
3606 return SendPacketNoLock(response.GetString());
3607}
3608
3611 StringExtractorGDBRemote &packet) {
3612 Log *log = GetLog(LLDBLog::Thread);
3613
3614 // Parse out save id.
3615 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3616 if (packet.GetBytesLeft() < 1)
3617 return SendIllFormedResponse(
3618 packet, "QRestoreRegisterState packet missing register save id");
3619
3620 const uint32_t save_id = packet.GetU32(0);
3621 if (save_id == 0) {
3622 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3623 "expecting decimal uint32_t");
3624 return SendErrorResponse(0x76);
3625 }
3626
3627 // Get the thread to use.
3628 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3629 if (!thread) {
3631 return SendIllFormedResponse(
3632 packet, "No thread specified in QRestoreRegisterState packet");
3633 else
3634 return SendIllFormedResponse(packet,
3635 "No thread was is set with the Hg packet");
3636 }
3637
3638 // Grab the register context for the thread.
3639 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3640
3641 // Retrieve register state buffer, then remove from the list.
3642 DataBufferSP register_data_sp;
3643 {
3644 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3645
3646 // Find the register set buffer for the given save id.
3647 auto it = m_saved_registers_map.find(save_id);
3648 if (it == m_saved_registers_map.end()) {
3649 LLDB_LOG(log,
3650 "pid {0} does not have a register set save buffer for id {1}",
3651 m_current_process->GetID(), save_id);
3652 return SendErrorResponse(0x77);
3653 }
3654 register_data_sp = it->second;
3655
3656 // Remove it from the map.
3657 m_saved_registers_map.erase(it);
3658 }
3659
3660 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3661 if (error.Fail()) {
3662 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3663 m_current_process->GetID(), error);
3664 return SendErrorResponse(0x77);
3665 }
3666
3667 return SendOKResponse();
3668}
3669
3672 StringExtractorGDBRemote &packet) {
3673 Log *log = GetLog(LLDBLog::Process);
3674
3675 // Consume the ';' after vAttach.
3676 packet.SetFilePos(strlen("vAttach"));
3677 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3678 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3679
3680 // Grab the PID to which we will attach (assume hex encoding).
3681 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3682 if (pid == LLDB_INVALID_PROCESS_ID)
3683 return SendIllFormedResponse(packet,
3684 "vAttach failed to parse the process id");
3685
3686 // Attempt to attach.
3687 LLDB_LOGF(log,
3688 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3689 "pid %" PRIu64,
3690 __FUNCTION__, pid);
3691
3693
3694 if (error.Fail()) {
3695 LLDB_LOGF(log,
3696 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3697 "pid %" PRIu64 ": %s\n",
3698 __FUNCTION__, pid, error.AsCString());
3699 return SendErrorResponse(error);
3700 }
3701
3702 // Notify we attached by sending a stop packet.
3703 assert(m_current_process);
3705 m_current_process->GetState(),
3706 /*force_synchronous=*/false);
3707}
3708
3711 StringExtractorGDBRemote &packet) {
3712 Log *log = GetLog(LLDBLog::Process);
3713
3714 // Consume the ';' after the identifier.
3715 packet.SetFilePos(strlen("vAttachWait"));
3716
3717 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3718 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3719
3720 // Allocate the buffer for the process name from vAttachWait.
3721 std::string process_name;
3722 if (!packet.GetHexByteString(process_name))
3723 return SendIllFormedResponse(packet,
3724 "vAttachWait failed to parse process name");
3725
3726 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3727
3728 Status error = AttachWaitProcess(process_name, false);
3729 if (error.Fail()) {
3730 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3731 error);
3732 return SendErrorResponse(error);
3733 }
3734
3735 // Notify we attached by sending a stop packet.
3736 assert(m_current_process);
3738 m_current_process->GetState(),
3739 /*force_synchronous=*/false);
3740}
3741
3747
3750 StringExtractorGDBRemote &packet) {
3751 Log *log = GetLog(LLDBLog::Process);
3752
3753 // Consume the ';' after the identifier.
3754 packet.SetFilePos(strlen("vAttachOrWait"));
3755
3756 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3757 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3758
3759 // Allocate the buffer for the process name from vAttachWait.
3760 std::string process_name;
3761 if (!packet.GetHexByteString(process_name))
3762 return SendIllFormedResponse(packet,
3763 "vAttachOrWait failed to parse process name");
3764
3765 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3766
3767 Status error = AttachWaitProcess(process_name, true);
3768 if (error.Fail()) {
3769 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3770 error);
3771 return SendErrorResponse(error);
3772 }
3773
3774 // Notify we attached by sending a stop packet.
3775 assert(m_current_process);
3777 m_current_process->GetState(),
3778 /*force_synchronous=*/false);
3779}
3780
3783 StringExtractorGDBRemote &packet) {
3784 Log *log = GetLog(LLDBLog::Process);
3785
3786 llvm::StringRef s = packet.GetStringRef();
3787 if (!s.consume_front("vRun;"))
3788 return SendErrorResponse(8);
3789
3790 llvm::SmallVector<llvm::StringRef, 16> argv;
3791 s.split(argv, ';');
3792
3793 for (llvm::StringRef hex_arg : argv) {
3794 StringExtractor arg_ext{hex_arg};
3795 std::string arg;
3796 arg_ext.GetHexByteString(arg);
3797 m_process_launch_info.GetArguments().AppendArgument(arg);
3798 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3799 arg.c_str());
3800 }
3801
3802 if (argv.empty())
3803 return SendErrorResponse(Status::FromErrorString("No arguments"));
3804 m_process_launch_info.GetExecutableFile().SetFile(
3805 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3807 if (m_process_launch_error.Fail())
3809 assert(m_current_process);
3811 m_current_process->GetState(),
3812 /*force_synchronous=*/true);
3813}
3814
3817 Log *log = GetLog(LLDBLog::Process);
3818 if (!m_non_stop)
3820
3822
3823 // Consume the ';' after D.
3824 packet.SetFilePos(1);
3825 if (packet.GetBytesLeft()) {
3826 if (packet.GetChar() != ';')
3827 return SendIllFormedResponse(packet, "D missing expected ';'");
3828
3829 // Grab the PID from which we will detach (assume hex encoding).
3830 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3831 if (pid == LLDB_INVALID_PROCESS_ID)
3832 return SendIllFormedResponse(packet, "D failed to parse the process id");
3833 }
3834
3835 // Detach forked children if their PID was specified *or* no PID was requested
3836 // (i.e. detach-all packet).
3837 llvm::Error detach_error = llvm::Error::success();
3838 bool detached = false;
3839 for (auto it = m_debugged_processes.begin();
3840 it != m_debugged_processes.end();) {
3841 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3842 LLDB_LOGF(log,
3843 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3844 __FUNCTION__, it->first);
3845 if (llvm::Error e = it->second.process_up->Detach().ToError())
3846 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3847 else {
3848 if (it->second.process_up.get() == m_current_process)
3849 m_current_process = nullptr;
3850 if (it->second.process_up.get() == m_continue_process)
3851 m_continue_process = nullptr;
3852 it = m_debugged_processes.erase(it);
3853 detached = true;
3854 continue;
3855 }
3856 }
3857 ++it;
3858 }
3859
3860 if (detach_error)
3861 return SendErrorResponse(std::move(detach_error));
3862 if (!detached)
3863 return SendErrorResponse(
3864 Status::FromErrorStringWithFormat("PID %" PRIu64 " not traced", pid));
3865 return SendOKResponse();
3866}
3867
3870 StringExtractorGDBRemote &packet) {
3871 Log *log = GetLog(LLDBLog::Thread);
3872
3873 if (!m_current_process ||
3875 return SendErrorResponse(50);
3876
3877 packet.SetFilePos(strlen("qThreadStopInfo"));
3878 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3879 if (tid == LLDB_INVALID_THREAD_ID) {
3880 LLDB_LOGF(log,
3881 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3882 "parse thread id from request \"%s\"",
3883 __FUNCTION__, packet.GetStringRef().data());
3884 return SendErrorResponse(0x15);
3885 }
3887 /*force_synchronous=*/true);
3888}
3889
3894
3895 // Ensure we have a debugged process.
3896 if (!m_current_process ||
3898 return SendErrorResponse(50);
3899 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3900
3901 StreamString response;
3902 const bool threads_with_valid_stop_info_only = false;
3903 llvm::Expected<json::Value> threads_info =
3904 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3905 if (!threads_info) {
3906 LLDB_LOG_ERROR(log, threads_info.takeError(),
3907 "failed to prepare a packet for pid {1}: {0}",
3908 m_current_process->GetID());
3909 return SendErrorResponse(52);
3910 }
3911
3912 response.AsRawOstream() << *threads_info;
3913 StreamGDBRemote escaped_response;
3914 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3915 return SendPacketNoLock(escaped_response.GetString());
3916}
3917
3920 StringExtractorGDBRemote &packet) {
3921 // Fail if we don't have a current process.
3922 if (!m_current_process ||
3924 return SendErrorResponse(68);
3925
3926 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3927 if (packet.GetBytesLeft() == 0)
3928 return SendOKResponse();
3929 if (packet.GetChar() != ':')
3930 return SendErrorResponse(67);
3931
3932 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3933
3934 StreamGDBRemote response;
3935 if (hw_debug_cap == std::nullopt)
3936 response.Printf("num:0;");
3937 else
3938 response.Printf("num:%d;", hw_debug_cap->second);
3939
3940 return SendPacketNoLock(response.GetString());
3941}
3942
3945 StringExtractorGDBRemote &packet) {
3946 // Fail if we don't have a current process.
3947 if (!m_current_process ||
3949 return SendErrorResponse(67);
3950
3951 packet.SetFilePos(strlen("qFileLoadAddress:"));
3952 if (packet.GetBytesLeft() == 0)
3953 return SendErrorResponse(68);
3954
3955 std::string file_name;
3956 packet.GetHexByteString(file_name);
3957
3958 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3959 Status error =
3960 m_current_process->GetFileLoadAddress(file_name, file_load_address);
3961 if (error.Fail())
3962 return SendErrorResponse(69);
3963
3964 if (file_load_address == LLDB_INVALID_ADDRESS)
3965 return SendErrorResponse(1); // File not loaded
3966
3967 StreamGDBRemote response;
3968 response.PutHex64(file_load_address);
3969 return SendPacketNoLock(response.GetString());
3970}
3971
3974 StringExtractorGDBRemote &packet) {
3975 std::vector<int> signals;
3976 packet.SetFilePos(strlen("QPassSignals:"));
3977
3978 // Read sequence of hex signal numbers divided by a semicolon and optionally
3979 // spaces.
3980 while (packet.GetBytesLeft() > 0) {
3981 int signal = packet.GetS32(-1, 16);
3982 if (signal < 0)
3983 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3984 signals.push_back(signal);
3985
3986 packet.SkipSpaces();
3987 char separator = packet.GetChar();
3988 if (separator == '\0')
3989 break; // End of string
3990 if (separator != ';')
3991 return SendIllFormedResponse(packet, "Invalid separator,"
3992 " expected semicolon.");
3993 }
3994
3995 // Fail if we don't have a current process.
3996 if (!m_current_process)
3997 return SendErrorResponse(68);
3998
3999 Status error = m_current_process->IgnoreSignals(signals);
4000 if (error.Fail())
4001 return SendErrorResponse(69);
4002
4003 return SendOKResponse();
4004}
4005
4008 StringExtractorGDBRemote &packet) {
4009 Log *log = GetLog(LLDBLog::Process);
4010
4011 // Ensure we have a process.
4012 if (!m_current_process ||
4014 LLDB_LOGF(
4015 log,
4016 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4017 __FUNCTION__);
4018 return SendErrorResponse(1);
4019 }
4020
4021 // We are expecting
4022 // qMemTags:<hex address>,<hex length>:<hex type>
4023
4024 // Address
4025 packet.SetFilePos(strlen("qMemTags:"));
4026 const char *current_char = packet.Peek();
4027 if (!current_char || *current_char == ',')
4028 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
4029 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4030
4031 // Length
4032 char previous_char = packet.GetChar();
4033 current_char = packet.Peek();
4034 // If we don't have a separator or the length field is empty
4035 if (previous_char != ',' || (current_char && *current_char == ':'))
4036 return SendIllFormedResponse(packet,
4037 "Invalid addr,length pair in qMemTags packet");
4038
4039 if (packet.GetBytesLeft() < 1)
4040 return SendIllFormedResponse(
4041 packet, "Too short qMemtags: packet (looking for length)");
4042 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4043
4044 // Type
4045 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
4046 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4047 return SendIllFormedResponse(packet, invalid_type_err);
4048
4049 // Type is a signed integer but packed into the packet as its raw bytes.
4050 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
4051 const char *first_type_char = packet.Peek();
4052 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4053 return SendIllFormedResponse(packet, invalid_type_err);
4054
4055 // Extract type as unsigned then cast to signed.
4056 // Using a uint64_t here so that we have some value outside of the 32 bit
4057 // range to use as the invalid return value.
4058 uint64_t raw_type =
4059 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4060
4061 if ( // Make sure the cast below would be valid
4062 raw_type > std::numeric_limits<uint32_t>::max() ||
4063 // To catch inputs like "123aardvark" that will parse but clearly aren't
4064 // valid in this case.
4065 packet.GetBytesLeft()) {
4066 return SendIllFormedResponse(packet, invalid_type_err);
4067 }
4068
4069 // First narrow to 32 bits otherwise the copy into type would take
4070 // the wrong 4 bytes on big endian.
4071 uint32_t raw_type_32 = raw_type;
4072 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4073
4074 StreamGDBRemote response;
4075 std::vector<uint8_t> tags;
4076 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
4077 if (error.Fail())
4078 return SendErrorResponse(1);
4079
4080 // This m is here in case we want to support multi part replies in the future.
4081 // In the same manner as qfThreadInfo/qsThreadInfo.
4082 response.PutChar('m');
4083 response.PutBytesAsRawHex8(tags.data(), tags.size());
4084 return SendPacketNoLock(response.GetString());
4085}
4086
4089 StringExtractorGDBRemote &packet) {
4090 Log *log = GetLog(LLDBLog::Process);
4091
4092 // Ensure we have a process.
4093 if (!m_current_process ||
4095 LLDB_LOGF(
4096 log,
4097 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4098 __FUNCTION__);
4099 return SendErrorResponse(1);
4100 }
4101
4102 // We are expecting
4103 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
4104
4105 // Address
4106 packet.SetFilePos(strlen("QMemTags:"));
4107 const char *current_char = packet.Peek();
4108 if (!current_char || *current_char == ',')
4109 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
4110 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4111
4112 // Length
4113 char previous_char = packet.GetChar();
4114 current_char = packet.Peek();
4115 // If we don't have a separator or the length field is empty
4116 if (previous_char != ',' || (current_char && *current_char == ':'))
4117 return SendIllFormedResponse(packet,
4118 "Invalid addr,length pair in QMemTags packet");
4119
4120 if (packet.GetBytesLeft() < 1)
4121 return SendIllFormedResponse(
4122 packet, "Too short QMemtags: packet (looking for length)");
4123 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4124
4125 // Type
4126 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
4127 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4128 return SendIllFormedResponse(packet, invalid_type_err);
4129
4130 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
4131 const char *first_type_char = packet.Peek();
4132 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4133 return SendIllFormedResponse(packet, invalid_type_err);
4134
4135 // The type is a signed integer but is in the packet as its raw bytes.
4136 // So parse first as unsigned then cast to signed later.
4137 // We extract to 64 bit, even though we only expect 32, so that we've
4138 // got some invalid value we can check for.
4139 uint64_t raw_type =
4140 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4141 if (raw_type > std::numeric_limits<uint32_t>::max())
4142 return SendIllFormedResponse(packet, invalid_type_err);
4143
4144 // First narrow to 32 bits. Otherwise the copy below would get the wrong
4145 // 4 bytes on big endian.
4146 uint32_t raw_type_32 = raw_type;
4147 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4148
4149 // Tag data
4150 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4151 return SendIllFormedResponse(packet,
4152 "Missing tag data in QMemTags: packet");
4153
4154 // Must be 2 chars per byte
4155 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
4156 if (packet.GetBytesLeft() % 2)
4157 return SendIllFormedResponse(packet, invalid_data_err);
4158
4159 // This is bytes here and is unpacked into target specific tags later
4160 // We cannot assume that number of bytes == length here because the server
4161 // can repeat tags to fill a given range.
4162 std::vector<uint8_t> tag_data;
4163 // Zero length writes will not have any tag data
4164 // (but we pass them on because it will still check that tagging is enabled)
4165 if (packet.GetBytesLeft()) {
4166 size_t byte_count = packet.GetBytesLeft() / 2;
4167 tag_data.resize(byte_count);
4168 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
4169 if (converted_bytes != byte_count) {
4170 return SendIllFormedResponse(packet, invalid_data_err);
4171 }
4172 }
4173
4174 Status status =
4175 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
4176 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
4177}
4178
4181 StringExtractorGDBRemote &packet) {
4182 // Fail if we don't have a current process.
4183 if (!m_current_process ||
4185 return SendErrorResponse(Status::FromErrorString("Process not running."));
4186
4187 std::string path_hint;
4188
4189 StringRef packet_str{packet.GetStringRef()};
4190 assert(packet_str.starts_with("qSaveCore"));
4191 if (packet_str.consume_front("qSaveCore;")) {
4192 for (auto x : llvm::split(packet_str, ';')) {
4193 if (x.consume_front("path-hint:"))
4194 StringExtractor(x).GetHexByteString(path_hint);
4195 else
4196 return SendErrorResponse(
4197 Status::FromErrorString("Unsupported qSaveCore option"));
4198 }
4199 }
4200
4201 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
4202 if (!ret)
4203 return SendErrorResponse(ret.takeError());
4204
4205 StreamString response;
4206 response.PutCString("core-path:");
4207 response.PutStringAsRawHex8(ret.get());
4208 return SendPacketNoLock(response.GetString());
4209}
4210
4213 StringExtractorGDBRemote &packet) {
4214 Log *log = GetLog(LLDBLog::Process);
4215
4216 StringRef packet_str{packet.GetStringRef()};
4217 assert(packet_str.starts_with("QNonStop:"));
4218 packet_str.consume_front("QNonStop:");
4219 if (packet_str == "0") {
4220 if (m_non_stop)
4222 for (auto &process_it : m_debugged_processes) {
4223 if (process_it.second.process_up->IsRunning()) {
4224 assert(m_non_stop);
4225 Status error = process_it.second.process_up->Interrupt();
4226 if (error.Fail()) {
4227 LLDB_LOG(log,
4228 "while disabling nonstop, failed to halt process {0}: {1}",
4229 process_it.first, error);
4230 return SendErrorResponse(0x41);
4231 }
4232 // we must not send stop reasons after QNonStop
4233 m_disabling_non_stop = true;
4234 }
4235 }
4238 m_non_stop = false;
4239 // If we are stopping anything, defer sending the OK response until we're
4240 // done.
4242 return PacketResult::Success;
4243 } else if (packet_str == "1") {
4244 if (!m_non_stop)
4246 m_non_stop = true;
4247 } else
4248 return SendErrorResponse(
4249 Status::FromErrorString("Invalid QNonStop packet"));
4250 return SendOKResponse();
4251}
4252
4255 std::deque<std::string> &queue) {
4256 // Per the protocol, the first message put into the queue is sent
4257 // immediately. However, it remains the queue until the client ACKs it --
4258 // then we pop it and send the next message. The process repeats until
4259 // the last message in the queue is ACK-ed, in which case the packet sends
4260 // an OK response.
4261 if (queue.empty())
4262 return SendErrorResponse(
4263 Status::FromErrorString("No pending notification to ack"));
4264 queue.pop_front();
4265 if (!queue.empty())
4266 return SendPacketNoLock(queue.front());
4267 return SendOKResponse();
4268}
4269
4275
4278 StringExtractorGDBRemote &packet) {
4280 // If this was the last notification and all the processes exited,
4281 // terminate the server.
4282 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4283 m_exit_now = true;
4284 m_mainloop.RequestTermination();
4285 }
4286 return ret;
4287}
4288
4291 StringExtractorGDBRemote &packet) {
4292 if (!m_non_stop)
4293 return SendErrorResponse(
4294 Status::FromErrorString("vCtrl is only valid in non-stop mode"));
4295
4296 PacketResult interrupt_res = Handle_interrupt(packet);
4297 // If interrupting the process failed, pass the result through.
4298 if (interrupt_res != PacketResult::Success)
4299 return interrupt_res;
4300 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4301 return SendOKResponse();
4302}
4303
4306 packet.SetFilePos(strlen("T"));
4307 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4309 if (!pid_tid)
4310 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
4311
4312 lldb::pid_t pid = pid_tid->first;
4313 lldb::tid_t tid = pid_tid->second;
4314
4315 // Technically, this would also be caught by the PID check but let's be more
4316 // explicit about the error.
4317 if (pid == LLDB_INVALID_PROCESS_ID)
4318 return SendErrorResponse(
4319 llvm::createStringError("no current process and no PID provided"));
4320
4321 // Check the process ID and find respective process instance.
4322 auto new_process_it = m_debugged_processes.find(pid);
4323 if (new_process_it == m_debugged_processes.end())
4324 return SendErrorResponse(1);
4325
4326 // Check the thread ID
4327 if (!new_process_it->second.process_up->GetThreadByID(tid))
4328 return SendErrorResponse(2);
4329
4330 return SendOKResponse();
4331}
4332
4334 Log *log = GetLog(LLDBLog::Process);
4335
4336 // Tell the stdio connection to shut down.
4337 if (m_stdio_communication.IsConnected()) {
4338 auto connection = m_stdio_communication.GetConnection();
4339 if (connection) {
4340 Status error;
4341 connection->Disconnect(&error);
4342
4343 if (error.Success()) {
4344 LLDB_LOGF(log,
4345 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4346 "terminal stdio - SUCCESS",
4347 __FUNCTION__);
4348 } else {
4349 LLDB_LOGF(log,
4350 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4351 "terminal stdio - FAIL: %s",
4352 __FUNCTION__, error.AsCString());
4353 }
4354 }
4355 }
4356}
4357
4359 StringExtractorGDBRemote &packet) {
4360 // We have no thread if we don't have a process.
4361 if (!m_current_process ||
4363 return nullptr;
4364
4365 // If the client hasn't asked for thread suffix support, there will not be a
4366 // thread suffix. Use the current thread in that case.
4368 const lldb::tid_t current_tid = GetCurrentThreadID();
4369 if (current_tid == LLDB_INVALID_THREAD_ID)
4370 return nullptr;
4371 else if (current_tid == 0) {
4372 // Pick a thread.
4373 return m_current_process->GetThreadAtIndex(0);
4374 } else
4375 return m_current_process->GetThreadByID(current_tid);
4376 }
4377
4378 Log *log = GetLog(LLDBLog::Thread);
4379
4380 // Parse out the ';'.
4381 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4382 LLDB_LOGF(log,
4383 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4384 "error: expected ';' prior to start of thread suffix: packet "
4385 "contents = '%s'",
4386 __FUNCTION__, packet.GetStringRef().data());
4387 return nullptr;
4388 }
4389
4390 if (!packet.GetBytesLeft())
4391 return nullptr;
4392
4393 // Parse out thread: portion.
4394 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4395 LLDB_LOGF(log,
4396 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4397 "error: expected 'thread:' but not found, packet contents = "
4398 "'%s'",
4399 __FUNCTION__, packet.GetStringRef().data());
4400 return nullptr;
4401 }
4402 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4403 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4404 if (tid != 0)
4405 return m_current_process->GetThreadByID(tid);
4406
4407 return nullptr;
4408}
4409
4412 // Use whatever the debug process says is the current thread id since the
4413 // protocol either didn't specify or specified we want any/all threads
4414 // marked as the current thread.
4415 if (!m_current_process)
4417 return m_current_process->GetCurrentThreadID();
4418 }
4419 // Use the specific current thread id set by the gdb remote protocol.
4420 return m_current_tid;
4421}
4422
4424 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4426}
4427
4429 Log *log = GetLog(LLDBLog::Process);
4430
4431 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4432 m_xfer_buffer_map.clear();
4433}
4434
4437 const ArchSpec &arch) {
4438 if (m_current_process) {
4439 FileSpec file_spec;
4441 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4442 .Success()) {
4443 if (FileSystem::Instance().Exists(file_spec))
4444 return file_spec;
4445 }
4446 }
4447
4449}
4450
4452 llvm::StringRef value) {
4453 std::string result;
4454 for (const char &c : value) {
4455 switch (c) {
4456 case '\'':
4457 result += "&apos;";
4458 break;
4459 case '"':
4460 result += "&quot;";
4461 break;
4462 case '<':
4463 result += "&lt;";
4464 break;
4465 case '>':
4466 result += "&gt;";
4467 break;
4468 default:
4469 result += c;
4470 break;
4471 }
4472 }
4473 return result;
4474}
4475
4477 const llvm::ArrayRef<llvm::StringRef> client_features) {
4478 std::vector<std::string> ret =
4480 ret.insert(ret.end(), {
4481 "QThreadSuffixSupported+",
4482 "QListThreadsInStopReply+",
4483 "qXfer:features:read+",
4484 "QNonStop+",
4485 "jMultiBreakpoint+",
4486 });
4487
4488 // report server-only features
4489 using Extension = NativeProcessProtocol::Extension;
4490 Extension plugin_features = m_process_manager.GetSupportedExtensions();
4491 if (bool(plugin_features & Extension::pass_signals))
4492 ret.push_back("QPassSignals+");
4493 if (bool(plugin_features & Extension::auxv))
4494 ret.push_back("qXfer:auxv:read+");
4495 if (bool(plugin_features & Extension::libraries_svr4))
4496 ret.push_back("qXfer:libraries-svr4:read+");
4497 if (bool(plugin_features & Extension::libraries))
4498 ret.push_back("qXfer:libraries:read+");
4499 if (bool(plugin_features & Extension::siginfo_read))
4500 ret.push_back("qXfer:siginfo:read+");
4501 if (bool(plugin_features & Extension::memory_tagging))
4502 ret.push_back("memory-tagging+");
4503 if (bool(plugin_features & Extension::savecore))
4504 ret.push_back("qSaveCore+");
4505 if (!m_accelerator_plugins.empty())
4506 ret.push_back("accelerator-plugins+");
4507
4508 // check for client features
4510 for (llvm::StringRef x : client_features)
4512 llvm::StringSwitch<Extension>(x)
4513 .Case("multiprocess+", Extension::multiprocess)
4514 .Case("fork-events+", Extension::fork)
4515 .Case("vfork-events+", Extension::vfork)
4516 .Case("qXfer:libraries:read+", Extension::libraries)
4517 .Case("qXfer:libraries-svr4:read+", Extension::libraries_svr4)
4518 .Default({});
4519
4520 // We consume lldb's swbreak/hwbreak feature, but it doesn't change the
4521 // behaviour of lldb-server. We always adjust the program counter for targets
4522 // like x86
4523
4524 m_extensions_supported &= plugin_features;
4525
4526 // fork & vfork require multiprocess
4527 if (!bool(m_extensions_supported & Extension::multiprocess))
4528 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4529
4530 // report only if actually supported
4531 if (bool(m_extensions_supported & Extension::multiprocess))
4532 ret.push_back("multiprocess+");
4533 if (bool(m_extensions_supported & Extension::fork))
4534 ret.push_back("fork-events+");
4535 if (bool(m_extensions_supported & Extension::vfork))
4536 ret.push_back("vfork-events+");
4537
4538 for (auto &x : m_debugged_processes)
4539 SetEnabledExtensions(*x.second.process_up);
4540 return ret;
4541}
4542
4544 NativeProcessProtocol &process) {
4546 assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));
4547 process.SetEnabledExtensions(flags);
4548}
4549
4557
4559 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4560 if (bool(m_extensions_supported &
4562 response.Format("p{0:x-}.", pid);
4563 response.Format("{0:x-}", tid);
4564}
4565
4566std::string
4568 bool reverse_connect) {
4569 // Try parsing the argument as URL.
4570 if (std::optional<URI> url = URI::Parse(url_arg)) {
4571 if (reverse_connect)
4572 return url_arg.str();
4573
4574 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4575 // If the scheme doesn't match any, pass it through to support using CFD
4576 // schemes directly.
4577 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4578 .Case("tcp", "listen")
4579 .Case("unix", "unix-accept")
4580 .Case("unix-abstract", "unix-abstract-accept")
4581 .Default(url->scheme.str());
4582 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4583 return new_url;
4584 }
4585
4586 std::string host_port = url_arg.str();
4587 // If host_and_port starts with ':', default the host to be "localhost" and
4588 // expect the remainder to be the port.
4589 if (url_arg.starts_with(":"))
4590 host_port.insert(0, "localhost");
4591
4592 // Try parsing the (preprocessed) argument as host:port pair.
4593 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4594 return (reverse_connect ? "connect://" : "listen://") + host_port;
4595
4596 // If none of the above applied, interpret the argument as UNIX socket path.
4597 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4598 url_arg.str();
4599}
4600
4602 std::unique_ptr<LLDBServerAcceleratorPlugin> plugin_up) {
4603 m_accelerator_plugins.emplace_back(std::move(plugin_up));
4604}
4605
4609 std::vector<AcceleratorActions> accelerator_actions;
4610 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4612 if (auto actions = plugin_up->GetInitializeActions())
4613 accelerator_actions.push_back(std::move(*actions));
4614 }
4615 StreamGDBRemote response;
4616 response.PutAsJSONArray(accelerator_actions, /*hex_ascii=*/false);
4617 return SendPacketNoLock(response.GetString());
4618}
4619
4622 StringExtractorGDBRemote &packet) {
4623 packet.ConsumeFront("jAcceleratorPluginBreakpointHit:");
4624 llvm::Expected<AcceleratorBreakpointHitArgs> args =
4625 llvm::json::parse<AcceleratorBreakpointHitArgs>(
4626 packet.Peek(), "AcceleratorBreakpointHitArgs");
4627 if (!args)
4628 return SendErrorResponse(args.takeError());
4629
4630 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4632 if (plugin_up->GetPluginName() == args->plugin_name) {
4633 llvm::Expected<AcceleratorBreakpointHitResponse> bp_response =
4634 plugin_up->BreakpointWasHit(*args);
4635 if (!bp_response)
4636 return SendErrorResponse(bp_response.takeError());
4637
4638 StreamGDBRemote response;
4639 response.PutAsJSON(*bp_response, /*hex_ascii=*/false);
4640 return SendPacketNoLock(response.GetString());
4641 }
4642 }
4643 return SendErrorResponse(
4644 Status::FromErrorString("unknown accelerator plugin name"));
4645}
static const size_t reg_size
static llvm::raw_ostream & error(Stream &strm)
static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo &reg_info)
static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo &reg_info)
static void WriteRegisterValueInHexFixedWidth(StreamString &response, NativeRegisterContext &reg_ctx, const RegisterInfo &reg_info, const RegisterValue *reg_value_p, lldb::ByteOrder byte_order)
static void AppendHexValue(StreamString &response, const uint8_t *buf, uint32_t buf_size, bool swap)
static std::optional< json::Object > GetRegistersAsJSON(NativeThreadProtocol &thread)
static const char * GetStopReasonString(StopReason stop_reason)
static void CollectRegNums(const uint32_t *reg_num, StreamString &response, bool usehex)
static bool ResumeActionListStopsAllThreads(ResumeActionList &actions)
static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo &reg_info)
static llvm::Expected< json::Array > GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
void swap(lldb_private::NonNullSharedPtr< T > &lhs, lldb_private::NonNullSharedPtr< T > &rhs)
Specialized swap function for NonNullSharedPtr to enable argument-dependent lookup (ADL) and efficien...
static constexpr lldb::tid_t AllThreads
static constexpr lldb::pid_t AllProcesses
std::optional< std::pair< lldb::pid_t, lldb::tid_t > > GetPidTid(lldb::pid_t default_pid)
void SetFilePos(uint32_t idx)
bool ConsumeFront(const llvm::StringRef &str)
uint32_t GetHexMaxU32(bool little_endian, uint32_t fail_value)
uint64_t GetHexMaxU64(bool little_endian, uint64_t fail_value)
uint64_t GetU64(uint64_t fail_value, int base=0)
size_t GetHexBytesAvail(llvm::MutableArrayRef< uint8_t > dest)
size_t GetHexByteString(std::string &str)
char GetChar(char fail_value='\0')
const char * Peek()
int32_t GetS32(int32_t fail_value, int base=0)
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
uint64_t GetFilePos() const
llvm::StringRef GetStringRef() const
uint32_t GetU32(uint32_t fail_value, int base=0)
An architecture specification class.
Definition ArchSpec.h:32
virtual void SetConnection(std::unique_ptr< Connection > connection)
Sets the connection that it to be used by this class.
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:211
static uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
virtual void RequestTermination()
std::optional< unsigned > GetProtectionKey() const
virtual std::optional< WaitStatus > GetExitStatus()
virtual void SetEnabledExtensions(Extension flags)
Method called in order to propagate the bitmap of protocol extensions supported by the client.
NativeThreadProtocol * GetThreadByID(lldb::tid_t tid)
virtual Status Resume(const ResumeActionList &resume_actions)=0
Extension
Extension flag constants, returned by Manager::GetSupportedExtensions() and passed to SetEnabledExten...
uint32_t ConvertRegisterKindToRegisterNumber(uint32_t kind, uint32_t num) const
virtual uint32_t GetUserRegisterCount() const =0
virtual const RegisterInfo * GetRegisterInfoAtIndex(uint32_t reg) const =0
const char * GetRegisterSetNameForRegisterAtIndex(uint32_t reg_index) const
virtual Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp)=0
virtual Status ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
virtual Status ReadAllRegisterValues(lldb::WritableDataBufferSP &data_sp)=0
virtual std::vector< uint32_t > GetExpeditedRegisters(ExpeditedRegs expType) const
virtual Status WriteRegister(const RegisterInfo *reg_info, const RegisterValue &reg_value)=0
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
void SetNameMatchType(NameMatch name_match_type)
ProcessInstanceInfo & GetProcessInfo()
void ToXML(Stream &strm, std::unordered_set< const RegisterType * > &previously_emitted, const RegisterType *user=nullptr) const
Output XML that describes this type, to be inserted into a target XML file.
const std::string & GetID() const
const void * GetBytes() const
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition Debug.h:74
void Append(const ResumeAction &action)
Definition Debug.h:52
bool SetDefaultThreadActionIfNeeded(lldb::StateType action, int signal)
Definition Debug.h:96
static llvm::Expected< HostAndPort > DecodeHostAndPort(llvm::StringRef host_and_port)
Definition Socket.cpp:299
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
int PutAsJSON(const T &obj, bool hex_ascii)
Definition GDBRemote.h:50
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:31
int PutAsJSONArray(const std::vector< T > &array, bool hex_ascii)
Definition GDBRemote.h:60
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t size_t PutHex8(uint8_t uvalue)
Append an uint8_t value in the hexadecimal format to the stream.
Definition Stream.cpp:269
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:418
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:307
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:291
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
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:391
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
virtual FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch)
void RegisterMemberFunctionHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketResult(T::*handler)(StringExtractorGDBRemote &packet))
static void CreateProcessInfoResponse_DebugServerStyle(const ProcessInstanceInfo &proc_info, StreamString &response)
virtual std::vector< std::string > HandleFeatures(llvm::ArrayRef< llvm::StringRef > client_features)
void AddProcessThreads(StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any)
llvm::StringMap< std::unique_ptr< llvm::MemoryBuffer > > m_xfer_buffer_map
PacketResult SendStopReasonForState(NativeProcessProtocol &process, lldb::StateType process_state, bool force_synchronous)
std::vector< std::unique_ptr< lldb_server::LLDBServerAcceleratorPlugin > > m_accelerator_plugins
GDBRemoteCommunication::PacketResult SendStructuredDataPacket(const llvm::json::Value &value)
std::variant< BreakpointOK, BreakpointIllFormed, BreakpointError > BreakpointResult
BreakpointResult ExecuteRemoveBreakpoint(llvm::StringRef packet_str)
Core logic for a z (remove breakpoint/watchpoint) request.
FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch) override
void NewProcessOutput(NativeProcessProtocol *process, llvm::StringRef data) override
Forward a chunk of inferior stdout/stderr produced by the platform's own reader.
void NewSubprocess(NativeProcessProtocol *parent_process, std::unique_ptr< NativeProcessProtocol > child_process) override
NativeThreadProtocol * GetThreadFromSuffix(StringExtractorGDBRemote &packet)
PacketResult SendBreakpointResponse(StringExtractorGDBRemote &packet, const BreakpointResult &result)
Convert a BreakpointResult into a PacketResult, sending the appropriate response.
BreakpointResult ExecuteSetBreakpoint(llvm::StringRef packet_str)
Core logic for a Z (set breakpoint/watchpoint) request.
Status LaunchProcess() override
Launch a process with the current launch settings.
void FlushPendingProcessOutput()
Drain m_pending_output_buffer and emit a $O packet if the debuggee is currently in a running state.
Status AttachWaitProcess(llvm::StringRef process_name, bool include_existing)
Wait to attach to a process with a given name.
PacketResult ResumeProcess(NativeProcessProtocol &process, const ResumeActionList &actions)
void InstallPlugin(std::unique_ptr< lldb_server::LLDBServerAcceleratorPlugin > plugin_up)
GDBRemoteCommunicationServerLLGS(MainLoop &mainloop, NativeProcessProtocol::Manager &process_manager)
PacketResult SendStopReplyPacketForThread(NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous)
void AppendThreadIDToResponse(Stream &response, lldb::pid_t pid, lldb::tid_t tid)
std::vector< std::string > HandleFeatures(const llvm::ArrayRef< llvm::StringRef > client_features) override
void ProcessStateChanged(NativeProcessProtocol *process, lldb::StateType state) override
llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > ReadXferObject(llvm::StringRef object, llvm::StringRef annex)
llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > BuildTargetXml()
void RegisterPacketHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketHandler handler)
PacketResult SendIllFormedResponse(const StringExtractorGDBRemote &packet, const char *error_message)
PacketResult GetPacketAndSendResponse(Timeout< std::micro > timeout, Status &error, bool &interrupt, bool &quit)
PacketResult SendJSONResponse(const llvm::json::Value &value)
Serialize and send a JSON object response.
PacketResult SendNotificationPacketNoLock(llvm::StringRef notify_type, std::deque< std::string > &queue, llvm::StringRef payload)
#define LLDB_REGNUM_GENERIC_RA
#define LLDB_REGNUM_GENERIC_ARG8
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_THREAD_ID
#define LLDB_REGNUM_GENERIC_ARG6
#define LLDB_REGNUM_GENERIC_SP
#define LLDB_REGNUM_GENERIC_ARG4
#define LLDB_REGNUM_GENERIC_ARG3
#define LLDB_REGNUM_GENERIC_ARG1
#define LLDB_REGNUM_GENERIC_ARG7
#define LLDB_REGNUM_GENERIC_FLAGS
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_REGNUM
#define LLDB_REGNUM_GENERIC_TP
#define LLDB_INVALID_PROCESS_ID
#define LLDB_REGNUM_GENERIC_ARG2
#define LLDB_REGNUM_GENERIC_PC
#define LLDB_REGNUM_GENERIC_FP
#define LLDB_REGNUM_GENERIC_ARG5
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
std::string LLGSArgToURL(llvm::StringRef url_arg, bool reverse_connect)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition State.cpp:68
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
MainLoopPosix MainLoop
Definition MainLoop.h:20
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
std::shared_ptr< lldb_private::IOObject > IOObjectSP
ConnectionStatus
Connection Status Types.
@ eConnectionStatusError
Check GetError() for details.
@ eConnectionStatusInterrupted
Interrupted read.
@ eConnectionStatusTimedOut
Request timed out.
@ eConnectionStatusEndOfFile
End-of-file encountered.
@ eConnectionStatusSuccess
Success.
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
@ eConnectionStatusNoConnection
No connection.
@ eFormatCString
NULL terminated C strings.
@ eFormatCharArray
Print characters with no single quotes, used for character arrays that can contain non printable char...
@ eFormatInstruction
Disassemble an opcode.
@ eFormatVectorOfChar
@ eFormatVectorOfUInt64
@ eFormatVoid
Do not print this.
@ eFormatVectorOfFloat16
@ eFormatVectorOfSInt64
@ eFormatComplex
Floating point complex type.
@ eFormatHexFloat
ISO C99 hex float string.
@ eFormatBytesWithASCII
@ eFormatOSType
OS character codes encoded into an integer 'PICT' 'text' etc...
@ eFormatAddressInfo
Describe what an address points to (func + offset with file/line, symbol + offset,...
@ eFormatVectorOfUInt128
@ eFormatVectorOfUInt8
@ eFormatVectorOfFloat32
@ eFormatVectorOfSInt32
@ eFormatVectorOfSInt8
@ eFormatVectorOfUInt16
@ eFormatHexUppercase
@ eFormatVectorOfFloat64
@ eFormatCharPrintable
Only printable characters, '.' if not printable.
@ eFormatComplexInteger
Integer complex type.
@ eFormatVectorOfSInt16
@ eFormatFloat128
Disambiguate between 128-bit long double (which uses eFormatFloat) and __float128 (which uses eFormat...
@ eFormatVectorOfUInt32
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
@ eEncodingIEEE754
float
@ eEncodingVector
vector registers
@ eEncodingUint
unsigned integer
@ eEncodingSint
signed integer
uint64_t pid_t
Definition lldb-types.h:84
ByteOrder
Byte ordering definitions.
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
StopReason
Thread stop reasons.
@ eStopReasonInstrumentation
@ eStopReasonPlanComplete
@ eStopReasonHistoryBoundary
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonInterrupt
Thread requested interrupt.
@ eStopReasonProcessorTrace
@ eStopReasonThreadExiting
@ eStopReasonException
@ eStopReasonWatchpoint
uint64_t tid_t
Definition lldb-types.h:85
@ eRegisterKindGeneric
insn ptr reg, stack ptr reg, etc not specific to any particular target
@ eRegisterKindDWARF
the register numbers seen DWARF
@ eRegisterKindEHFrame
the register numbers seen in eh_frame
Terminal window dimensions to use when the launcher creates a pseudo-terminal for the inferior's stdi...
BaseType GetRangeBase() const
Definition RangeMap.h:45
SizeType GetByteSize() const
Definition RangeMap.h:87
Every register is described in detail including its name, alternate name (optional),...
lldb::Encoding encoding
Encoding of the register bits.
const char * alt_name
Alternate name of this register, can be NULL.
uint32_t * value_regs
List of registers (terminated with LLDB_INVALID_REGNUM).
uint32_t byte_offset
The byte offset in the register context data where this register's value is found.
uint32_t byte_size
Size in bytes of the register.
uint32_t kinds[lldb::kNumRegisterKinds]
Holds all of the various register numbers for all register kinds.
const RegisterType * register_type
If not nullptr, a type defined by XML descriptions.
const char * name
Name of this register, can't be NULL.
lldb::Format format
Default display format.
uint32_t * invalidate_regs
List of registers (terminated with LLDB_INVALID_REGNUM).
lldb::StateType state
Definition Debug.h:23
lldb::addr_t data[8]
Definition Debug.h:139
struct lldb_private::ThreadStopInfo::@116236113001137253323017204263037302160273237376::@034237007264067231263360140073224264215170222231 exception
lldb::StopReason reason
Definition Debug.h:132
struct lldb_private::ThreadStopInfo::@116236113001137253323017204263037302160273237376::@075376350020015165106375110034031012204332263127 fork
union lldb_private::ThreadStopInfo::@116236113001137253323017204263037302160273237376 details
static std::optional< URI > Parse(llvm::StringRef uri)
Definition UriParser.cpp:28