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 else
2192 response << "set:general;";
2193
2196 response.Printf("ehframe:%" PRIu32 ";",
2198
2200 response.Printf("dwarf:%" PRIu32 ";",
2202
2203 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2204 if (!kind_generic.empty())
2205 response << "generic:" << kind_generic << ';';
2206
2207 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2208 response.PutCString("container-regs:");
2209 CollectRegNums(reg_info->value_regs, response, true);
2210 response.PutChar(';');
2211 }
2212
2213 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2214 response.PutCString("invalidate-regs:");
2215 CollectRegNums(reg_info->invalidate_regs, response, true);
2216 response.PutChar(';');
2217 }
2218
2219 return SendPacketNoLock(response.GetString());
2220}
2221
2223 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2224 Log *log = GetLog(LLDBLog::Thread);
2225
2226 lldb::pid_t pid = process.GetID();
2227 if (pid == LLDB_INVALID_PROCESS_ID)
2228 return;
2229
2230 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2231 for (NativeThreadProtocol &thread : process.Threads()) {
2232 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2233 response.PutChar(had_any ? ',' : 'm');
2234 AppendThreadIDToResponse(response, pid, thread.GetID());
2235 had_any = true;
2236 }
2237}
2238
2241 StringExtractorGDBRemote &packet) {
2242 assert(m_debugged_processes.size() <= 1 ||
2245
2246 bool had_any = false;
2247 StreamGDBRemote response;
2248
2249 for (auto &pid_ptr : m_debugged_processes)
2250 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2251
2252 if (!had_any)
2253 return SendOKResponse();
2254 return SendPacketNoLock(response.GetString());
2255}
2256
2259 StringExtractorGDBRemote &packet) {
2260 // FIXME for now we return the full thread list in the initial packet and
2261 // always do nothing here.
2262 return SendPacketNoLock("l");
2263}
2264
2267 Log *log = GetLog(LLDBLog::Thread);
2268
2269 // Move past packet name.
2270 packet.SetFilePos(strlen("g"));
2271
2272 // Get the thread to use.
2273 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2274 if (!thread) {
2275 LLDB_LOG(log, "failed, no thread available");
2276 return SendErrorResponse(0x15);
2277 }
2278
2279 // Get the thread's register context.
2280 NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
2281
2282 std::vector<uint8_t> regs_buffer;
2283 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2284 ++reg_num) {
2285 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2286
2287 if (reg_info == nullptr) {
2288 LLDB_LOG(log, "failed to get register info for register index {0}",
2289 reg_num);
2290 return SendErrorResponse(0x15);
2291 }
2292
2293 if (reg_info->value_regs != nullptr)
2294 continue; // skip registers that are contained in other registers
2295
2296 RegisterValue reg_value;
2297 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2298 if (error.Fail()) {
2299 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2300 return SendErrorResponse(0x15);
2301 }
2302
2303 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2304 // Resize the buffer to guarantee it can store the register offsetted
2305 // data.
2306 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2307
2308 // Copy the register offsetted data to the buffer.
2309 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2310 reg_info->byte_size);
2311 }
2312
2313 // Write the response.
2314 StreamGDBRemote response;
2315 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2316
2317 return SendPacketNoLock(response.GetString());
2318}
2319
2322 Log *log = GetLog(LLDBLog::Thread);
2323
2324 // Parse out the register number from the request.
2325 packet.SetFilePos(strlen("p"));
2326 const uint32_t reg_index =
2327 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2328 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2329 LLDB_LOGF(log,
2330 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2331 "parse register number from request \"%s\"",
2332 __FUNCTION__, packet.GetStringRef().data());
2333 return SendErrorResponse(0x15);
2334 }
2335
2336 // Get the thread to use.
2337 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2338 if (!thread) {
2339 LLDB_LOG(log, "failed, no thread available");
2340 return SendErrorResponse(0x15);
2341 }
2342
2343 // Get the thread's register context.
2344 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2345
2346 // Return the end of registers response if we've iterated one past the end of
2347 // the register set.
2348 if (reg_index >= reg_context.GetUserRegisterCount()) {
2349 LLDB_LOGF(log,
2350 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2351 "register %" PRIu32 " beyond register count %" PRIu32,
2352 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2353 return SendErrorResponse(0x15);
2354 }
2355
2356 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2357 if (!reg_info) {
2358 LLDB_LOGF(log,
2359 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2360 "register %" PRIu32 " returned NULL",
2361 __FUNCTION__, reg_index);
2362 return SendErrorResponse(0x15);
2363 }
2364
2365 // Build the reginfos response.
2366 StreamGDBRemote response;
2367
2368 // Retrieve the value
2369 RegisterValue reg_value;
2370 Status error = reg_context.ReadRegister(reg_info, reg_value);
2371 if (error.Fail()) {
2372 LLDB_LOGF(log,
2373 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2374 "requested register %" PRIu32 " (%s) failed: %s",
2375 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2376 return SendErrorResponse(0x15);
2377 }
2378
2379 const uint8_t *const data =
2380 static_cast<const uint8_t *>(reg_value.GetBytes());
2381 if (!data) {
2382 LLDB_LOGF(log,
2383 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2384 "bytes from requested register %" PRIu32,
2385 __FUNCTION__, reg_index);
2386 return SendErrorResponse(0x15);
2387 }
2388
2389 // FIXME flip as needed to get data in big/little endian format for this host.
2390 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2391 response.PutHex8(data[i]);
2392
2393 return SendPacketNoLock(response.GetString());
2394}
2395
2398 Log *log = GetLog(LLDBLog::Thread);
2399
2400 // Ensure there is more content.
2401 if (packet.GetBytesLeft() < 1)
2402 return SendIllFormedResponse(packet, "Empty P packet");
2403
2404 // Parse out the register number from the request.
2405 packet.SetFilePos(strlen("P"));
2406 const uint32_t reg_index =
2407 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2408 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2409 LLDB_LOGF(log,
2410 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2411 "parse register number from request \"%s\"",
2412 __FUNCTION__, packet.GetStringRef().data());
2413 return SendErrorResponse(0x29);
2414 }
2415
2416 // Note debugserver would send an E30 here.
2417 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2418 return SendIllFormedResponse(
2419 packet, "P packet missing '=' char after register number");
2420
2421 // Parse out the value.
2422 size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);
2423
2424 // Get the thread to use.
2425 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2426 if (!thread) {
2427 LLDB_LOGF(log,
2428 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2429 "available (thread index 0)",
2430 __FUNCTION__);
2431 return SendErrorResponse(0x28);
2432 }
2433
2434 // Get the thread's register context.
2435 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2436 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2437 if (!reg_info) {
2438 LLDB_LOGF(log,
2439 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2440 "register %" PRIu32 " returned NULL",
2441 __FUNCTION__, reg_index);
2442 return SendErrorResponse(0x48);
2443 }
2444
2445 // Return the end of registers response if we've iterated one past the end of
2446 // the register set.
2447 if (reg_index >= reg_context.GetUserRegisterCount()) {
2448 LLDB_LOGF(log,
2449 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2450 "register %" PRIu32 " beyond register count %" PRIu32,
2451 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2452 return SendErrorResponse(0x47);
2453 }
2454
2455 if (reg_size != reg_info->byte_size)
2456 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2457
2458 // Build the reginfos response.
2459 StreamGDBRemote response;
2460
2461 RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),
2462 m_current_process->GetArchitecture().GetByteOrder());
2463 Status error = reg_context.WriteRegister(reg_info, reg_value);
2464 if (error.Fail()) {
2465 LLDB_LOGF(log,
2466 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2467 "requested register %" PRIu32 " (%s) failed: %s",
2468 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2469 return SendErrorResponse(0x32);
2470 }
2471
2472 return SendOKResponse();
2473}
2474
2477 Log *log = GetLog(LLDBLog::Thread);
2478
2479 // Parse out which variant of $H is requested.
2480 packet.SetFilePos(strlen("H"));
2481 if (packet.GetBytesLeft() < 1) {
2482 LLDB_LOGF(log,
2483 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2484 "missing {g,c} variant",
2485 __FUNCTION__);
2486 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2487 }
2488
2489 const char h_variant = packet.GetChar();
2490 NativeProcessProtocol *default_process;
2491 switch (h_variant) {
2492 case 'g':
2493 default_process = m_current_process;
2494 break;
2495
2496 case 'c':
2497 default_process = m_continue_process;
2498 break;
2499
2500 default:
2501 LLDB_LOGF(
2502 log,
2503 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2504 __FUNCTION__, h_variant);
2505 return SendIllFormedResponse(packet,
2506 "H variant unsupported, should be c or g");
2507 }
2508
2509 // Parse out the thread number.
2510 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2512 if (!pid_tid)
2513 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
2514
2515 lldb::pid_t pid = pid_tid->first;
2516 lldb::tid_t tid = pid_tid->second;
2517
2519 return SendUnimplementedResponse("Selecting all processes not supported");
2520 if (pid == LLDB_INVALID_PROCESS_ID)
2521 return SendErrorResponse(
2522 llvm::createStringError("no current process and no PID provided"));
2523
2524 // Check the process ID and find respective process instance.
2525 auto new_process_it = m_debugged_processes.find(pid);
2526 if (new_process_it == m_debugged_processes.end())
2527 return SendErrorResponse(
2528 llvm::createStringErrorV("no process with PID {0} debugged", pid));
2529
2530 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2531 // (any thread).
2532 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2533 NativeThreadProtocol *thread =
2534 new_process_it->second.process_up->GetThreadByID(tid);
2535 if (!thread) {
2536 LLDB_LOGF(log,
2537 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2538 " not found",
2539 __FUNCTION__, tid);
2540 return SendErrorResponse(0x15);
2541 }
2542 }
2543
2544 // Now switch the given process and thread type.
2545 switch (h_variant) {
2546 case 'g':
2547 m_current_process = new_process_it->second.process_up.get();
2548 SetCurrentThreadID(tid);
2549 break;
2550
2551 case 'c':
2552 m_continue_process = new_process_it->second.process_up.get();
2554 break;
2555
2556 default:
2557 assert(false && "unsupported $H variant - shouldn't get here");
2558 return SendIllFormedResponse(packet,
2559 "H variant unsupported, should be c or g");
2560 }
2561
2562 return SendOKResponse();
2563}
2564
2567 Log *log = GetLog(LLDBLog::Thread);
2568
2569 // Fail if we don't have a current process.
2570 if (!m_current_process ||
2572 LLDB_LOGF(
2573 log,
2574 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2575 __FUNCTION__);
2576 return SendErrorResponse(0x15);
2577 }
2578
2579 packet.SetFilePos(::strlen("I"));
2580 uint8_t tmp[4096];
2581 for (;;) {
2582 size_t read = packet.GetHexBytesAvail(tmp);
2583 if (read == 0) {
2584 break;
2585 }
2586 // write directly to stdin *this might block if stdin buffer is full*
2587 // TODO: enqueue this block in circular buffer and send window size to
2588 // remote host
2589 Status error;
2590
2591#if defined(_WIN32)
2592 // On Windows the inferior's stdio is owned by NativeProcessWindows (which
2593 // holds the ConPTY). Route stdin through NativeProcessProtocol::WriteStdin
2594 // rather than m_stdio_communication, which is unconnected on Windows.
2595 if (m_current_process->WriteStdin(tmp, read, error) != read || error.Fail())
2596 return SendErrorResponse(0x15);
2597#else
2598 ConnectionStatus status;
2599 m_stdio_communication.WriteAll(tmp, read, status, &error);
2600 if (error.Fail()) {
2601 return SendErrorResponse(0x15);
2602 }
2603#endif
2604 }
2605
2606 return SendOKResponse();
2607}
2608
2611 StringExtractorGDBRemote &packet) {
2613
2614 // Fail if we don't have a current process.
2615 if (!m_current_process ||
2617 LLDB_LOG(log, "failed, no process available");
2618 return SendErrorResponse(0x15);
2619 }
2620
2621 // Interrupt the process.
2622 Status error = m_current_process->Interrupt();
2623 if (error.Fail()) {
2624 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2625 error);
2626 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2627 }
2628
2629 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2630
2631 // No response required from stop all.
2632 return PacketResult::Success;
2633}
2634
2637 StringExtractorGDBRemote &packet) {
2638 Log *log = GetLog(LLDBLog::Process);
2639
2640 if (!m_current_process ||
2642 LLDB_LOGF(
2643 log,
2644 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2645 __FUNCTION__);
2646 return SendErrorResponse(0x15);
2647 }
2648
2649 // Parse out the memory address.
2650 packet.SetFilePos(strlen("m"));
2651 if (packet.GetBytesLeft() < 1)
2652 return SendIllFormedResponse(packet, "Too short m packet");
2653
2654 // Read the address. Punting on validation.
2655 // FIXME replace with Hex U64 read with no default value that fails on failed
2656 // read.
2657 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2658
2659 // Validate comma.
2660 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2661 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2662
2663 // Get # bytes to read.
2664 if (packet.GetBytesLeft() < 1)
2665 return SendIllFormedResponse(packet, "Length missing in m packet");
2666
2667 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2668 if (byte_count == 0) {
2669 LLDB_LOGF(log,
2670 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2671 "zero-length packet",
2672 __FUNCTION__);
2673 return SendOKResponse();
2674 }
2675
2676 // Allocate the response buffer.
2677 std::string buf(byte_count, '\0');
2678 if (buf.empty())
2679 return SendErrorResponse(0x78);
2680
2681 // Retrieve the process memory.
2682 size_t bytes_read = 0;
2683 Status error = m_current_process->ReadMemoryWithoutTrap(
2684 read_addr, &buf[0], byte_count, bytes_read);
2685 LLDB_LOG(
2686 log,
2687 "ReadMemoryWithoutTrap({0}) read {1} of {2} requested bytes (error: {3})",
2688 read_addr, byte_count, bytes_read, error);
2689 if (bytes_read == 0)
2690 return SendErrorResponse(0x08);
2691
2692 StreamGDBRemote response;
2693 packet.SetFilePos(0);
2694 char kind = packet.GetChar('?');
2695 if (kind == 'x')
2696 response.PutEscapedBytes(buf.data(), bytes_read);
2697 else {
2698 assert(kind == 'm');
2699 for (size_t i = 0; i < bytes_read; ++i)
2700 response.PutHex8(buf[i]);
2701 }
2702
2703 return SendPacketNoLock(response.GetString());
2704}
2705
2708 Log *log = GetLog(LLDBLog::Process);
2709
2710 if (!m_current_process ||
2712 LLDB_LOGF(
2713 log,
2714 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2715 __FUNCTION__);
2716 return SendErrorResponse(0x15);
2717 }
2718
2719 // Parse out the memory address.
2720 packet.SetFilePos(strlen("_M"));
2721 if (packet.GetBytesLeft() < 1)
2722 return SendIllFormedResponse(packet, "Too short _M packet");
2723
2724 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2725 if (size == LLDB_INVALID_ADDRESS)
2726 return SendIllFormedResponse(packet, "Address not valid");
2727 if (packet.GetChar() != ',')
2728 return SendIllFormedResponse(packet, "Bad packet");
2729 Permissions perms = {};
2730 while (packet.GetBytesLeft() > 0) {
2731 switch (packet.GetChar()) {
2732 case 'r':
2733 perms |= ePermissionsReadable;
2734 break;
2735 case 'w':
2736 perms |= ePermissionsWritable;
2737 break;
2738 case 'x':
2739 perms |= ePermissionsExecutable;
2740 break;
2741 default:
2742 return SendIllFormedResponse(packet, "Bad permissions");
2743 }
2744 }
2745
2746 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2747 if (!addr)
2748 return SendErrorResponse(addr.takeError());
2749
2750 StreamGDBRemote response;
2751 response.PutHex64(*addr);
2752 return SendPacketNoLock(response.GetString());
2753}
2754
2757 Log *log = GetLog(LLDBLog::Process);
2758
2759 if (!m_current_process ||
2761 LLDB_LOGF(
2762 log,
2763 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2764 __FUNCTION__);
2765 return SendErrorResponse(0x15);
2766 }
2767
2768 // Parse out the memory address.
2769 packet.SetFilePos(strlen("_m"));
2770 if (packet.GetBytesLeft() < 1)
2771 return SendIllFormedResponse(packet, "Too short m packet");
2772
2773 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2774 if (addr == LLDB_INVALID_ADDRESS)
2775 return SendIllFormedResponse(packet, "Address not valid");
2776
2777 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2778 return SendErrorResponse(std::move(Err));
2779
2780 return SendOKResponse();
2781}
2782
2785 Log *log = GetLog(LLDBLog::Process);
2786
2787 if (!m_current_process ||
2789 LLDB_LOGF(
2790 log,
2791 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2792 __FUNCTION__);
2793 return SendErrorResponse(0x15);
2794 }
2795
2796 // Parse out the memory address.
2797 packet.SetFilePos(strlen("M"));
2798 if (packet.GetBytesLeft() < 1)
2799 return SendIllFormedResponse(packet, "Too short M packet");
2800
2801 // Read the address. Punting on validation.
2802 // FIXME replace with Hex U64 read with no default value that fails on failed
2803 // read.
2804 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2805
2806 // Validate comma.
2807 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2808 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2809
2810 // Get # bytes to read.
2811 if (packet.GetBytesLeft() < 1)
2812 return SendIllFormedResponse(packet, "Length missing in M packet");
2813
2814 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2815 if (byte_count == 0) {
2816 LLDB_LOG(log, "nothing to write: zero-length packet");
2817 return PacketResult::Success;
2818 }
2819
2820 // Validate colon.
2821 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2822 return SendIllFormedResponse(
2823 packet, "Comma sep missing in M packet after byte length");
2824
2825 // Allocate the conversion buffer.
2826 std::vector<uint8_t> buf(byte_count, 0);
2827 if (buf.empty())
2828 return SendErrorResponse(0x78);
2829
2830 // Convert the hex memory write contents to bytes.
2831 StreamGDBRemote response;
2832 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2833 if (convert_count != byte_count) {
2834 LLDB_LOG(log,
2835 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2836 "to convert.",
2837 m_current_process->GetID(), write_addr, byte_count, convert_count);
2838 return SendIllFormedResponse(packet, "M content byte length specified did "
2839 "not match hex-encoded content "
2840 "length");
2841 }
2842
2843 // Write the process memory.
2844 size_t bytes_written = 0;
2845 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2846 bytes_written);
2847 if (error.Fail()) {
2848 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2849 m_current_process->GetID(), write_addr, error);
2850 return SendErrorResponse(0x09);
2851 }
2852
2853 if (bytes_written == 0) {
2854 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2855 m_current_process->GetID(), write_addr, byte_count);
2856 return SendErrorResponse(0x09);
2857 }
2858
2859 return SendOKResponse();
2860}
2861
2864 StringExtractorGDBRemote &packet) {
2865 Log *log = GetLog(LLDBLog::Process);
2866
2867 // Currently only the NativeProcessProtocol knows if it can handle a
2868 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2869 // attached to a process. For now we'll assume the client only asks this
2870 // when a process is being debugged.
2871
2872 // Ensure we have a process running; otherwise, we can't figure this out
2873 // since we won't have a NativeProcessProtocol.
2874 if (!m_current_process ||
2876 LLDB_LOGF(
2877 log,
2878 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2879 __FUNCTION__);
2880 return SendErrorResponse(0x15);
2881 }
2882
2883 // Test if we can get any region back when asking for the region around NULL.
2884 MemoryRegionInfo region_info;
2885 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2886 if (error.Fail()) {
2887 // We don't support memory region info collection for this
2888 // NativeProcessProtocol.
2889 return SendUnimplementedResponse("");
2890 }
2891
2892 return SendOKResponse();
2893}
2894
2897 StringExtractorGDBRemote &packet) {
2898 Log *log = GetLog(LLDBLog::Process);
2899
2900 // Ensure we have a process.
2901 if (!m_current_process ||
2903 LLDB_LOGF(
2904 log,
2905 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2906 __FUNCTION__);
2907 return SendErrorResponse(0x15);
2908 }
2909
2910 // Parse out the memory address.
2911 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2912 if (packet.GetBytesLeft() < 1)
2913 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2914
2915 // Read the address. Punting on validation.
2916 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2917
2918 StreamGDBRemote response;
2919
2920 // Get the memory region info for the target address.
2921 MemoryRegionInfo region_info;
2922 const Status error =
2923 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2924 if (error.Fail()) {
2925 // Return the error message.
2926
2927 response.PutCString("error:");
2928 response.PutStringAsRawHex8(error.AsCString());
2929 response.PutChar(';');
2930 } else {
2931 // Range start and size.
2932 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2933 region_info.GetRange().GetRangeBase(),
2934 region_info.GetRange().GetByteSize());
2935
2936 // Permissions.
2937 if (region_info.GetReadable() || region_info.GetWritable() ||
2938 region_info.GetExecutable()) {
2939 // Write permissions info.
2940 response.PutCString("permissions:");
2941
2942 if (region_info.GetReadable())
2943 response.PutChar('r');
2944 if (region_info.GetWritable())
2945 response.PutChar('w');
2946 if (region_info.GetExecutable())
2947 response.PutChar('x');
2948
2949 response.PutChar(';');
2950 }
2951
2952 // Flags
2953 LazyBool memory_tagged = region_info.GetMemoryTagged();
2954 LazyBool is_shadow_stack = region_info.IsShadowStack();
2955
2956 if (memory_tagged != eLazyBoolDontKnow ||
2957 is_shadow_stack != eLazyBoolDontKnow) {
2958 response.PutCString("flags:");
2959 // Space is the separator.
2960 if (memory_tagged == eLazyBoolYes)
2961 response.PutCString("mt ");
2962 if (is_shadow_stack == eLazyBoolYes)
2963 response.PutCString("ss ");
2964
2965 response.PutChar(';');
2966 }
2967
2968 // Name
2969 ConstString name = region_info.GetName();
2970 if (name) {
2971 response.PutCString("name:");
2972 response.PutStringAsRawHex8(name.GetStringRef());
2973 response.PutChar(';');
2974 }
2975
2976 if (std::optional<unsigned> protection_key = region_info.GetProtectionKey())
2977 response.Printf("protection-key:%" PRIu32 ";", *protection_key);
2978
2979 LazyBool is_stack = region_info.IsStackMemory();
2980 if (is_stack != eLazyBoolDontKnow)
2981 response.Printf("type: %s", is_stack ? "stack" : "heap");
2982 }
2983
2984 return SendPacketNoLock(response.GetString());
2985}
2986
2987namespace {
2988struct UseBreakpoint {
2989 bool want_hardware = false;
2990};
2991struct UseWatchpoint {
2992 uint32_t flags;
2993 static constexpr bool want_hardware = true;
2994};
2995struct InvalidStoppoint {};
2996
2997std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint>
2998getBreakpointKind(GDBStoppointType stoppoint_type) {
2999 switch (stoppoint_type) {
3001 return UseBreakpoint{/*want_hardware*/ false};
3003 return UseBreakpoint{/*want_hardware*/ true};
3004 case eWatchpointWrite:
3005 return UseWatchpoint{/*flags*/ 1};
3006 case eWatchpointRead:
3007 return UseWatchpoint{/*flags*/ 2};
3009 return UseWatchpoint{/*flags*/ 3};
3010 case eStoppointInvalid:
3011 return InvalidStoppoint();
3012 }
3013 llvm_unreachable("unhandled GDBStoppointType");
3014}
3015} // namespace
3016
3019 llvm::StringRef packet_str) {
3020 // Ensure we have a process.
3021 if (!m_current_process ||
3023 Log *log = GetLog(LLDBLog::Process);
3024 LLDB_LOG(log, "failed, no process available");
3025 return BreakpointError{0x15};
3026 }
3027
3028 StringExtractorGDBRemote packet(packet_str);
3029
3030 // Parse out software or hardware breakpoint or watchpoint requested.
3031 packet.SetFilePos(strlen("Z"));
3032 if (packet.GetBytesLeft() < 1)
3033 return BreakpointIllFormed{
3034 "Too short Z packet, missing software/hardware specifier"};
3035
3036 const GDBStoppointType stoppoint_type =
3038 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3039 getBreakpointKind(stoppoint_type);
3040 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3041 return BreakpointIllFormed{
3042 "Z packet had invalid software/hardware specifier"};
3043
3044 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3045 return BreakpointIllFormed{
3046 "Malformed Z packet, expecting comma after stoppoint type"};
3047
3048 // Parse out the stoppoint address.
3049 if (packet.GetBytesLeft() < 1)
3050 return BreakpointIllFormed{"Too short Z packet, missing address"};
3051 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3052
3053 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3054 return BreakpointIllFormed{
3055 "Malformed Z packet, expecting comma after address"};
3056
3057 // Parse out the stoppoint size (i.e. size hint for opcode size).
3058 const uint32_t size =
3059 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
3060 if (size == std::numeric_limits<uint32_t>::max())
3061 return BreakpointIllFormed{
3062 "Malformed Z packet, failed to parse size argument"};
3063
3064 // Try to set a breakpoint.
3065 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3066 const Status error =
3067 m_current_process->SetBreakpoint(addr, size, bp_kind->want_hardware);
3068 if (error.Success())
3069 return BreakpointOK();
3071 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
3072 m_current_process->GetID(), error);
3073 return BreakpointError{0x09};
3074 }
3075
3076 // Try to set a watchpoint.
3077 auto wp_kind = std::get<UseWatchpoint>(bp_variant);
3078 const Status error = m_current_process->SetWatchpoint(
3079 addr, size, wp_kind.flags, wp_kind.want_hardware);
3080 if (error.Success())
3081 return BreakpointOK();
3083 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
3084 m_current_process->GetID(), error);
3085 return BreakpointError{0x09};
3086}
3087
3090 llvm::StringRef packet_str) {
3091 // Ensure we have a process.
3092 if (!m_current_process ||
3094 Log *log = GetLog(LLDBLog::Process);
3095 LLDB_LOG(log, "failed, no process available");
3096 return BreakpointError{0x15};
3097 }
3098
3099 StringExtractorGDBRemote packet(packet_str);
3100
3101 // Parse out software or hardware breakpoint or watchpoint requested.
3102 packet.SetFilePos(strlen("z"));
3103 if (packet.GetBytesLeft() < 1)
3104 return BreakpointIllFormed{
3105 "Too short z packet, missing software/hardware specifier"};
3106
3107 const GDBStoppointType stoppoint_type =
3109 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3110 getBreakpointKind(stoppoint_type);
3111 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3112 return BreakpointIllFormed{
3113 "z packet had invalid software/hardware specifier"};
3114
3115 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3116 return BreakpointIllFormed{
3117 "Malformed z packet, expecting comma after stoppoint type"};
3118
3119 // Parse out the stoppoint address.
3120 if (packet.GetBytesLeft() < 1)
3121 return BreakpointIllFormed{"Too short z packet, missing address"};
3122 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3123
3124 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3125 return BreakpointIllFormed{
3126 "Malformed z packet, expecting comma after address"};
3127
3128 /*
3129 // Parse out the stoppoint size (i.e. size hint for opcode size).
3130 const uint32_t size = packet.GetHexMaxU32 (false,
3131 std::numeric_limits<uint32_t>::max ());
3132 if (size == std::numeric_limits<uint32_t>::max ())
3133 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
3134 size argument");
3135 */
3136
3137 // Try to clear the breakpoint.
3138 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3139 const Status error =
3140 m_current_process->RemoveBreakpoint(addr, bp_kind->want_hardware);
3141 if (error.Success())
3142 return BreakpointOK();
3144 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
3145 m_current_process->GetID(), error);
3146 return BreakpointError{0x09};
3147 }
3148 // Try to clear the watchpoint.
3149 const Status error = m_current_process->RemoveWatchpoint(addr);
3150 if (error.Success())
3151 return BreakpointOK();
3153 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3154 m_current_process->GetID(), error);
3155 return BreakpointError{0x09};
3156}
3157
3160 StringExtractorGDBRemote &packet, const BreakpointResult &result) {
3161 return std::visit(
3162 [&](auto &&arg) {
3163 using T = std::decay_t<decltype(arg)>;
3164 static_assert(std::is_same_v<T, BreakpointOK> ||
3165 std::is_same_v<T, BreakpointError> ||
3166 std::is_same_v<T, BreakpointIllFormed>,
3167 "non-exhaustive visitor!");
3168 if constexpr (std::is_same_v<T, BreakpointOK>)
3169 return SendOKResponse();
3170 else if constexpr (std::is_same_v<T, BreakpointError>)
3171 return SendErrorResponse(arg.error_code);
3172 else
3173 return SendIllFormedResponse(packet, arg.message.c_str());
3174 },
3175 result);
3176}
3177
3183
3189
3192 StringExtractorGDBRemote &packet) {
3193 llvm::StringRef packet_str = packet.GetStringRef();
3194 if (!packet_str.consume_front("jMultiBreakpoint:"))
3195 return SendIllFormedResponse(packet,
3196 "Invalid jMultiBreakpoint packet prefix");
3197
3198 llvm::Expected<llvm::json::Value> parsed = llvm::json::parse(packet_str);
3199 if (!parsed) {
3200 llvm::consumeError(parsed.takeError());
3201 return SendIllFormedResponse(packet,
3202 "jMultiBreakpoint did not contain valid JSON");
3203 }
3204 llvm::json::Object *request_dict = parsed->getAsObject();
3205 if (!request_dict)
3206 return SendIllFormedResponse(
3207 packet, "jMultiBreakpoint did not contain a JSON dictionary");
3208
3209 llvm::json::Array *request_array =
3210 request_dict->getArray("breakpoint_requests");
3211 if (!request_array)
3212 return SendIllFormedResponse(
3213 packet,
3214 "jMultiBreakpoint did not contain a valid 'breakpoint_requests' field");
3215
3216 llvm::json::Array reply_array;
3217 for (const llvm::json::Value &value : *request_array) {
3218 std::optional<llvm::StringRef> request = value.getAsString();
3219 if (!request)
3220 return SendIllFormedResponse(packet,
3221 "jMultiBreakpoint had a non-string entry");
3222 BreakpointResult result = request->starts_with("Z")
3223 ? ExecuteSetBreakpoint(*request)
3224 : ExecuteRemoveBreakpoint(*request);
3225 std::visit(
3226 [&](const auto &arg) {
3227 using T = std::decay_t<decltype(arg)>;
3228 static_assert(std::is_same_v<T, BreakpointOK> ||
3229 std::is_same_v<T, BreakpointError> ||
3230 std::is_same_v<T, BreakpointIllFormed>,
3231 "non-exhaustive visitor!");
3232 if constexpr (std::is_same_v<T, BreakpointOK>)
3233 reply_array.push_back("OK");
3234 else if constexpr (std::is_same_v<T, BreakpointError>)
3235 reply_array.push_back(
3236 llvm::formatv("E{0:X-2}", arg.error_code).str());
3237 else
3238 reply_array.push_back("E03");
3239 },
3240 result);
3241 }
3242
3243 llvm::json::Object dict;
3244 dict.try_emplace("results", std::move(reply_array));
3245
3246 StreamString stream;
3247 stream.AsRawOstream() << llvm::json::Value(std::move(dict));
3248 StringRef response_str = stream.GetString();
3249 StreamGDBRemote response;
3250 response.PutEscapedBytes(response_str.data(), response_str.size());
3251 return SendPacketNoLock(response.GetString());
3252}
3253
3257
3258 // Ensure we have a process.
3259 if (!m_continue_process ||
3261 LLDB_LOGF(
3262 log,
3263 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3264 __FUNCTION__);
3265 return SendErrorResponse(0x32);
3266 }
3267
3268 // We first try to use a continue thread id. If any one or any all set, use
3269 // the current thread. Bail out if we don't have a thread id.
3271 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3272 tid = GetCurrentThreadID();
3273 if (tid == LLDB_INVALID_THREAD_ID)
3274 return SendErrorResponse(0x33);
3275
3276 // Double check that we have such a thread.
3277 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3278 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3279 if (!thread)
3280 return SendErrorResponse(0x33);
3281
3282 // Create the step action for the given thread.
3284
3285 // Setup the actions list.
3286 ResumeActionList actions;
3287 actions.Append(action);
3288
3289 // All other threads stop while we're single stepping a thread.
3291
3292 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3293 if (resume_res != PacketResult::Success)
3294 return resume_res;
3295
3296 // No response here, unless in non-stop mode.
3297 // Otherwise, the stop or exit will come from the resulting action.
3299}
3300
3301llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3303 // Ensure we have a thread.
3304 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3305 if (!thread)
3306 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3307 "No thread available");
3308
3310 // Get the register context for the first thread.
3311 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3312
3313 StreamString response;
3314
3315 response.Printf("<?xml version=\"1.0\"?>\n");
3316 response.Printf("<target version=\"1.0\">\n");
3317 response.IndentMore();
3318
3319 response.Indent();
3320 const llvm::StringRef arch_name =
3321 m_current_process->GetArchitecture().GetTriple().getArchName();
3322 // Match gdbserver's expected architecture. We do the reverse when
3323 // decoding the architecture when receiving the target.xml
3324 // in ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess.
3325 const llvm::StringRef new_arch_name = StringSwitch<llvm::StringRef>(arch_name)
3326 .Case("x86_64", "i386:x86-64")
3327 .Case("riscv64", "riscv:rv64")
3328 .Case("riscv32", "riscv:rv32")
3329 .Default(arch_name);
3330 response.Format("<architecture>{}</architecture>\n", new_arch_name);
3331 response.Indent("<feature>\n");
3332
3333 const int registers_count = reg_context.GetUserRegisterCount();
3334 if (registers_count)
3335 response.IndentMore();
3336
3337 std::unordered_set<const RegisterType *> register_types_emitted;
3338 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3339 const RegisterInfo *reg_info =
3340 reg_context.GetRegisterInfoAtIndex(reg_index);
3341
3342 if (!reg_info) {
3343 LLDB_LOGF(log,
3344 "%s failed to get register info for register index %" PRIu32,
3345 "target.xml", reg_index);
3346 continue;
3347 }
3348
3349 if (reg_info->register_type)
3350 reg_info->register_type->ToXML(response, register_types_emitted);
3351
3352 response.Indent();
3353 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3354 "\" regnum=\"%d\" ",
3355 reg_info->name, reg_info->byte_size * 8, reg_index);
3356
3357 if (!reg_context.RegisterOffsetIsDynamic())
3358 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3359
3360 if (reg_info->alt_name && reg_info->alt_name[0])
3361 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3362
3363 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3364 if (!encoding.empty())
3365 response << "encoding=\"" << encoding << "\" ";
3366
3367 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3368 if (!format.empty())
3369 response << "format=\"" << format << "\" ";
3370
3371 if (reg_info->register_type)
3372 response << "type=\"" << reg_info->register_type->GetID() << "\" ";
3373
3374 const char *const register_set_name =
3375 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3376 if (register_set_name)
3377 response << "group=\"" << register_set_name << "\" ";
3378
3381 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3383
3384 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3386 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3388
3389 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3390 if (!kind_generic.empty())
3391 response << "generic=\"" << kind_generic << "\" ";
3392
3393 if (reg_info->value_regs &&
3394 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3395 response.PutCString("value_regnums=\"");
3396 CollectRegNums(reg_info->value_regs, response, false);
3397 response.Printf("\" ");
3398 }
3399
3400 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3401 response.PutCString("invalidate_regnums=\"");
3402 CollectRegNums(reg_info->invalidate_regs, response, false);
3403 response.Printf("\" ");
3404 }
3405
3406 response.Printf("/>\n");
3407 }
3408
3409 if (registers_count)
3410 response.IndentLess();
3411
3412 response.Indent("</feature>\n");
3413 response.IndentLess();
3414 response.Indent("</target>\n");
3415 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3416}
3417
3418llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3420 llvm::StringRef annex) {
3421 // Make sure we have a valid process.
3422 if (!m_current_process ||
3424 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3425 "No process available");
3426 }
3427
3428 if (object == "auxv") {
3429 // Grab the auxv data.
3430 auto buffer_or_error = m_current_process->GetAuxvData();
3431 if (!buffer_or_error)
3432 return llvm::errorCodeToError(buffer_or_error.getError());
3433 return std::move(*buffer_or_error);
3434 }
3435
3436 if (object == "siginfo") {
3437 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3438 if (!thread)
3439 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3440 "no current thread");
3441
3442 auto buffer_or_error = thread->GetSiginfo();
3443 if (!buffer_or_error)
3444 return buffer_or_error.takeError();
3445 return std::move(*buffer_or_error);
3446 }
3447
3448 if (object == "libraries-svr4") {
3449 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3450 if (!library_list)
3451 return library_list.takeError();
3452
3453 StreamString response;
3454 response.Printf("<library-list-svr4 version=\"1.0\">");
3455 for (auto const &library : *library_list) {
3456 response.Printf("<library name=\"%s\" ",
3457 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3458 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3459 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3460 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3461 }
3462 response.Printf("</library-list-svr4>");
3463 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3464 }
3465
3466 if (object == "libraries") {
3467 auto library_list = m_current_process->GetLoadedLibraries();
3468 if (!library_list)
3469 return library_list.takeError();
3470
3471 StreamString response;
3472 response.Printf("<library-list>");
3473 for (auto const &library : *library_list) {
3474 response.Printf("<library name=\"%s\">",
3475 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3476 response.Printf("<section address=\"0x%" PRIx64 "\"/>",
3477 library.base_addr);
3478 response.Printf("</library>");
3479 }
3480 response.Printf("</library-list>");
3481 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3482 }
3483
3484 if (object == "features" && annex == "target.xml")
3485 return BuildTargetXml();
3486
3487 return llvm::make_error<UnimplementedError>();
3488}
3489
3492 StringExtractorGDBRemote &packet) {
3493 SmallVector<StringRef, 5> fields;
3494 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3495 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3496 if (fields.size() != 5)
3497 return SendIllFormedResponse(packet, "malformed qXfer packet");
3498 StringRef &xfer_object = fields[1];
3499 StringRef &xfer_action = fields[2];
3500 StringRef &xfer_annex = fields[3];
3501 StringExtractor offset_data(fields[4]);
3502 if (xfer_action != "read")
3503 return SendUnimplementedResponse("qXfer action not supported");
3504 // Parse offset.
3505 const uint64_t xfer_offset =
3506 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3507 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3508 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3509 // Parse out comma.
3510 if (offset_data.GetChar() != ',')
3511 return SendIllFormedResponse(packet,
3512 "qXfer packet missing comma after offset");
3513 // Parse out the length.
3514 const uint64_t xfer_length =
3515 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3516 if (xfer_length == std::numeric_limits<uint64_t>::max())
3517 return SendIllFormedResponse(packet, "qXfer packet missing length");
3518
3519 // Get a previously constructed buffer if it exists or create it now.
3520 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3521 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3522 if (buffer_it == m_xfer_buffer_map.end()) {
3523 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3524 if (!buffer_up)
3525 return SendErrorResponse(buffer_up.takeError());
3526 buffer_it = m_xfer_buffer_map
3527 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3528 .first;
3529 }
3530
3531 // Send back the response
3532 StreamGDBRemote response;
3533 bool done_with_buffer = false;
3534 llvm::StringRef buffer = buffer_it->second->getBuffer();
3535 if (xfer_offset >= buffer.size()) {
3536 // We have nothing left to send. Mark the buffer as complete.
3537 response.PutChar('l');
3538 done_with_buffer = true;
3539 } else {
3540 // Figure out how many bytes are available starting at the given offset.
3541 buffer = buffer.drop_front(xfer_offset);
3542 // Mark the response type according to whether we're reading the remainder
3543 // of the data.
3544 if (xfer_length >= buffer.size()) {
3545 // There will be nothing left to read after this
3546 response.PutChar('l');
3547 done_with_buffer = true;
3548 } else {
3549 // There will still be bytes to read after this request.
3550 response.PutChar('m');
3551 buffer = buffer.take_front(xfer_length);
3552 }
3553 // Now write the data in encoded binary form.
3554 response.PutEscapedBytes(buffer.data(), buffer.size());
3555 }
3556
3557 if (done_with_buffer)
3558 m_xfer_buffer_map.erase(buffer_it);
3559
3560 return SendPacketNoLock(response.GetString());
3561}
3562
3565 StringExtractorGDBRemote &packet) {
3566 Log *log = GetLog(LLDBLog::Thread);
3567
3568 // Move past packet name.
3569 packet.SetFilePos(strlen("QSaveRegisterState"));
3570
3571 // Get the thread to use.
3572 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3573 if (!thread) {
3575 return SendIllFormedResponse(
3576 packet, "No thread specified in QSaveRegisterState packet");
3577 else
3578 return SendIllFormedResponse(packet,
3579 "No thread was is set with the Hg packet");
3580 }
3581
3582 // Grab the register context for the thread.
3583 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3584
3585 // Save registers to a buffer.
3586 WritableDataBufferSP register_data_sp;
3587 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3588 if (error.Fail()) {
3589 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3590 m_current_process->GetID(), error);
3591 return SendErrorResponse(0x75);
3592 }
3593
3594 // Allocate a new save id.
3595 const uint32_t save_id = GetNextSavedRegistersID();
3596 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3597 "GetNextRegisterSaveID() returned an existing register save id");
3598
3599 // Save the register data buffer under the save id.
3600 {
3601 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3602 m_saved_registers_map[save_id] = register_data_sp;
3603 }
3604
3605 // Write the response.
3606 StreamGDBRemote response;
3607 response.Printf("%" PRIu32, save_id);
3608 return SendPacketNoLock(response.GetString());
3609}
3610
3613 StringExtractorGDBRemote &packet) {
3614 Log *log = GetLog(LLDBLog::Thread);
3615
3616 // Parse out save id.
3617 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3618 if (packet.GetBytesLeft() < 1)
3619 return SendIllFormedResponse(
3620 packet, "QRestoreRegisterState packet missing register save id");
3621
3622 const uint32_t save_id = packet.GetU32(0);
3623 if (save_id == 0) {
3624 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3625 "expecting decimal uint32_t");
3626 return SendErrorResponse(0x76);
3627 }
3628
3629 // Get the thread to use.
3630 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3631 if (!thread) {
3633 return SendIllFormedResponse(
3634 packet, "No thread specified in QRestoreRegisterState packet");
3635 else
3636 return SendIllFormedResponse(packet,
3637 "No thread was is set with the Hg packet");
3638 }
3639
3640 // Grab the register context for the thread.
3641 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3642
3643 // Retrieve register state buffer, then remove from the list.
3644 DataBufferSP register_data_sp;
3645 {
3646 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3647
3648 // Find the register set buffer for the given save id.
3649 auto it = m_saved_registers_map.find(save_id);
3650 if (it == m_saved_registers_map.end()) {
3651 LLDB_LOG(log,
3652 "pid {0} does not have a register set save buffer for id {1}",
3653 m_current_process->GetID(), save_id);
3654 return SendErrorResponse(0x77);
3655 }
3656 register_data_sp = it->second;
3657
3658 // Remove it from the map.
3659 m_saved_registers_map.erase(it);
3660 }
3661
3662 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3663 if (error.Fail()) {
3664 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3665 m_current_process->GetID(), error);
3666 return SendErrorResponse(0x77);
3667 }
3668
3669 return SendOKResponse();
3670}
3671
3674 StringExtractorGDBRemote &packet) {
3675 Log *log = GetLog(LLDBLog::Process);
3676
3677 // Consume the ';' after vAttach.
3678 packet.SetFilePos(strlen("vAttach"));
3679 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3680 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3681
3682 // Grab the PID to which we will attach (assume hex encoding).
3683 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3684 if (pid == LLDB_INVALID_PROCESS_ID)
3685 return SendIllFormedResponse(packet,
3686 "vAttach failed to parse the process id");
3687
3688 // Attempt to attach.
3689 LLDB_LOGF(log,
3690 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3691 "pid %" PRIu64,
3692 __FUNCTION__, pid);
3693
3695
3696 if (error.Fail()) {
3697 LLDB_LOGF(log,
3698 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3699 "pid %" PRIu64 ": %s\n",
3700 __FUNCTION__, pid, error.AsCString());
3701 return SendErrorResponse(error);
3702 }
3703
3704 // Notify we attached by sending a stop packet.
3705 assert(m_current_process);
3707 m_current_process->GetState(),
3708 /*force_synchronous=*/false);
3709}
3710
3713 StringExtractorGDBRemote &packet) {
3714 Log *log = GetLog(LLDBLog::Process);
3715
3716 // Consume the ';' after the identifier.
3717 packet.SetFilePos(strlen("vAttachWait"));
3718
3719 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3720 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3721
3722 // Allocate the buffer for the process name from vAttachWait.
3723 std::string process_name;
3724 if (!packet.GetHexByteString(process_name))
3725 return SendIllFormedResponse(packet,
3726 "vAttachWait failed to parse process name");
3727
3728 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3729
3730 Status error = AttachWaitProcess(process_name, false);
3731 if (error.Fail()) {
3732 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3733 error);
3734 return SendErrorResponse(error);
3735 }
3736
3737 // Notify we attached by sending a stop packet.
3738 assert(m_current_process);
3740 m_current_process->GetState(),
3741 /*force_synchronous=*/false);
3742}
3743
3749
3752 StringExtractorGDBRemote &packet) {
3753 Log *log = GetLog(LLDBLog::Process);
3754
3755 // Consume the ';' after the identifier.
3756 packet.SetFilePos(strlen("vAttachOrWait"));
3757
3758 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3759 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3760
3761 // Allocate the buffer for the process name from vAttachWait.
3762 std::string process_name;
3763 if (!packet.GetHexByteString(process_name))
3764 return SendIllFormedResponse(packet,
3765 "vAttachOrWait failed to parse process name");
3766
3767 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3768
3769 Status error = AttachWaitProcess(process_name, true);
3770 if (error.Fail()) {
3771 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3772 error);
3773 return SendErrorResponse(error);
3774 }
3775
3776 // Notify we attached by sending a stop packet.
3777 assert(m_current_process);
3779 m_current_process->GetState(),
3780 /*force_synchronous=*/false);
3781}
3782
3785 StringExtractorGDBRemote &packet) {
3786 Log *log = GetLog(LLDBLog::Process);
3787
3788 llvm::StringRef s = packet.GetStringRef();
3789 if (!s.consume_front("vRun;"))
3790 return SendErrorResponse(8);
3791
3792 llvm::SmallVector<llvm::StringRef, 16> argv;
3793 s.split(argv, ';');
3794
3795 for (llvm::StringRef hex_arg : argv) {
3796 StringExtractor arg_ext{hex_arg};
3797 std::string arg;
3798 arg_ext.GetHexByteString(arg);
3799 m_process_launch_info.GetArguments().AppendArgument(arg);
3800 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3801 arg.c_str());
3802 }
3803
3804 if (argv.empty())
3805 return SendErrorResponse(Status::FromErrorString("No arguments"));
3806 m_process_launch_info.GetExecutableFile().SetFile(
3807 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3809 if (m_process_launch_error.Fail())
3811 assert(m_current_process);
3813 m_current_process->GetState(),
3814 /*force_synchronous=*/true);
3815}
3816
3819 Log *log = GetLog(LLDBLog::Process);
3820 if (!m_non_stop)
3822
3824
3825 // Consume the ';' after D.
3826 packet.SetFilePos(1);
3827 if (packet.GetBytesLeft()) {
3828 if (packet.GetChar() != ';')
3829 return SendIllFormedResponse(packet, "D missing expected ';'");
3830
3831 // Grab the PID from which we will detach (assume hex encoding).
3832 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3833 if (pid == LLDB_INVALID_PROCESS_ID)
3834 return SendIllFormedResponse(packet, "D failed to parse the process id");
3835 }
3836
3837 // Detach forked children if their PID was specified *or* no PID was requested
3838 // (i.e. detach-all packet).
3839 llvm::Error detach_error = llvm::Error::success();
3840 bool detached = false;
3841 for (auto it = m_debugged_processes.begin();
3842 it != m_debugged_processes.end();) {
3843 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3844 LLDB_LOGF(log,
3845 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3846 __FUNCTION__, it->first);
3847 if (llvm::Error e = it->second.process_up->Detach().ToError())
3848 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3849 else {
3850 if (it->second.process_up.get() == m_current_process)
3851 m_current_process = nullptr;
3852 if (it->second.process_up.get() == m_continue_process)
3853 m_continue_process = nullptr;
3854 it = m_debugged_processes.erase(it);
3855 detached = true;
3856 continue;
3857 }
3858 }
3859 ++it;
3860 }
3861
3862 if (detach_error)
3863 return SendErrorResponse(std::move(detach_error));
3864 if (!detached)
3865 return SendErrorResponse(
3866 Status::FromErrorStringWithFormat("PID %" PRIu64 " not traced", pid));
3867 return SendOKResponse();
3868}
3869
3872 StringExtractorGDBRemote &packet) {
3873 Log *log = GetLog(LLDBLog::Thread);
3874
3875 if (!m_current_process ||
3877 return SendErrorResponse(50);
3878
3879 packet.SetFilePos(strlen("qThreadStopInfo"));
3880 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3881 if (tid == LLDB_INVALID_THREAD_ID) {
3882 LLDB_LOGF(log,
3883 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3884 "parse thread id from request \"%s\"",
3885 __FUNCTION__, packet.GetStringRef().data());
3886 return SendErrorResponse(0x15);
3887 }
3889 /*force_synchronous=*/true);
3890}
3891
3896
3897 // Ensure we have a debugged process.
3898 if (!m_current_process ||
3900 return SendErrorResponse(50);
3901 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3902
3903 StreamString response;
3904 const bool threads_with_valid_stop_info_only = false;
3905 llvm::Expected<json::Value> threads_info =
3906 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3907 if (!threads_info) {
3908 LLDB_LOG_ERROR(log, threads_info.takeError(),
3909 "failed to prepare a packet for pid {1}: {0}",
3910 m_current_process->GetID());
3911 return SendErrorResponse(52);
3912 }
3913
3914 response.AsRawOstream() << *threads_info;
3915 StreamGDBRemote escaped_response;
3916 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3917 return SendPacketNoLock(escaped_response.GetString());
3918}
3919
3922 StringExtractorGDBRemote &packet) {
3923 // Fail if we don't have a current process.
3924 if (!m_current_process ||
3926 return SendErrorResponse(68);
3927
3928 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3929 if (packet.GetBytesLeft() == 0)
3930 return SendOKResponse();
3931 if (packet.GetChar() != ':')
3932 return SendErrorResponse(67);
3933
3934 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3935
3936 StreamGDBRemote response;
3937 if (hw_debug_cap == std::nullopt)
3938 response.Printf("num:0;");
3939 else
3940 response.Printf("num:%d;", hw_debug_cap->second);
3941
3942 return SendPacketNoLock(response.GetString());
3943}
3944
3947 StringExtractorGDBRemote &packet) {
3948 // Fail if we don't have a current process.
3949 if (!m_current_process ||
3951 return SendErrorResponse(67);
3952
3953 packet.SetFilePos(strlen("qFileLoadAddress:"));
3954 if (packet.GetBytesLeft() == 0)
3955 return SendErrorResponse(68);
3956
3957 std::string file_name;
3958 packet.GetHexByteString(file_name);
3959
3960 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3961 Status error =
3962 m_current_process->GetFileLoadAddress(file_name, file_load_address);
3963 if (error.Fail())
3964 return SendErrorResponse(69);
3965
3966 if (file_load_address == LLDB_INVALID_ADDRESS)
3967 return SendErrorResponse(1); // File not loaded
3968
3969 StreamGDBRemote response;
3970 response.PutHex64(file_load_address);
3971 return SendPacketNoLock(response.GetString());
3972}
3973
3976 StringExtractorGDBRemote &packet) {
3977 std::vector<int> signals;
3978 packet.SetFilePos(strlen("QPassSignals:"));
3979
3980 // Read sequence of hex signal numbers divided by a semicolon and optionally
3981 // spaces.
3982 while (packet.GetBytesLeft() > 0) {
3983 int signal = packet.GetS32(-1, 16);
3984 if (signal < 0)
3985 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3986 signals.push_back(signal);
3987
3988 packet.SkipSpaces();
3989 char separator = packet.GetChar();
3990 if (separator == '\0')
3991 break; // End of string
3992 if (separator != ';')
3993 return SendIllFormedResponse(packet, "Invalid separator,"
3994 " expected semicolon.");
3995 }
3996
3997 // Fail if we don't have a current process.
3998 if (!m_current_process)
3999 return SendErrorResponse(68);
4000
4001 Status error = m_current_process->IgnoreSignals(signals);
4002 if (error.Fail())
4003 return SendErrorResponse(69);
4004
4005 return SendOKResponse();
4006}
4007
4010 StringExtractorGDBRemote &packet) {
4011 Log *log = GetLog(LLDBLog::Process);
4012
4013 // Ensure we have a process.
4014 if (!m_current_process ||
4016 LLDB_LOGF(
4017 log,
4018 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4019 __FUNCTION__);
4020 return SendErrorResponse(1);
4021 }
4022
4023 // We are expecting
4024 // qMemTags:<hex address>,<hex length>:<hex type>
4025
4026 // Address
4027 packet.SetFilePos(strlen("qMemTags:"));
4028 const char *current_char = packet.Peek();
4029 if (!current_char || *current_char == ',')
4030 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
4031 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4032
4033 // Length
4034 char previous_char = packet.GetChar();
4035 current_char = packet.Peek();
4036 // If we don't have a separator or the length field is empty
4037 if (previous_char != ',' || (current_char && *current_char == ':'))
4038 return SendIllFormedResponse(packet,
4039 "Invalid addr,length pair in qMemTags packet");
4040
4041 if (packet.GetBytesLeft() < 1)
4042 return SendIllFormedResponse(
4043 packet, "Too short qMemtags: packet (looking for length)");
4044 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4045
4046 // Type
4047 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
4048 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4049 return SendIllFormedResponse(packet, invalid_type_err);
4050
4051 // Type is a signed integer but packed into the packet as its raw bytes.
4052 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
4053 const char *first_type_char = packet.Peek();
4054 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4055 return SendIllFormedResponse(packet, invalid_type_err);
4056
4057 // Extract type as unsigned then cast to signed.
4058 // Using a uint64_t here so that we have some value outside of the 32 bit
4059 // range to use as the invalid return value.
4060 uint64_t raw_type =
4061 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4062
4063 if ( // Make sure the cast below would be valid
4064 raw_type > std::numeric_limits<uint32_t>::max() ||
4065 // To catch inputs like "123aardvark" that will parse but clearly aren't
4066 // valid in this case.
4067 packet.GetBytesLeft()) {
4068 return SendIllFormedResponse(packet, invalid_type_err);
4069 }
4070
4071 // First narrow to 32 bits otherwise the copy into type would take
4072 // the wrong 4 bytes on big endian.
4073 uint32_t raw_type_32 = raw_type;
4074 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4075
4076 StreamGDBRemote response;
4077 std::vector<uint8_t> tags;
4078 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
4079 if (error.Fail())
4080 return SendErrorResponse(1);
4081
4082 // This m is here in case we want to support multi part replies in the future.
4083 // In the same manner as qfThreadInfo/qsThreadInfo.
4084 response.PutChar('m');
4085 response.PutBytesAsRawHex8(tags.data(), tags.size());
4086 return SendPacketNoLock(response.GetString());
4087}
4088
4091 StringExtractorGDBRemote &packet) {
4092 Log *log = GetLog(LLDBLog::Process);
4093
4094 // Ensure we have a process.
4095 if (!m_current_process ||
4097 LLDB_LOGF(
4098 log,
4099 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4100 __FUNCTION__);
4101 return SendErrorResponse(1);
4102 }
4103
4104 // We are expecting
4105 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
4106
4107 // Address
4108 packet.SetFilePos(strlen("QMemTags:"));
4109 const char *current_char = packet.Peek();
4110 if (!current_char || *current_char == ',')
4111 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
4112 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4113
4114 // Length
4115 char previous_char = packet.GetChar();
4116 current_char = packet.Peek();
4117 // If we don't have a separator or the length field is empty
4118 if (previous_char != ',' || (current_char && *current_char == ':'))
4119 return SendIllFormedResponse(packet,
4120 "Invalid addr,length pair in QMemTags packet");
4121
4122 if (packet.GetBytesLeft() < 1)
4123 return SendIllFormedResponse(
4124 packet, "Too short QMemtags: packet (looking for length)");
4125 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4126
4127 // Type
4128 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
4129 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4130 return SendIllFormedResponse(packet, invalid_type_err);
4131
4132 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
4133 const char *first_type_char = packet.Peek();
4134 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4135 return SendIllFormedResponse(packet, invalid_type_err);
4136
4137 // The type is a signed integer but is in the packet as its raw bytes.
4138 // So parse first as unsigned then cast to signed later.
4139 // We extract to 64 bit, even though we only expect 32, so that we've
4140 // got some invalid value we can check for.
4141 uint64_t raw_type =
4142 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4143 if (raw_type > std::numeric_limits<uint32_t>::max())
4144 return SendIllFormedResponse(packet, invalid_type_err);
4145
4146 // First narrow to 32 bits. Otherwise the copy below would get the wrong
4147 // 4 bytes on big endian.
4148 uint32_t raw_type_32 = raw_type;
4149 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4150
4151 // Tag data
4152 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4153 return SendIllFormedResponse(packet,
4154 "Missing tag data in QMemTags: packet");
4155
4156 // Must be 2 chars per byte
4157 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
4158 if (packet.GetBytesLeft() % 2)
4159 return SendIllFormedResponse(packet, invalid_data_err);
4160
4161 // This is bytes here and is unpacked into target specific tags later
4162 // We cannot assume that number of bytes == length here because the server
4163 // can repeat tags to fill a given range.
4164 std::vector<uint8_t> tag_data;
4165 // Zero length writes will not have any tag data
4166 // (but we pass them on because it will still check that tagging is enabled)
4167 if (packet.GetBytesLeft()) {
4168 size_t byte_count = packet.GetBytesLeft() / 2;
4169 tag_data.resize(byte_count);
4170 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
4171 if (converted_bytes != byte_count) {
4172 return SendIllFormedResponse(packet, invalid_data_err);
4173 }
4174 }
4175
4176 Status status =
4177 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
4178 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
4179}
4180
4183 StringExtractorGDBRemote &packet) {
4184 // Fail if we don't have a current process.
4185 if (!m_current_process ||
4187 return SendErrorResponse(Status::FromErrorString("Process not running."));
4188
4189 std::string path_hint;
4190
4191 StringRef packet_str{packet.GetStringRef()};
4192 assert(packet_str.starts_with("qSaveCore"));
4193 if (packet_str.consume_front("qSaveCore;")) {
4194 for (auto x : llvm::split(packet_str, ';')) {
4195 if (x.consume_front("path-hint:"))
4196 StringExtractor(x).GetHexByteString(path_hint);
4197 else
4198 return SendErrorResponse(
4199 Status::FromErrorString("Unsupported qSaveCore option"));
4200 }
4201 }
4202
4203 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
4204 if (!ret)
4205 return SendErrorResponse(ret.takeError());
4206
4207 StreamString response;
4208 response.PutCString("core-path:");
4209 response.PutStringAsRawHex8(ret.get());
4210 return SendPacketNoLock(response.GetString());
4211}
4212
4215 StringExtractorGDBRemote &packet) {
4216 Log *log = GetLog(LLDBLog::Process);
4217
4218 StringRef packet_str{packet.GetStringRef()};
4219 assert(packet_str.starts_with("QNonStop:"));
4220 packet_str.consume_front("QNonStop:");
4221 if (packet_str == "0") {
4222 if (m_non_stop)
4224 for (auto &process_it : m_debugged_processes) {
4225 if (process_it.second.process_up->IsRunning()) {
4226 assert(m_non_stop);
4227 Status error = process_it.second.process_up->Interrupt();
4228 if (error.Fail()) {
4229 LLDB_LOG(log,
4230 "while disabling nonstop, failed to halt process {0}: {1}",
4231 process_it.first, error);
4232 return SendErrorResponse(0x41);
4233 }
4234 // we must not send stop reasons after QNonStop
4235 m_disabling_non_stop = true;
4236 }
4237 }
4240 m_non_stop = false;
4241 // If we are stopping anything, defer sending the OK response until we're
4242 // done.
4244 return PacketResult::Success;
4245 } else if (packet_str == "1") {
4246 if (!m_non_stop)
4248 m_non_stop = true;
4249 } else
4250 return SendErrorResponse(
4251 Status::FromErrorString("Invalid QNonStop packet"));
4252 return SendOKResponse();
4253}
4254
4257 std::deque<std::string> &queue) {
4258 // Per the protocol, the first message put into the queue is sent
4259 // immediately. However, it remains the queue until the client ACKs it --
4260 // then we pop it and send the next message. The process repeats until
4261 // the last message in the queue is ACK-ed, in which case the packet sends
4262 // an OK response.
4263 if (queue.empty())
4264 return SendErrorResponse(
4265 Status::FromErrorString("No pending notification to ack"));
4266 queue.pop_front();
4267 if (!queue.empty())
4268 return SendPacketNoLock(queue.front());
4269 return SendOKResponse();
4270}
4271
4277
4280 StringExtractorGDBRemote &packet) {
4282 // If this was the last notification and all the processes exited,
4283 // terminate the server.
4284 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4285 m_exit_now = true;
4286 m_mainloop.RequestTermination();
4287 }
4288 return ret;
4289}
4290
4293 StringExtractorGDBRemote &packet) {
4294 if (!m_non_stop)
4295 return SendErrorResponse(
4296 Status::FromErrorString("vCtrl is only valid in non-stop mode"));
4297
4298 PacketResult interrupt_res = Handle_interrupt(packet);
4299 // If interrupting the process failed, pass the result through.
4300 if (interrupt_res != PacketResult::Success)
4301 return interrupt_res;
4302 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4303 return SendOKResponse();
4304}
4305
4308 packet.SetFilePos(strlen("T"));
4309 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4311 if (!pid_tid)
4312 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
4313
4314 lldb::pid_t pid = pid_tid->first;
4315 lldb::tid_t tid = pid_tid->second;
4316
4317 // Technically, this would also be caught by the PID check but let's be more
4318 // explicit about the error.
4319 if (pid == LLDB_INVALID_PROCESS_ID)
4320 return SendErrorResponse(
4321 llvm::createStringError("no current process and no PID provided"));
4322
4323 // Check the process ID and find respective process instance.
4324 auto new_process_it = m_debugged_processes.find(pid);
4325 if (new_process_it == m_debugged_processes.end())
4326 return SendErrorResponse(1);
4327
4328 // Check the thread ID
4329 if (!new_process_it->second.process_up->GetThreadByID(tid))
4330 return SendErrorResponse(2);
4331
4332 return SendOKResponse();
4333}
4334
4336 Log *log = GetLog(LLDBLog::Process);
4337
4338 // Tell the stdio connection to shut down.
4339 if (m_stdio_communication.IsConnected()) {
4340 auto connection = m_stdio_communication.GetConnection();
4341 if (connection) {
4342 Status error;
4343 connection->Disconnect(&error);
4344
4345 if (error.Success()) {
4346 LLDB_LOGF(log,
4347 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4348 "terminal stdio - SUCCESS",
4349 __FUNCTION__);
4350 } else {
4351 LLDB_LOGF(log,
4352 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4353 "terminal stdio - FAIL: %s",
4354 __FUNCTION__, error.AsCString());
4355 }
4356 }
4357 }
4358}
4359
4361 StringExtractorGDBRemote &packet) {
4362 // We have no thread if we don't have a process.
4363 if (!m_current_process ||
4365 return nullptr;
4366
4367 // If the client hasn't asked for thread suffix support, there will not be a
4368 // thread suffix. Use the current thread in that case.
4370 const lldb::tid_t current_tid = GetCurrentThreadID();
4371 if (current_tid == LLDB_INVALID_THREAD_ID)
4372 return nullptr;
4373 else if (current_tid == 0) {
4374 // Pick a thread.
4375 return m_current_process->GetThreadAtIndex(0);
4376 } else
4377 return m_current_process->GetThreadByID(current_tid);
4378 }
4379
4380 Log *log = GetLog(LLDBLog::Thread);
4381
4382 // Parse out the ';'.
4383 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4384 LLDB_LOGF(log,
4385 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4386 "error: expected ';' prior to start of thread suffix: packet "
4387 "contents = '%s'",
4388 __FUNCTION__, packet.GetStringRef().data());
4389 return nullptr;
4390 }
4391
4392 if (!packet.GetBytesLeft())
4393 return nullptr;
4394
4395 // Parse out thread: portion.
4396 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4397 LLDB_LOGF(log,
4398 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4399 "error: expected 'thread:' but not found, packet contents = "
4400 "'%s'",
4401 __FUNCTION__, packet.GetStringRef().data());
4402 return nullptr;
4403 }
4404 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4405 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4406 if (tid != 0)
4407 return m_current_process->GetThreadByID(tid);
4408
4409 return nullptr;
4410}
4411
4414 // Use whatever the debug process says is the current thread id since the
4415 // protocol either didn't specify or specified we want any/all threads
4416 // marked as the current thread.
4417 if (!m_current_process)
4419 return m_current_process->GetCurrentThreadID();
4420 }
4421 // Use the specific current thread id set by the gdb remote protocol.
4422 return m_current_tid;
4423}
4424
4426 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4428}
4429
4431 Log *log = GetLog(LLDBLog::Process);
4432
4433 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4434 m_xfer_buffer_map.clear();
4435}
4436
4439 const ArchSpec &arch) {
4440 if (m_current_process) {
4441 FileSpec file_spec;
4443 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4444 .Success()) {
4445 if (FileSystem::Instance().Exists(file_spec))
4446 return file_spec;
4447 }
4448 }
4449
4451}
4452
4454 llvm::StringRef value) {
4455 std::string result;
4456 for (const char &c : value) {
4457 switch (c) {
4458 case '\'':
4459 result += "&apos;";
4460 break;
4461 case '"':
4462 result += "&quot;";
4463 break;
4464 case '<':
4465 result += "&lt;";
4466 break;
4467 case '>':
4468 result += "&gt;";
4469 break;
4470 default:
4471 result += c;
4472 break;
4473 }
4474 }
4475 return result;
4476}
4477
4479 const llvm::ArrayRef<llvm::StringRef> client_features) {
4480 std::vector<std::string> ret =
4482 ret.insert(ret.end(), {
4483 "QThreadSuffixSupported+",
4484 "QListThreadsInStopReply+",
4485 "qXfer:features:read+",
4486 "QNonStop+",
4487 "jMultiBreakpoint+",
4488 });
4489
4490 // report server-only features
4491 using Extension = NativeProcessProtocol::Extension;
4492 Extension plugin_features = m_process_manager.GetSupportedExtensions();
4493 if (bool(plugin_features & Extension::pass_signals))
4494 ret.push_back("QPassSignals+");
4495 if (bool(plugin_features & Extension::auxv))
4496 ret.push_back("qXfer:auxv:read+");
4497 if (bool(plugin_features & Extension::libraries_svr4))
4498 ret.push_back("qXfer:libraries-svr4:read+");
4499 if (bool(plugin_features & Extension::libraries))
4500 ret.push_back("qXfer:libraries:read+");
4501 if (bool(plugin_features & Extension::siginfo_read))
4502 ret.push_back("qXfer:siginfo:read+");
4503 if (bool(plugin_features & Extension::memory_tagging))
4504 ret.push_back("memory-tagging+");
4505 if (bool(plugin_features & Extension::savecore))
4506 ret.push_back("qSaveCore+");
4507 if (!m_accelerator_plugins.empty())
4508 ret.push_back("accelerator-plugins+");
4509
4510 // check for client features
4512 for (llvm::StringRef x : client_features)
4514 llvm::StringSwitch<Extension>(x)
4515 .Case("multiprocess+", Extension::multiprocess)
4516 .Case("fork-events+", Extension::fork)
4517 .Case("vfork-events+", Extension::vfork)
4518 .Case("qXfer:libraries:read+", Extension::libraries)
4519 .Case("qXfer:libraries-svr4:read+", Extension::libraries_svr4)
4520 .Default({});
4521
4522 // We consume lldb's swbreak/hwbreak feature, but it doesn't change the
4523 // behaviour of lldb-server. We always adjust the program counter for targets
4524 // like x86
4525
4526 m_extensions_supported &= plugin_features;
4527
4528 // fork & vfork require multiprocess
4529 if (!bool(m_extensions_supported & Extension::multiprocess))
4530 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4531
4532 // report only if actually supported
4533 if (bool(m_extensions_supported & Extension::multiprocess))
4534 ret.push_back("multiprocess+");
4535 if (bool(m_extensions_supported & Extension::fork))
4536 ret.push_back("fork-events+");
4537 if (bool(m_extensions_supported & Extension::vfork))
4538 ret.push_back("vfork-events+");
4539
4540 for (auto &x : m_debugged_processes)
4541 SetEnabledExtensions(*x.second.process_up);
4542 return ret;
4543}
4544
4546 NativeProcessProtocol &process) {
4548 assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));
4549 process.SetEnabledExtensions(flags);
4550}
4551
4559
4561 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4562 if (bool(m_extensions_supported &
4564 response.Format("p{0:x-}.", pid);
4565 response.Format("{0:x-}", tid);
4566}
4567
4568std::string
4570 bool reverse_connect) {
4571 // Try parsing the argument as URL.
4572 if (std::optional<URI> url = URI::Parse(url_arg)) {
4573 if (reverse_connect)
4574 return url_arg.str();
4575
4576 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4577 // If the scheme doesn't match any, pass it through to support using CFD
4578 // schemes directly.
4579 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4580 .Case("tcp", "listen")
4581 .Case("unix", "unix-accept")
4582 .Case("unix-abstract", "unix-abstract-accept")
4583 .Default(url->scheme.str());
4584 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4585 return new_url;
4586 }
4587
4588 std::string host_port = url_arg.str();
4589 // If host_and_port starts with ':', default the host to be "localhost" and
4590 // expect the remainder to be the port.
4591 if (url_arg.starts_with(":"))
4592 host_port.insert(0, "localhost");
4593
4594 // Try parsing the (preprocessed) argument as host:port pair.
4595 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4596 return (reverse_connect ? "connect://" : "listen://") + host_port;
4597
4598 // If none of the above applied, interpret the argument as UNIX socket path.
4599 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4600 url_arg.str();
4601}
4602
4604 std::unique_ptr<LLDBServerAcceleratorPlugin> plugin_up) {
4605 m_accelerator_plugins.emplace_back(std::move(plugin_up));
4606}
4607
4611 std::vector<AcceleratorActions> accelerator_actions;
4612 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4614 if (auto actions = plugin_up->GetInitializeActions())
4615 accelerator_actions.push_back(std::move(*actions));
4616 }
4617 StreamGDBRemote response;
4618 response.PutAsJSONArray(accelerator_actions, /*hex_ascii=*/false);
4619 return SendPacketNoLock(response.GetString());
4620}
4621
4624 StringExtractorGDBRemote &packet) {
4625 packet.ConsumeFront("jAcceleratorPluginBreakpointHit:");
4626 llvm::Expected<AcceleratorBreakpointHitArgs> args =
4627 llvm::json::parse<AcceleratorBreakpointHitArgs>(
4628 packet.Peek(), "AcceleratorBreakpointHitArgs");
4629 if (!args)
4630 return SendErrorResponse(args.takeError());
4631
4632 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4634 if (plugin_up->GetPluginName() == args->plugin_name) {
4635 llvm::Expected<AcceleratorBreakpointHitResponse> bp_response =
4636 plugin_up->BreakpointWasHit(*args);
4637 if (!bp_response)
4638 return SendErrorResponse(bp_response.takeError());
4639
4640 StreamGDBRemote response;
4641 response.PutAsJSON(*bp_response, /*hex_ascii=*/false);
4642 return SendPacketNoLock(response.GetString());
4643 }
4644 }
4645 return SendErrorResponse(
4646 Status::FromErrorString("unknown accelerator plugin name"));
4647}
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