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
85
213
243 eServerPacketType_jAcceleratorPluginBreakpointHit,
248 eServerPacketType_jAcceleratorPluginGetDynamicLoaderLibraryInfo,
251
254
258
262
264 [this](StringExtractorGDBRemote packet, Status &error,
265 bool &interrupt, bool &quit) {
266 quit = true;
267 return this->Handle_k(packet);
268 });
269
273
277
290}
291
295
298
299 if (!m_process_launch_info.GetArguments().GetArgumentCount())
301 "%s: no process command line specified to launch", __FUNCTION__);
302
303 const bool should_forward_stdio =
304 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
305 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
306 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
307 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
308 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
309
310 if (should_forward_stdio) {
311#if defined(_WIN32)
313 m_process_launch_info.GetSTDIOWindowSize();
314 if (m_process_launch_info.IsSTDIOWindowSizeExplicit() &&
315 win_size.cols == 0 && win_size.rows == 0) {
316 if (llvm::Error Err = m_process_launch_info.SetUpPipeRedirection())
317 return Status::FromError(std::move(Err));
318 } else {
319 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
320 return Status::FromError(std::move(Err));
321 }
322#else
323 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
324 return Status::FromError(std::move(Err));
325#endif
326 }
327
328 {
329 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
330 assert(m_debugged_processes.empty() && "lldb-server creating debugged "
331 "process but one already exists");
332 auto process_or = m_process_manager.Launch(m_process_launch_info, *this);
333 if (!process_or)
334 return Status::FromError(process_or.takeError());
335 m_continue_process = m_current_process = process_or->get();
336 m_debugged_processes.emplace(
337 m_current_process->GetID(),
338 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
339 }
340
341 SetEnabledExtensions(*m_current_process);
342
343 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
344 // needed. llgs local-process debugging may specify PTY paths, which will
345 // make these file actions non-null process launch -i/e/o will also make
346 // these file actions non-null nullptr means that the traffic is expected to
347 // flow over gdb-remote protocol
348 if (should_forward_stdio) {
349 // nullptr means it's not redirected to file or pty (in case of LLGS local)
350 // at least one of stdio will be transferred pty<->gdb-remote we need to
351 // give the pty primary handle to this object to read and/or write
352 LLDB_LOG(log,
353 "pid = {0}: setting up stdout/stderr redirection via $O "
354 "gdb-remote commands",
355 m_current_process->GetID());
356
357 // Setup stdout/stderr mapping from inferior to $O
358 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
359 if (terminal_fd >= 0) {
360 LLDB_LOGF(log,
361 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
362 "inferior STDIO fd to %d",
363 __FUNCTION__, terminal_fd);
364 Status status = SetSTDIOFileDescriptor(terminal_fd);
365 if (status.Fail())
366 return status;
367 } else {
368 LLDB_LOGF(log,
369 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
370 "inferior STDIO since terminal fd reported as %d",
371 __FUNCTION__, terminal_fd);
372 }
373 } else {
374 LLDB_LOG(log,
375 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
376 "will communicate over client-provided file descriptors",
377 m_current_process->GetID());
378 }
379
380 printf("Launched '%s' as process %" PRIu64 "...\n",
381 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
382 m_current_process->GetID());
383
384 return Status();
385}
386
389 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
390 __FUNCTION__, pid);
391
392 // Before we try to attach, make sure we aren't already monitoring something
393 // else.
394 if (!m_debugged_processes.empty())
396 "cannot attach to process %" PRIu64
397 " when another process with pid %" PRIu64 " is being debugged.",
398 pid, m_current_process->GetID());
399
400 // Try to attach.
401 auto process_or = m_process_manager.Attach(pid, *this);
402 if (!process_or) {
403 Status status = Status::FromError(process_or.takeError());
404 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
405 status);
406 return status;
407 }
408 m_continue_process = m_current_process = process_or->get();
409 m_debugged_processes.emplace(
410 m_current_process->GetID(),
411 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
412 SetEnabledExtensions(*m_current_process);
413
414 // Setup stdout/stderr mapping from inferior.
415 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
416 if (terminal_fd >= 0) {
417 LLDB_LOGF(log,
418 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
419 "inferior STDIO fd to %d",
420 __FUNCTION__, terminal_fd);
421 Status status = SetSTDIOFileDescriptor(terminal_fd);
422 if (status.Fail())
423 return status;
424 } else {
425 LLDB_LOGF(log,
426 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
427 "inferior STDIO since terminal fd reported as %d",
428 __FUNCTION__, terminal_fd);
429 }
430
431 printf("Attached to process %" PRIu64 "...\n", pid);
432 return Status();
433}
434
436 llvm::StringRef process_name, bool include_existing) {
438
439 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
440
441 // Create the matcher used to search the process list.
442 ProcessInstanceInfoList exclusion_list;
443 ProcessInstanceInfoMatch match_info;
445 process_name, llvm::sys::path::Style::native);
447
448 if (include_existing) {
449 LLDB_LOG(log, "including existing processes in search");
450 } else {
451 // Create the excluded process list before polling begins.
452 Host::FindProcesses(match_info, exclusion_list);
453 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
454 exclusion_list.size());
455 }
456
457 LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
458
459 auto is_in_exclusion_list =
460 [&exclusion_list](const ProcessInstanceInfo &info) {
461 for (auto &excluded : exclusion_list) {
462 if (excluded.GetProcessID() == info.GetProcessID())
463 return true;
464 }
465 return false;
466 };
467
468 ProcessInstanceInfoList loop_process_list;
469 while (true) {
470 loop_process_list.clear();
471 if (Host::FindProcesses(match_info, loop_process_list)) {
472 // Remove all the elements that are in the exclusion list.
473 llvm::erase_if(loop_process_list, is_in_exclusion_list);
474
475 // One match! We found the desired process.
476 if (loop_process_list.size() == 1) {
477 auto matching_process_pid = loop_process_list[0].GetProcessID();
478 LLDB_LOG(log, "found pid {0}", matching_process_pid);
479 return AttachToProcess(matching_process_pid);
480 }
481
482 // Multiple matches! Return an error reporting the PIDs we found.
483 if (loop_process_list.size() > 1) {
484 StreamString error_stream;
485 error_stream.Format(
486 "Multiple executables with name: '{0}' found. Pids: ",
487 process_name);
488 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
489 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
490 }
491 error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
492
494 error = Status(error_stream.GetString().str());
495 return error;
496 }
497 }
498 // No matches, we have not found the process. Sleep until next poll.
499 LLDB_LOG(log, "sleep {0} seconds", polling_interval);
500 std::this_thread::sleep_for(polling_interval);
501 }
502}
503
505 NativeProcessProtocol *process) {
506 assert(process && "process cannot be NULL");
508 LLDB_LOGF(log,
509 "GDBRemoteCommunicationServerLLGS::%s called with "
510 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
511 __FUNCTION__, process->GetID(),
512 StateAsCString(process->GetState()));
513}
514
517 NativeProcessProtocol *process) {
518 assert(process && "process cannot be NULL");
520
521 // send W notification
522 auto wait_status = process->GetExitStatus();
523 if (!wait_status) {
524 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
525 process->GetID());
526
527 StreamGDBRemote response;
528 response.PutChar('E');
529 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
530 return SendPacketNoLock(response.GetString());
531 }
532
533 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
534 *wait_status);
535
536 // If the process was killed through vKill, return "OK".
537 if (bool(m_debugged_processes.at(process->GetID()).flags &
539 return SendOKResponse();
540
541 StreamGDBRemote response;
542 response.Format("{0:g}", *wait_status);
543 if (bool(m_extensions_supported &
545 response.Format(";process:{0:x-}", process->GetID());
546 if (m_non_stop)
548 response.GetString());
549 return SendPacketNoLock(response.GetString());
550}
551
552static void AppendHexValue(StreamString &response, const uint8_t *buf,
553 uint32_t buf_size, bool swap) {
554 int64_t i;
555 if (swap) {
556 for (i = buf_size - 1; i >= 0; i--)
557 response.PutHex8(buf[i]);
558 } else {
559 for (i = 0; i < buf_size; i++)
560 response.PutHex8(buf[i]);
561 }
562}
563
564static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo &reg_info) {
565 switch (reg_info.encoding) {
566 case eEncodingUint:
567 return "uint";
568 case eEncodingSint:
569 return "sint";
570 case eEncodingIEEE754:
571 return "ieee754";
572 case eEncodingVector:
573 return "vector";
574 default:
575 return "";
576 }
577}
578
579static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo &reg_info) {
580 switch (reg_info.format) {
581 case eFormatDefault:
582 return "";
583 case eFormatBoolean:
584 return "boolean";
585 case eFormatBinary:
586 return "binary";
587 case eFormatBytes:
588 return "bytes";
590 return "bytes-with-ascii";
591 case eFormatChar:
592 return "char";
594 return "char-printable";
595 case eFormatComplex:
596 return "complex";
597 case eFormatCString:
598 return "cstring";
599 case eFormatDecimal:
600 return "decimal";
601 case eFormatEnum:
602 return "enum";
603 case eFormatHex:
604 return "hex";
606 return "hex-uppercase";
607 case eFormatFloat:
608 return "float";
609 case eFormatOctal:
610 return "octal";
611 case eFormatOSType:
612 return "ostype";
613 case eFormatUnicode16:
614 return "unicode16";
615 case eFormatUnicode32:
616 return "unicode32";
617 case eFormatUnsigned:
618 return "unsigned";
619 case eFormatPointer:
620 return "pointer";
622 return "vector-char";
624 return "vector-sint64";
626 return "vector-float16";
628 return "vector-float64";
630 return "vector-sint8";
632 return "vector-uint8";
634 return "vector-sint16";
636 return "vector-uint16";
638 return "vector-sint32";
640 return "vector-uint32";
642 return "vector-float32";
644 return "vector-uint64";
646 return "vector-uint128";
648 return "complex-integer";
649 case eFormatCharArray:
650 return "char-array";
652 return "address-info";
653 case eFormatHexFloat:
654 return "hex-float";
656 return "instruction";
657 case eFormatVoid:
658 return "void";
659 case eFormatUnicode8:
660 return "unicode8";
661 case eFormatFloat128:
662 return "float128";
663 default:
664 llvm_unreachable("Unknown register format");
665 };
666}
667
668static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo &reg_info) {
669 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
671 return "pc";
673 return "sp";
675 return "fp";
677 return "ra";
679 return "flags";
681 return "arg1";
683 return "arg2";
685 return "arg3";
687 return "arg4";
689 return "arg5";
691 return "arg6";
693 return "arg7";
695 return "arg8";
697 return "tp";
698 default:
699 return "";
700 }
701}
702
703static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
704 bool usehex) {
705 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
706 if (i > 0)
707 response.PutChar(',');
708 if (usehex)
709 response.Printf("%" PRIx32, *reg_num);
710 else
711 response.Printf("%" PRIu32, *reg_num);
712 }
713}
714
716 StreamString &response, NativeRegisterContext &reg_ctx,
717 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
718 lldb::ByteOrder byte_order) {
719 RegisterValue reg_value;
720 if (!reg_value_p) {
721 Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
722 if (error.Success())
723 reg_value_p = &reg_value;
724 // else log.
725 }
726
727 if (reg_value_p) {
728 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
729 reg_value_p->GetByteSize(),
730 byte_order == lldb::eByteOrderLittle);
731 } else {
732 // Zero-out any unreadable values.
733 if (reg_info.byte_size > 0) {
734 std::vector<uint8_t> zeros(reg_info.byte_size, '\0');
735 AppendHexValue(response, zeros.data(), zeros.size(), false);
736 }
737 }
738}
739
740static std::optional<json::Object>
742 Log *log = GetLog(LLDBLog::Thread);
743
744 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
745
746 json::Object register_object;
747
748#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
749 const auto expedited_regs =
751#else
752 const auto expedited_regs =
754#endif
755 if (expedited_regs.empty())
756 return std::nullopt;
757
758 for (auto &reg_num : expedited_regs) {
759 const RegisterInfo *const reg_info_p =
760 reg_ctx.GetRegisterInfoAtIndex(reg_num);
761 if (reg_info_p == nullptr) {
762 LLDB_LOGF(log,
763 "%s failed to get register info for register index %" PRIu32,
764 __FUNCTION__, reg_num);
765 continue;
766 }
767
768 if (reg_info_p->value_regs != nullptr)
769 continue; // Only expedite registers that are not contained in other
770 // registers.
771
772 RegisterValue reg_value;
773 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
774 if (error.Fail()) {
775 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
776 __FUNCTION__,
777 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
778 reg_num, error.AsCString());
779 continue;
780 }
781
782 StreamString stream;
783 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
784 &reg_value, lldb::eByteOrderBig);
785
786 register_object.try_emplace(llvm::to_string(reg_num),
787 stream.GetString().str());
788 }
789
790 return register_object;
791}
792
793static const char *GetStopReasonString(StopReason stop_reason) {
794 switch (stop_reason) {
795 case eStopReasonTrace:
796 return "trace";
798 return "breakpoint";
800 return "watchpoint";
802 return "signal";
804 return "exception";
805 case eStopReasonExec:
806 return "exec";
808 return "processor trace";
809 case eStopReasonFork:
810 return "fork";
811 case eStopReasonVFork:
812 return "vfork";
814 return "vforkdone";
816 return "async interrupt";
818 return "dyld";
824 case eStopReasonNone:
825 break; // ignored
826 }
827 return nullptr;
828}
829
830static llvm::Expected<json::Array>
833
834 json::Array threads_array;
835
836 // Ensure we can get info on the given thread.
837 for (NativeThreadProtocol &thread : process.Threads()) {
838 lldb::tid_t tid = thread.GetID();
839 // Grab the reason this thread stopped.
840 struct ThreadStopInfo tid_stop_info;
841 std::string description;
842 if (!thread.GetStopReason(tid_stop_info, description))
843 return llvm::createStringError("failed to get stop reason");
844
845 const int signum = tid_stop_info.signo;
846 LLDB_LOGF(log,
847 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
848 " tid %" PRIu64
849 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
850 __FUNCTION__, process.GetID(), tid, signum, tid_stop_info.reason,
851 tid_stop_info.details.exception.type);
852
853 json::Object thread_obj;
854
855 if (!abridged) {
856 if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))
857 thread_obj.try_emplace("registers", std::move(*registers));
858 }
859
860 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
861
862 if (signum != 0)
863 thread_obj.try_emplace("signal", signum);
864
865 const std::string thread_name = thread.GetName();
866 if (!thread_name.empty())
867 thread_obj.try_emplace("name", thread_name);
868
869 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
870 if (stop_reason)
871 thread_obj.try_emplace("reason", stop_reason);
872
873 if (!description.empty())
874 thread_obj.try_emplace("description", description);
875
876 if ((tid_stop_info.reason == eStopReasonException) &&
877 tid_stop_info.details.exception.type) {
878 thread_obj.try_emplace(
879 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
880
881 json::Array medata_array;
882 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
883 ++i) {
884 medata_array.push_back(
885 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
886 }
887 thread_obj.try_emplace("medata", std::move(medata_array));
888 }
889 threads_array.push_back(std::move(thread_obj));
890 }
891 return threads_array;
892}
893
894StreamString
896 NativeThreadProtocol &thread) {
898
899 NativeProcessProtocol &process = thread.GetProcess();
900
901 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
902 thread.GetID());
903
904 // Grab the reason this thread stopped.
905 StreamString response;
906 struct ThreadStopInfo tid_stop_info;
907 std::string description;
908 if (!thread.GetStopReason(tid_stop_info, description))
909 return response;
910
911 // FIXME implement register handling for exec'd inferiors.
912 // if (tid_stop_info.reason == eStopReasonExec) {
913 // const bool force = true;
914 // InitializeRegisters(force);
915 // }
916
917 // Output the T packet with the thread
918 response.PutChar('T');
919 int signum = tid_stop_info.signo;
920 LLDB_LOG(
921 log,
922 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
923 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
924 tid_stop_info.details.exception.type);
925
926 // Print the signal number.
927 response.PutHex8(signum & 0xff);
928
929 // Include the (pid and) tid.
930 response.PutCString("thread:");
931 AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
932 response.PutChar(';');
933
934 // Include the thread name if there is one.
935 const std::string thread_name = thread.GetName();
936 if (!thread_name.empty()) {
937 size_t thread_name_len = thread_name.length();
938
939 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
940 response.PutCString("name:");
941 response.PutCString(thread_name);
942 } else {
943 // The thread name contains special chars, send as hex bytes.
944 response.PutCString("hexname:");
945 response.PutStringAsRawHex8(thread_name);
946 }
947 response.PutChar(';');
948 }
949
950 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
951 // send all thread IDs back in the "threads" key whose value is a list of hex
952 // thread IDs separated by commas:
953 // "threads:10a,10b,10c;"
954 // This will save the debugger from having to send a pair of qfThreadInfo and
955 // qsThreadInfo packets, but it also might take a lot of room in the stop
956 // reply packet, so it must be enabled only on systems where there are no
957 // limits on packet lengths.
959 response.PutCString("threads:");
960
961 uint32_t thread_num = 0;
962 for (NativeThreadProtocol &listed_thread : process.Threads()) {
963 if (thread_num > 0)
964 response.PutChar(',');
965 response.Printf("%" PRIx64, listed_thread.GetID());
966 ++thread_num;
967 }
968 response.PutChar(';');
969
970 // Include JSON info that describes the stop reason for any threads that
971 // actually have stop reasons. We use the new "jstopinfo" key whose values
972 // is hex ascii JSON that contains the thread IDs thread stop info only for
973 // threads that have stop reasons. Only send this if we have more than one
974 // thread otherwise this packet has all the info it needs.
975 if (thread_num > 1) {
976 const bool threads_with_valid_stop_info_only = true;
977 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
978 *m_current_process, threads_with_valid_stop_info_only);
979 if (threads_info) {
980 response.PutCString("jstopinfo:");
981 StreamString unescaped_response;
982 unescaped_response.AsRawOstream() << std::move(*threads_info);
983 response.PutStringAsRawHex8(unescaped_response.GetData());
984 response.PutChar(';');
985 } else {
986 LLDB_LOG_ERROR(log, threads_info.takeError(),
987 "failed to prepare a jstopinfo field for pid {1}: {0}",
988 process.GetID());
989 }
990 }
991
992 response.PutCString("thread-pcs");
993 char delimiter = ':';
994 for (NativeThreadProtocol &thread : process.Threads()) {
995 NativeRegisterContext &reg_ctx = thread.GetRegisterContext();
996
997 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
999 const RegisterInfo *const reg_info_p =
1000 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
1001
1002 RegisterValue reg_value;
1003 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
1004 if (error.Fail()) {
1005 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
1006 __FUNCTION__,
1007 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
1008 reg_to_read, error.AsCString());
1009 continue;
1010 }
1011
1012 response.PutChar(delimiter);
1013 delimiter = ',';
1014 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
1015 &reg_value, endian::InlHostByteOrder());
1016 }
1017
1018 response.PutChar(';');
1019 }
1020
1021 //
1022 // Expedite registers.
1023 //
1024
1025 // Grab the register context.
1026 NativeRegisterContext &reg_ctx = thread.GetRegisterContext();
1027 const auto expedited_regs =
1029
1030 for (auto &reg_num : expedited_regs) {
1031 const RegisterInfo *const reg_info_p =
1032 reg_ctx.GetRegisterInfoAtIndex(reg_num);
1033 // Only expediate registers that are not contained in other registers.
1034 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
1035 RegisterValue reg_value;
1036 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
1037 if (error.Success()) {
1038 response.Printf("%.02x:", reg_num);
1039 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
1040 &reg_value, lldb::eByteOrderBig);
1041 response.PutChar(';');
1042 } else {
1043 LLDB_LOGF(log,
1044 "GDBRemoteCommunicationServerLLGS::%s failed to read "
1045 "register '%s' index %" PRIu32 ": %s",
1046 __FUNCTION__,
1047 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
1048 reg_num, error.AsCString());
1049 }
1050 }
1051 }
1052
1053 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
1054 if (reason_str != nullptr) {
1055 response.Printf("reason:%s;", reason_str);
1056 }
1057
1058 if (!description.empty()) {
1059 // Description may contains special chars, send as hex bytes.
1060 response.PutCString("description:");
1061 response.PutStringAsRawHex8(description);
1062 response.PutChar(';');
1063 } else if ((tid_stop_info.reason == eStopReasonException) &&
1064 tid_stop_info.details.exception.type) {
1065 response.PutCString("metype:");
1066 response.PutHex64(tid_stop_info.details.exception.type);
1067 response.PutCString(";mecount:");
1068 response.PutHex32(tid_stop_info.details.exception.data_count);
1069 response.PutChar(';');
1070
1071 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
1072 response.PutCString("medata:");
1073 response.PutHex64(tid_stop_info.details.exception.data[i]);
1074 response.PutChar(';');
1075 }
1076 }
1077
1078 // Include child process PID/TID for forks.
1079 if (tid_stop_info.reason == eStopReasonFork ||
1080 tid_stop_info.reason == eStopReasonVFork) {
1081 assert(bool(m_extensions_supported &
1083 if (tid_stop_info.reason == eStopReasonFork)
1084 assert(bool(m_extensions_supported &
1086 if (tid_stop_info.reason == eStopReasonVFork)
1087 assert(bool(m_extensions_supported &
1089 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
1090 tid_stop_info.details.fork.child_pid,
1091 tid_stop_info.details.fork.child_tid);
1092 }
1093
1094 if (process.HasPendingLibraryEvents()) {
1095 // 1 is an arbitrary value here. The parameter is ignored.
1096 response.PutCString("library:1;");
1097 }
1098
1099 return response;
1100}
1101
1104 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1105 // Ensure we can get info on the given thread.
1106 NativeThreadProtocol *thread = process.GetThreadByID(tid);
1107 if (!thread)
1108 return SendErrorResponse(51);
1109
1111 if (response.Empty())
1112 return SendErrorResponse(42);
1113
1114 if (m_non_stop && !force_synchronous) {
1116 "Stop", m_stop_notification_queue, response.GetString());
1117 // Queue notification events for the remaining threads.
1119 return ret;
1120 }
1121
1122 return SendPacketNoLock(response.GetString());
1123}
1124
1126 lldb::tid_t thread_to_skip) {
1127 if (!m_non_stop)
1128 return;
1129
1130 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1131 if (listed_thread.GetID() != thread_to_skip) {
1132 StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1133 if (!stop_reply.Empty())
1134 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1135 }
1136 }
1137}
1138
1140 NativeProcessProtocol *process) {
1141 assert(process && "process cannot be NULL");
1142
1143 Log *log = GetLog(LLDBLog::Process);
1144 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1145
1146 if (std::optional<WaitStatus> exit_status = process->GetExitStatus())
1147 for (const std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin>
1148 &plugin_up : m_accelerator_plugins)
1149 plugin_up->NativeProcessDidExit(*exit_status);
1150
1152 *process, StateType::eStateExited, /*force_synchronous=*/false);
1153 if (result != PacketResult::Success) {
1154 LLDB_LOGF(log,
1155 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1156 "notification for PID %" PRIu64 ", state: eStateExited",
1157 __FUNCTION__, process->GetID());
1158 }
1159
1160 if (m_current_process == process)
1161 m_current_process = nullptr;
1162 if (m_continue_process == process)
1163 m_continue_process = nullptr;
1164
1165 lldb::pid_t pid = process->GetID();
1166 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1167 auto find_it = m_debugged_processes.find(pid);
1168 assert(find_it != m_debugged_processes.end());
1169 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1170 m_debugged_processes.erase(find_it);
1171 // Terminate the main loop only if vKill has not been used.
1172 // When running in non-stop mode, wait for the vStopped to clear
1173 // the notification queue.
1174 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1175 // Close the pipe to the inferior terminal i/o if we launched it and set
1176 // one up.
1178
1179 // We are ready to exit the debug monitor.
1180 m_exit_now = true;
1181 loop.RequestTermination();
1182 }
1183 });
1184}
1185
1187 NativeProcessProtocol *process) {
1188 assert(process && "process cannot be NULL");
1189
1190 Log *log = GetLog(LLDBLog::Process);
1191 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1192
1194 *process, StateType::eStateStopped, /*force_synchronous=*/false);
1195 if (result != PacketResult::Success) {
1196 LLDB_LOGF(log,
1197 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1198 "notification for PID %" PRIu64 ", state: eStateExited",
1199 __FUNCTION__, process->GetID());
1200 }
1201}
1202
1204 NativeProcessProtocol *process, lldb::StateType state) {
1205 assert(process && "process cannot be NULL");
1206 Log *log = GetLog(LLDBLog::Process);
1207 LLDB_LOGF(log,
1208 "GDBRemoteCommunicationServerLLGS::%s called with "
1209 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1210 __FUNCTION__, process->GetID(), StateAsCString(state));
1211
1212 switch (state) {
1214 break;
1215
1217 // Make sure we get all of the pending stdout/stderr from the inferior and
1218 // send it to the lldb host before we send the state change notification
1220 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1221 // does not interfere with our protocol.
1222 if (!m_non_stop)
1225 break;
1226
1228 // Same as above
1230 if (!m_non_stop)
1233 break;
1234
1235 default:
1236 LLDB_LOGF(log,
1237 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1238 "change for pid %" PRIu64 ", new state: %s",
1239 __FUNCTION__, process->GetID(), StateAsCString(state));
1240 break;
1241 }
1242}
1243
1247
1249 NativeProcessProtocol *parent_process,
1250 std::unique_ptr<NativeProcessProtocol> child_process) {
1251 lldb::pid_t child_pid = child_process->GetID();
1252 assert(child_pid != LLDB_INVALID_PROCESS_ID);
1253 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1254 m_debugged_processes.emplace(
1255 child_pid,
1256 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1257}
1258
1260 llvm::StringRef data) {
1261 if (data.empty())
1262 return;
1263
1264 {
1265 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
1266 m_pending_output_buffer.append(data.begin(), data.end());
1267 }
1268 m_mainloop.AddPendingCallback(
1269 [this](MainLoopBase &) { FlushPendingProcessOutput(); });
1270}
1271
1274 return;
1275
1276 std::string out;
1277 {
1278 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
1279 if (m_pending_output_buffer.empty())
1280 return;
1281 out.swap(m_pending_output_buffer);
1282 }
1283 SendONotification(out.data(), out.size());
1284}
1285
1287 Log *log = GetLog(GDBRLog::Comm);
1288
1289 bool interrupt = false;
1290 bool done = false;
1291 Status error;
1292 while (true) {
1294 std::chrono::microseconds(0), error, interrupt, done);
1295 if (result == PacketResult::ErrorReplyTimeout)
1296 break; // No more packets in the queue
1297
1298 if ((result != PacketResult::Success)) {
1299 LLDB_LOGF(log,
1300 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1301 "failed: %s",
1302 __FUNCTION__, error.AsCString());
1303 m_mainloop.RequestTermination();
1304 break;
1305 }
1306 }
1307}
1308
1310 std::unique_ptr<Connection> connection) {
1311 IOObjectSP read_object_sp = connection->GetReadObject();
1312 GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1313
1314 Status error;
1315 m_network_handle_up = m_mainloop.RegisterReadObject(
1316 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1317 error);
1318 return error;
1319}
1320
1323 const llvm::json::Value &value) {
1324 std::string json_string;
1325 raw_string_ostream os(json_string);
1326 os << value;
1327
1328 StreamGDBRemote escaped_response;
1329 escaped_response.PutCString("JSON-async:");
1330 escaped_response.PutEscapedBytes(json_string.c_str(), json_string.size());
1331 return SendPacketNoLock(escaped_response.GetString());
1332}
1333
1336 uint32_t len) {
1337 if ((buffer == nullptr) || (len == 0)) {
1338 // Nothing to send.
1339 return PacketResult::Success;
1340 }
1341
1342 StreamString response;
1343 response.PutChar('O');
1344 response.PutBytesAsRawHex8(buffer, len);
1345
1346 if (m_non_stop)
1348 response.GetString());
1349 return SendPacketNoLock(response.GetString());
1350}
1351
1353 Status error;
1354
1355 // Set up the reading/handling of process I/O
1356 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1357 new ConnectionFileDescriptor(fd, true));
1358 if (!conn_up) {
1359 error =
1360 Status::FromErrorString("failed to create ConnectionFileDescriptor");
1361 return error;
1362 }
1363
1364 m_stdio_communication.SetCloseOnEOF(false);
1365 m_stdio_communication.SetConnection(std::move(conn_up));
1366 if (!m_stdio_communication.IsConnected()) {
1368 "failed to set connection for inferior I/O communication");
1369 return error;
1370 }
1371
1372 return Status();
1373}
1374
1376 // Don't forward if not connected (e.g. when attaching).
1377 if (!m_stdio_communication.IsConnected())
1378 return;
1379
1380 Status error;
1381 assert(!m_stdio_handle_up);
1382 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1383 m_stdio_communication.GetConnection()->GetReadObject(),
1384 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1385
1386 if (!m_stdio_handle_up) {
1387 // Not much we can do about the failure. Log it and continue without
1388 // forwarding.
1389 if (Log *log = GetLog(LLDBLog::Process))
1390 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1391 }
1392}
1393
1397
1399 char buffer[1024];
1400 ConnectionStatus status;
1401 Status error;
1402 while (true) {
1403 size_t bytes_read = m_stdio_communication.Read(
1404 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1405 switch (status) {
1407 SendONotification(buffer, bytes_read);
1408 break;
1413 if (Log *log = GetLog(LLDBLog::Process))
1414 LLDB_LOGF(log,
1415 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1416 "forwarding as communication returned status %d (error: "
1417 "%s)",
1418 __FUNCTION__, status, error.AsCString());
1419 m_stdio_handle_up.reset();
1420 return;
1421
1424 return;
1425 }
1426 }
1427}
1428
1431 StringExtractorGDBRemote &packet) {
1432
1433 // Fail if we don't have a current process.
1434 if (!m_current_process ||
1436 return SendErrorResponse(Status::FromErrorString("Process not running."));
1437
1438 return SendJSONResponse(m_current_process->TraceSupported());
1439}
1440
1443 StringExtractorGDBRemote &packet) {
1444 // Fail if we don't have a current process.
1445 if (!m_current_process ||
1447 return SendErrorResponse(Status::FromErrorString("Process not running."));
1448
1449 packet.ConsumeFront("jLLDBTraceStop:");
1450 Expected<TraceStopRequest> stop_request =
1451 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1452 if (!stop_request)
1453 return SendErrorResponse(stop_request.takeError());
1454
1455 if (Error err = m_current_process->TraceStop(*stop_request))
1456 return SendErrorResponse(std::move(err));
1457
1458 return SendOKResponse();
1459}
1460
1463 StringExtractorGDBRemote &packet) {
1464
1465 // Fail if we don't have a current process.
1466 if (!m_current_process ||
1468 return SendErrorResponse(Status::FromErrorString("Process not running."));
1469
1470 packet.ConsumeFront("jLLDBTraceStart:");
1471 Expected<TraceStartRequest> request =
1472 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1473 if (!request)
1474 return SendErrorResponse(request.takeError());
1475
1476 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1477 return SendErrorResponse(std::move(err));
1478
1479 return SendOKResponse();
1480}
1481
1484 StringExtractorGDBRemote &packet) {
1485
1486 // Fail if we don't have a current process.
1487 if (!m_current_process ||
1489 return SendErrorResponse(Status::FromErrorString("Process not running."));
1490
1491 packet.ConsumeFront("jLLDBTraceGetState:");
1492 Expected<TraceGetStateRequest> request =
1493 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1494 if (!request)
1495 return SendErrorResponse(request.takeError());
1496
1497 return SendJSONResponse(m_current_process->TraceGetState(request->type));
1498}
1499
1502 StringExtractorGDBRemote &packet) {
1503
1504 // Fail if we don't have a current process.
1505 if (!m_current_process ||
1507 return SendErrorResponse(Status::FromErrorString("Process not running."));
1508
1509 packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1510 llvm::Expected<TraceGetBinaryDataRequest> request =
1511 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1512 "TraceGetBinaryDataRequest");
1513 if (!request)
1514 return SendErrorResponse(Status::FromError(request.takeError()));
1515
1516 if (Expected<std::vector<uint8_t>> bytes =
1517 m_current_process->TraceGetBinaryData(*request)) {
1518 StreamGDBRemote response;
1519 response.PutEscapedBytes(bytes->data(), bytes->size());
1520 return SendPacketNoLock(response.GetString());
1521 } else
1522 return SendErrorResponse(bytes.takeError());
1523}
1524
1527 StringExtractorGDBRemote &packet) {
1528 // Fail if we don't have a current process.
1529 if (!m_current_process ||
1531 return SendErrorResponse(68);
1532
1533 std::vector<std::string> structured_data_plugins =
1534 m_current_process->GetStructuredDataPlugins();
1535
1536 return SendJSONResponse(
1537 llvm::json::Value(llvm::json::Array(structured_data_plugins)));
1538}
1539
1542 StringExtractorGDBRemote &packet) {
1543 // Fail if we don't have a current process.
1544 if (!m_current_process ||
1546 return SendErrorResponse(68);
1547
1548 lldb::pid_t pid = m_current_process->GetID();
1549
1550 if (pid == LLDB_INVALID_PROCESS_ID)
1551 return SendErrorResponse(1);
1552
1553 ProcessInstanceInfo proc_info;
1554 if (!Host::GetProcessInfo(pid, proc_info))
1555 return SendErrorResponse(1);
1556
1557 StreamString response;
1558 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1559 return SendPacketNoLock(response.GetString());
1560}
1561
1564 // Fail if we don't have a current process.
1565 if (!m_current_process ||
1567 return SendErrorResponse(68);
1568
1569 // Make sure we set the current thread so g and p packets return the data the
1570 // gdb will expect.
1571 lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1572 SetCurrentThreadID(tid);
1573
1574 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1575 if (!thread)
1576 return SendErrorResponse(69);
1577
1578 StreamString response;
1579 response.PutCString("QC");
1581 thread->GetID());
1582
1583 return SendPacketNoLock(response.GetString());
1584}
1585
1588 Log *log = GetLog(LLDBLog::Process);
1589
1590 if (!m_non_stop)
1592
1593 if (m_debugged_processes.empty()) {
1594 LLDB_LOG(log, "No debugged process found.");
1595 return PacketResult::Success;
1596 }
1597
1598 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1599 ++it) {
1600 LLDB_LOG(log, "Killing process {0}", it->first);
1601 Status error = it->second.process_up->Kill();
1602 if (error.Fail())
1603 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1604 error);
1605 }
1606
1607 // The response to kill packet is undefined per the spec. LLDB
1608 // follows the same rules as for continue packets, i.e. no response
1609 // in all-stop mode, and "OK" in non-stop mode; in both cases this
1610 // is followed by the actual stop reason.
1612}
1613
1616 StringExtractorGDBRemote &packet) {
1617 if (!m_non_stop)
1619
1620 packet.SetFilePos(6); // vKill;
1621 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1622 if (pid == LLDB_INVALID_PROCESS_ID)
1623 return SendIllFormedResponse(packet,
1624 "vKill failed to parse the process id");
1625
1626 auto it = m_debugged_processes.find(pid);
1627 if (it == m_debugged_processes.end())
1628 return SendErrorResponse(42);
1629
1630 Status error = it->second.process_up->Kill();
1631 if (error.Fail())
1632 return SendErrorResponse(error.ToError());
1633
1634 // OK response is sent when the process dies.
1635 it->second.flags |= DebuggedProcess::Flag::vkilled;
1636 return PacketResult::Success;
1637}
1638
1641 StringExtractorGDBRemote &packet) {
1642 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1643 if (packet.GetU32(0))
1644 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1645 else
1646 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1647 return SendOKResponse();
1648}
1649
1652 StringExtractorGDBRemote &packet) {
1653 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1654 std::string path;
1655 packet.GetHexByteString(path);
1656 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1657 return SendOKResponse();
1658}
1659
1662 StringExtractorGDBRemote &packet) {
1663 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1664 if (working_dir) {
1665 StreamString response;
1666 response.PutStringAsRawHex8(working_dir.GetPath().c_str());
1667 return SendPacketNoLock(response.GetString());
1668 }
1669
1670 return SendErrorResponse(14);
1671}
1672
1679
1686
1689 NativeProcessProtocol &process, const ResumeActionList &actions) {
1691
1692 // In non-stop protocol mode, the process could be running already.
1693 // We do not support resuming threads independently, so just error out.
1694 if (!process.CanResume()) {
1695 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1696 process.GetState());
1697 return SendErrorResponse(0x37);
1698 }
1699
1700 Status error = process.Resume(actions);
1701 if (error.Fail()) {
1702 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1703 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1704 }
1705
1706 LLDB_LOG(log, "process {0} resumed", process.GetID());
1707
1708 return PacketResult::Success;
1709}
1710
1714 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1715
1716 // Ensure we have a native process.
1717 if (!m_continue_process) {
1718 LLDB_LOGF(log,
1719 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1720 "shared pointer",
1721 __FUNCTION__);
1722 return SendErrorResponse(0x36);
1723 }
1724
1725 // Pull out the signal number.
1726 packet.SetFilePos(::strlen("C"));
1727 if (packet.GetBytesLeft() < 1) {
1728 // Shouldn't be using a C without a signal.
1729 return SendIllFormedResponse(packet, "C packet specified without signal.");
1730 }
1731 const uint32_t signo =
1732 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1733 if (signo == std::numeric_limits<uint32_t>::max())
1734 return SendIllFormedResponse(packet, "failed to parse signal number");
1735
1736 // Handle optional continue address.
1737 if (packet.GetBytesLeft() > 0) {
1738 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1739 if (*packet.Peek() == ';')
1740 return SendUnimplementedResponse(packet.GetStringRef().data());
1741 else
1742 return SendIllFormedResponse(
1743 packet, "unexpected content after $C{signal-number}");
1744 }
1745
1746 // In non-stop protocol mode, the process could be running already.
1747 // We do not support resuming threads independently, so just error out.
1748 if (!m_continue_process->CanResume()) {
1749 LLDB_LOG(log, "process cannot be resumed (state={0})",
1750 m_continue_process->GetState());
1751 return SendErrorResponse(0x37);
1752 }
1753
1756 Status error;
1757
1758 // We have two branches: what to do if a continue thread is specified (in
1759 // which case we target sending the signal to that thread), or when we don't
1760 // have a continue thread set (in which case we send a signal to the
1761 // process).
1762
1763 // TODO discuss with Greg Clayton, make sure this makes sense.
1764
1765 lldb::tid_t signal_tid = GetContinueThreadID();
1766 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1767 // The resume action for the continue thread (or all threads if a continue
1768 // thread is not set).
1770 static_cast<int>(signo)};
1771
1772 // Add the action for the continue thread (or all threads when the continue
1773 // thread isn't present).
1774 resume_actions.Append(action);
1775 } else {
1776 // Send the signal to the process since we weren't targeting a specific
1777 // continue thread with the signal.
1778 error = m_continue_process->Signal(signo);
1779 if (error.Fail()) {
1780 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1781 m_continue_process->GetID(), error);
1782
1783 return SendErrorResponse(0x52);
1784 }
1785 }
1786
1787 // NB: this checks CanResume() twice but using a single code path for
1788 // resuming still seems worth it.
1789 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1790 if (resume_res != PacketResult::Success)
1791 return resume_res;
1792
1793 // Don't send an "OK" packet, except in non-stop mode;
1794 // otherwise, the response is the stopped/exited message.
1796}
1797
1801 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1802
1803 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1804
1805 // For now just support all continue.
1806 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1807 if (has_continue_address) {
1808 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1809 packet.Peek());
1810 return SendUnimplementedResponse(packet.GetStringRef().data());
1811 }
1812
1813 // Ensure we have a native process.
1814 if (!m_continue_process) {
1815 LLDB_LOGF(log,
1816 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1817 "shared pointer",
1818 __FUNCTION__);
1819 return SendErrorResponse(0x36);
1820 }
1821
1822 // Build the ResumeActionList
1825
1826 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1827 if (resume_res != PacketResult::Success)
1828 return resume_res;
1829
1831}
1832
1835 StringExtractorGDBRemote &packet) {
1836 StreamString response;
1837 response.Printf("vCont;c;C;s;S;t");
1838
1839 return SendPacketNoLock(response.GetString());
1840}
1841
1843 // We're doing a stop-all if and only if our only action is a "t" for all
1844 // threads.
1845 if (const ResumeAction *default_action =
1847 if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1848 return true;
1849 }
1850
1851 return false;
1852}
1853
1856 StringExtractorGDBRemote &packet) {
1857 Log *log = GetLog(LLDBLog::Process);
1858 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1859 __FUNCTION__);
1860
1861 packet.SetFilePos(::strlen("vCont"));
1862
1863 if (packet.GetBytesLeft() == 0) {
1864 LLDB_LOGF(log,
1865 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1866 "vCont package",
1867 __FUNCTION__);
1868 return SendIllFormedResponse(packet, "Missing action from vCont package");
1869 }
1870
1871 if (::strcmp(packet.Peek(), ";s") == 0) {
1872 // Move past the ';', then do a simple 's'.
1873 packet.SetFilePos(packet.GetFilePos() + 1);
1874 return Handle_s(packet);
1875 }
1876
1877 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1878
1879 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1880 // Skip the semi-colon.
1881 packet.GetChar();
1882
1883 // Build up the thread action.
1884 ResumeAction thread_action;
1885 thread_action.tid = LLDB_INVALID_THREAD_ID;
1886 thread_action.state = eStateInvalid;
1887 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1888
1889 const char action = packet.GetChar();
1890 switch (action) {
1891 case 'C':
1892 thread_action.signal = packet.GetHexMaxU32(false, 0);
1893 if (thread_action.signal == 0)
1894 return SendIllFormedResponse(
1895 packet, "Could not parse signal in vCont packet C action");
1896 [[fallthrough]];
1897
1898 case 'c':
1899 // Continue
1900 thread_action.state = eStateRunning;
1901 break;
1902
1903 case 'S':
1904 thread_action.signal = packet.GetHexMaxU32(false, 0);
1905 if (thread_action.signal == 0)
1906 return SendIllFormedResponse(
1907 packet, "Could not parse signal in vCont packet S action");
1908 [[fallthrough]];
1909
1910 case 's':
1911 // Step
1912 thread_action.state = eStateStepping;
1913 break;
1914
1915 case 't':
1916 // Stop
1917 thread_action.state = eStateSuspended;
1918 break;
1919
1920 default:
1921 return SendIllFormedResponse(packet, "Unsupported vCont action");
1922 break;
1923 }
1924
1925 // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".
1928
1929 // Parse out optional :{thread-id} value.
1930 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1931 // Consume the separator.
1932 packet.GetChar();
1933
1934 auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);
1935 if (!pid_tid)
1936 return SendIllFormedResponse(packet, "Malformed thread-id");
1937
1938 pid = pid_tid->first;
1939 tid = pid_tid->second;
1940 }
1941
1942 if (thread_action.state == eStateSuspended &&
1944 return SendIllFormedResponse(
1945 packet, "'t' action not supported for individual threads");
1946 }
1947
1948 // If we get TID without PID, it's the current process.
1949 if (pid == LLDB_INVALID_PROCESS_ID) {
1950 if (!m_continue_process) {
1951 LLDB_LOG(log, "no process selected via Hc");
1952 return SendErrorResponse(0x36);
1953 }
1954 pid = m_continue_process->GetID();
1955 }
1956
1957 assert(pid != LLDB_INVALID_PROCESS_ID);
1960 thread_action.tid = tid;
1961
1963 if (tid != LLDB_INVALID_THREAD_ID)
1964 return SendIllFormedResponse(
1965 packet, "vCont: p-1 is not valid with a specific tid");
1966 for (auto &process_it : m_debugged_processes)
1967 thread_actions[process_it.first].Append(thread_action);
1968 } else
1969 thread_actions[pid].Append(thread_action);
1970 }
1971
1972 assert(thread_actions.size() >= 1);
1973 if (thread_actions.size() > 1 && !m_non_stop)
1974 return SendIllFormedResponse(
1975 packet,
1976 "Resuming multiple processes is supported in non-stop mode only");
1977
1978 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1979 auto process_it = m_debugged_processes.find(x.first);
1980 if (process_it == m_debugged_processes.end()) {
1981 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1982 x.first);
1983 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1984 }
1985
1986 // There are four possible scenarios here. These are:
1987 // 1. vCont on a stopped process that resumes at least one thread.
1988 // In this case, we call Resume().
1989 // 2. vCont on a stopped process that leaves all threads suspended.
1990 // A no-op.
1991 // 3. vCont on a running process that requests suspending all
1992 // running threads. In this case, we call Interrupt().
1993 // 4. vCont on a running process that requests suspending a subset
1994 // of running threads or resuming a subset of suspended threads.
1995 // Since we do not support full nonstop mode, this is unsupported
1996 // and we return an error.
1997
1998 assert(process_it->second.process_up);
1999 if (ResumeActionListStopsAllThreads(x.second)) {
2000 if (process_it->second.process_up->IsRunning()) {
2001 assert(m_non_stop);
2002
2003 Status error = process_it->second.process_up->Interrupt();
2004 if (error.Fail()) {
2005 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
2006 error);
2007 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2008 }
2009
2010 LLDB_LOG(log, "halted process {0}", x.first);
2011
2012 // hack to avoid enabling stdio forwarding after stop
2013 // TODO: remove this when we improve stdio forwarding for nonstop
2014 assert(thread_actions.size() == 1);
2015 return SendOKResponse();
2016 }
2017 } else {
2018 PacketResult resume_res =
2019 ResumeProcess(*process_it->second.process_up, x.second);
2020 if (resume_res != PacketResult::Success)
2021 return resume_res;
2022 }
2023 }
2024
2026}
2027
2029 Log *log = GetLog(LLDBLog::Thread);
2030 LLDB_LOG(log, "setting current thread id to {0}", tid);
2031
2032 m_current_tid = tid;
2034 m_current_process->SetCurrentThreadID(m_current_tid);
2035}
2036
2038 Log *log = GetLog(LLDBLog::Thread);
2039 LLDB_LOG(log, "setting continue thread id to {0}", tid);
2040
2041 m_continue_tid = tid;
2042}
2043
2046 StringExtractorGDBRemote &packet) {
2047 // Handle the $? gdbremote command.
2048
2049 if (m_non_stop) {
2050 // Clear the notification queue first, except for pending exit
2051 // notifications.
2052 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
2053 return x.front() != 'W' && x.front() != 'X';
2054 });
2055
2056 if (m_current_process) {
2057 // Queue stop reply packets for all active threads. Start with
2058 // the current thread (for clients that don't actually support multiple
2059 // stop reasons).
2060 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
2061 if (thread) {
2062 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
2063 if (!stop_reply.Empty())
2064 m_stop_notification_queue.push_back(stop_reply.GetString().str());
2065 }
2066 EnqueueStopReplyPackets(thread ? thread->GetID()
2068 }
2069
2070 // If the notification queue is empty (i.e. everything is running), send OK.
2071 if (m_stop_notification_queue.empty())
2072 return SendOKResponse();
2073
2074 // Send the first item from the new notification queue synchronously.
2076 }
2077
2078 // If no process, indicate error
2079 if (!m_current_process)
2080 return SendErrorResponse(02);
2081
2083 m_current_process->GetState(),
2084 /*force_synchronous=*/true);
2085}
2086
2089 NativeProcessProtocol &process, lldb::StateType process_state,
2090 bool force_synchronous) {
2091 Log *log = GetLog(LLDBLog::Process);
2092
2093 {
2094 std::string out;
2095 {
2096 std::lock_guard<std::mutex> lock(m_pending_output_mutex);
2097 out.swap(m_pending_output_buffer);
2098 }
2099 if (!out.empty())
2100 SendONotification(out.data(), out.size());
2101 }
2102
2104 // Check if we are waiting for any more processes to stop. If we are,
2105 // do not send the OK response yet.
2106 for (const auto &it : m_debugged_processes) {
2107 if (it.second.process_up->IsRunning())
2108 return PacketResult::Success;
2109 }
2110
2111 // If all expected processes were stopped after a QNonStop:0 request,
2112 // send the OK response.
2113 m_disabling_non_stop = false;
2114 return SendOKResponse();
2115 }
2116
2117 switch (process_state) {
2118 case eStateAttaching:
2119 case eStateLaunching:
2120 case eStateRunning:
2121 case eStateStepping:
2122 case eStateDetached:
2123 // NOTE: gdb protocol doc looks like it should return $OK
2124 // when everything is running (i.e. no stopped result).
2125 return PacketResult::Success; // Ignore
2126
2127 case eStateSuspended:
2128 case eStateStopped:
2129 case eStateCrashed: {
2130 lldb::tid_t tid = process.GetCurrentThreadID();
2131 // Make sure we set the current thread so g and p packets return the data
2132 // the gdb will expect.
2133 SetCurrentThreadID(tid);
2134 return SendStopReplyPacketForThread(process, tid, force_synchronous);
2135 }
2136
2137 case eStateInvalid:
2138 case eStateUnloaded:
2139 case eStateExited:
2140 return SendWResponse(&process);
2141
2142 default:
2143 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
2144 process.GetID(), process_state);
2145 break;
2146 }
2147
2148 return SendErrorResponse(0);
2149}
2150
2153 StringExtractorGDBRemote &packet) {
2154 // Fail if we don't have a current process.
2155 if (!m_current_process ||
2157 return SendErrorResponse(68);
2158
2159 // Ensure we have a thread.
2160 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
2161 if (!thread)
2162 return SendErrorResponse(69);
2163
2164 // Get the register context for the first thread.
2165 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2166
2167 // Parse out the register number from the request.
2168 packet.SetFilePos(strlen("qRegisterInfo"));
2169 const uint32_t reg_index =
2170 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2171 if (reg_index == std::numeric_limits<uint32_t>::max())
2172 return SendErrorResponse(69);
2173
2174 // Return the end of registers response if we've iterated one past the end of
2175 // the register set.
2176 if (reg_index >= reg_context.GetUserRegisterCount())
2177 return SendErrorResponse(69);
2178
2179 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2180 if (!reg_info)
2181 return SendErrorResponse(69);
2182
2183 // Build the reginfos response.
2184 StreamGDBRemote response;
2185
2186 response.PutCString("name:");
2187 response.PutCString(reg_info->name);
2188 response.PutChar(';');
2189
2190 if (reg_info->alt_name && reg_info->alt_name[0]) {
2191 response.PutCString("alt-name:");
2192 response.PutCString(reg_info->alt_name);
2193 response.PutChar(';');
2194 }
2195
2196 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2197
2198 if (!reg_context.RegisterOffsetIsDynamic())
2199 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2200
2201 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2202 if (!encoding.empty())
2203 response << "encoding:" << encoding << ';';
2204
2205 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2206 if (!format.empty())
2207 response << "format:" << format << ';';
2208
2209 const char *const register_set_name =
2210 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2211 if (register_set_name)
2212 response << "set:" << register_set_name << ';';
2213 else
2214 response << "set:general;";
2215
2218 response.Printf("ehframe:%" PRIu32 ";",
2220
2222 response.Printf("dwarf:%" PRIu32 ";",
2224
2225 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2226 if (!kind_generic.empty())
2227 response << "generic:" << kind_generic << ';';
2228
2229 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2230 response.PutCString("container-regs:");
2231 CollectRegNums(reg_info->value_regs, response, true);
2232 response.PutChar(';');
2233 }
2234
2235 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2236 response.PutCString("invalidate-regs:");
2237 CollectRegNums(reg_info->invalidate_regs, response, true);
2238 response.PutChar(';');
2239 }
2240
2241 return SendPacketNoLock(response.GetString());
2242}
2243
2245 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2246 Log *log = GetLog(LLDBLog::Thread);
2247
2248 lldb::pid_t pid = process.GetID();
2249 if (pid == LLDB_INVALID_PROCESS_ID)
2250 return;
2251
2252 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2253 for (NativeThreadProtocol &thread : process.Threads()) {
2254 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2255 response.PutChar(had_any ? ',' : 'm');
2256 AppendThreadIDToResponse(response, pid, thread.GetID());
2257 had_any = true;
2258 }
2259}
2260
2263 StringExtractorGDBRemote &packet) {
2264 assert(m_debugged_processes.size() <= 1 ||
2267
2268 bool had_any = false;
2269 StreamGDBRemote response;
2270
2271 for (auto &pid_ptr : m_debugged_processes)
2272 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2273
2274 if (!had_any)
2275 return SendOKResponse();
2276 return SendPacketNoLock(response.GetString());
2277}
2278
2281 StringExtractorGDBRemote &packet) {
2282 // FIXME for now we return the full thread list in the initial packet and
2283 // always do nothing here.
2284 return SendPacketNoLock("l");
2285}
2286
2289 Log *log = GetLog(LLDBLog::Thread);
2290
2291 // Move past packet name.
2292 packet.SetFilePos(strlen("g"));
2293
2294 // Get the thread to use.
2295 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2296 if (!thread) {
2297 LLDB_LOG(log, "failed, no thread available");
2298 return SendErrorResponse(0x15);
2299 }
2300
2301 // Get the thread's register context.
2302 NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
2303
2304 std::vector<uint8_t> regs_buffer;
2305 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2306 ++reg_num) {
2307 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2308
2309 if (reg_info == nullptr) {
2310 LLDB_LOG(log, "failed to get register info for register index {0}",
2311 reg_num);
2312 return SendErrorResponse(0x15);
2313 }
2314
2315 if (reg_info->value_regs != nullptr)
2316 continue; // skip registers that are contained in other registers
2317
2318 RegisterValue reg_value;
2319 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2320 if (error.Fail()) {
2321 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2322 return SendErrorResponse(0x15);
2323 }
2324
2325 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2326 // Resize the buffer to guarantee it can store the register offsetted
2327 // data.
2328 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2329
2330 // Copy the register offsetted data to the buffer.
2331 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2332 reg_info->byte_size);
2333 }
2334
2335 // Write the response.
2336 StreamGDBRemote response;
2337 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2338
2339 return SendPacketNoLock(response.GetString());
2340}
2341
2344 Log *log = GetLog(LLDBLog::Thread);
2345
2346 // Parse out the register number from the request.
2347 packet.SetFilePos(strlen("p"));
2348 const uint32_t reg_index =
2349 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2350 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2351 LLDB_LOGF(log,
2352 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2353 "parse register number from request \"%s\"",
2354 __FUNCTION__, packet.GetStringRef().data());
2355 return SendErrorResponse(0x15);
2356 }
2357
2358 // Get the thread to use.
2359 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2360 if (!thread) {
2361 LLDB_LOG(log, "failed, no thread available");
2362 return SendErrorResponse(0x15);
2363 }
2364
2365 // Get the thread's register context.
2366 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2367
2368 // Return the end of registers response if we've iterated one past the end of
2369 // the register set.
2370 if (reg_index >= reg_context.GetUserRegisterCount()) {
2371 LLDB_LOGF(log,
2372 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2373 "register %" PRIu32 " beyond register count %" PRIu32,
2374 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2375 return SendErrorResponse(0x15);
2376 }
2377
2378 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2379 if (!reg_info) {
2380 LLDB_LOGF(log,
2381 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2382 "register %" PRIu32 " returned NULL",
2383 __FUNCTION__, reg_index);
2384 return SendErrorResponse(0x15);
2385 }
2386
2387 // Build the reginfos response.
2388 StreamGDBRemote response;
2389
2390 // Retrieve the value
2391 RegisterValue reg_value;
2392 Status error = reg_context.ReadRegister(reg_info, reg_value);
2393 if (error.Fail()) {
2394 LLDB_LOGF(log,
2395 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2396 "requested register %" PRIu32 " (%s) failed: %s",
2397 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2398 return SendErrorResponse(0x15);
2399 }
2400
2401 const uint8_t *const data =
2402 static_cast<const uint8_t *>(reg_value.GetBytes());
2403 if (!data) {
2404 LLDB_LOGF(log,
2405 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2406 "bytes from requested register %" PRIu32,
2407 __FUNCTION__, reg_index);
2408 return SendErrorResponse(0x15);
2409 }
2410
2411 // FIXME flip as needed to get data in big/little endian format for this host.
2412 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2413 response.PutHex8(data[i]);
2414
2415 return SendPacketNoLock(response.GetString());
2416}
2417
2420 Log *log = GetLog(LLDBLog::Thread);
2421
2422 // Ensure there is more content.
2423 if (packet.GetBytesLeft() < 1)
2424 return SendIllFormedResponse(packet, "Empty P packet");
2425
2426 // Parse out the register number from the request.
2427 packet.SetFilePos(strlen("P"));
2428 const uint32_t reg_index =
2429 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2430 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2431 LLDB_LOGF(log,
2432 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2433 "parse register number from request \"%s\"",
2434 __FUNCTION__, packet.GetStringRef().data());
2435 return SendErrorResponse(0x29);
2436 }
2437
2438 // Note debugserver would send an E30 here.
2439 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2440 return SendIllFormedResponse(
2441 packet, "P packet missing '=' char after register number");
2442
2443 // Parse out the value.
2444 size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);
2445
2446 // Get the thread to use.
2447 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2448 if (!thread) {
2449 LLDB_LOGF(log,
2450 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2451 "available (thread index 0)",
2452 __FUNCTION__);
2453 return SendErrorResponse(0x28);
2454 }
2455
2456 // Get the thread's register context.
2457 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2458 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2459 if (!reg_info) {
2460 LLDB_LOGF(log,
2461 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2462 "register %" PRIu32 " returned NULL",
2463 __FUNCTION__, reg_index);
2464 return SendErrorResponse(0x48);
2465 }
2466
2467 // Return the end of registers response if we've iterated one past the end of
2468 // the register set.
2469 if (reg_index >= reg_context.GetUserRegisterCount()) {
2470 LLDB_LOGF(log,
2471 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2472 "register %" PRIu32 " beyond register count %" PRIu32,
2473 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2474 return SendErrorResponse(0x47);
2475 }
2476
2477 if (reg_size != reg_info->byte_size)
2478 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2479
2480 // Build the reginfos response.
2481 StreamGDBRemote response;
2482
2483 RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),
2484 m_current_process->GetArchitecture().GetByteOrder());
2485 Status error = reg_context.WriteRegister(reg_info, reg_value);
2486 if (error.Fail()) {
2487 LLDB_LOGF(log,
2488 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2489 "requested register %" PRIu32 " (%s) failed: %s",
2490 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2491 return SendErrorResponse(0x32);
2492 }
2493
2494 return SendOKResponse();
2495}
2496
2499 Log *log = GetLog(LLDBLog::Thread);
2500
2501 // Parse out which variant of $H is requested.
2502 packet.SetFilePos(strlen("H"));
2503 if (packet.GetBytesLeft() < 1) {
2504 LLDB_LOGF(log,
2505 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2506 "missing {g,c} variant",
2507 __FUNCTION__);
2508 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2509 }
2510
2511 const char h_variant = packet.GetChar();
2512 NativeProcessProtocol *default_process;
2513 switch (h_variant) {
2514 case 'g':
2515 default_process = m_current_process;
2516 break;
2517
2518 case 'c':
2519 default_process = m_continue_process;
2520 break;
2521
2522 default:
2523 LLDB_LOGF(
2524 log,
2525 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2526 __FUNCTION__, h_variant);
2527 return SendIllFormedResponse(packet,
2528 "H variant unsupported, should be c or g");
2529 }
2530
2531 // Parse out the thread number.
2532 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2534 if (!pid_tid)
2535 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
2536
2537 lldb::pid_t pid = pid_tid->first;
2538 lldb::tid_t tid = pid_tid->second;
2539
2541 return SendUnimplementedResponse("Selecting all processes not supported");
2542 if (pid == LLDB_INVALID_PROCESS_ID)
2543 return SendErrorResponse(
2544 llvm::createStringError("no current process and no PID provided"));
2545
2546 // Check the process ID and find respective process instance.
2547 auto new_process_it = m_debugged_processes.find(pid);
2548 if (new_process_it == m_debugged_processes.end())
2549 return SendErrorResponse(
2550 llvm::createStringErrorV("no process with PID {0} debugged", pid));
2551
2552 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2553 // (any thread).
2554 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2555 NativeThreadProtocol *thread =
2556 new_process_it->second.process_up->GetThreadByID(tid);
2557 if (!thread) {
2558 LLDB_LOGF(log,
2559 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2560 " not found",
2561 __FUNCTION__, tid);
2562 return SendErrorResponse(0x15);
2563 }
2564 }
2565
2566 // Now switch the given process and thread type.
2567 switch (h_variant) {
2568 case 'g':
2569 m_current_process = new_process_it->second.process_up.get();
2570 SetCurrentThreadID(tid);
2571 break;
2572
2573 case 'c':
2574 m_continue_process = new_process_it->second.process_up.get();
2576 break;
2577
2578 default:
2579 assert(false && "unsupported $H variant - shouldn't get here");
2580 return SendIllFormedResponse(packet,
2581 "H variant unsupported, should be c or g");
2582 }
2583
2584 return SendOKResponse();
2585}
2586
2589 Log *log = GetLog(LLDBLog::Thread);
2590
2591 // Fail if we don't have a current process.
2592 if (!m_current_process ||
2594 LLDB_LOGF(
2595 log,
2596 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2597 __FUNCTION__);
2598 return SendErrorResponse(0x15);
2599 }
2600
2601 packet.SetFilePos(::strlen("I"));
2602 uint8_t tmp[4096];
2603 for (;;) {
2604 size_t read = packet.GetHexBytesAvail(tmp);
2605 if (read == 0) {
2606 break;
2607 }
2608 // write directly to stdin *this might block if stdin buffer is full*
2609 // TODO: enqueue this block in circular buffer and send window size to
2610 // remote host
2611 Status error;
2612
2613#if defined(_WIN32)
2614 // On Windows the inferior's stdio is owned by NativeProcessWindows (which
2615 // holds the ConPTY). Route stdin through NativeProcessProtocol::WriteStdin
2616 // rather than m_stdio_communication, which is unconnected on Windows.
2617 if (m_current_process->WriteStdin(tmp, read, error) != read || error.Fail())
2618 return SendErrorResponse(0x15);
2619#else
2620 ConnectionStatus status;
2621 m_stdio_communication.WriteAll(tmp, read, status, &error);
2622 if (error.Fail()) {
2623 return SendErrorResponse(0x15);
2624 }
2625#endif
2626 }
2627
2628 return SendOKResponse();
2629}
2630
2633 StringExtractorGDBRemote &packet) {
2635
2636 // Fail if we don't have a current process.
2637 if (!m_current_process ||
2639 LLDB_LOG(log, "failed, no process available");
2640 return SendErrorResponse(0x15);
2641 }
2642
2643 // Interrupt the process.
2644 Status error = m_current_process->Interrupt();
2645 if (error.Fail()) {
2646 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2647 error);
2648 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2649 }
2650
2651 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2652
2653 // No response required from stop all.
2654 return PacketResult::Success;
2655}
2656
2659 StringExtractorGDBRemote &packet) {
2660 Log *log = GetLog(LLDBLog::Process);
2661
2662 if (!m_current_process ||
2664 LLDB_LOGF(
2665 log,
2666 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2667 __FUNCTION__);
2668 return SendErrorResponse(0x15);
2669 }
2670
2671 // Parse out the memory address.
2672 packet.SetFilePos(strlen("m"));
2673 if (packet.GetBytesLeft() < 1)
2674 return SendIllFormedResponse(packet, "Too short m packet");
2675
2676 // Read the address. Punting on validation.
2677 // FIXME replace with Hex U64 read with no default value that fails on failed
2678 // read.
2679 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2680
2681 // Validate comma.
2682 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2683 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2684
2685 // Get # bytes to read.
2686 if (packet.GetBytesLeft() < 1)
2687 return SendIllFormedResponse(packet, "Length missing in m packet");
2688
2689 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2690 if (byte_count == 0) {
2691 LLDB_LOGF(log,
2692 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2693 "zero-length packet",
2694 __FUNCTION__);
2695 return SendOKResponse();
2696 }
2697
2698 // Optional "address_space:<hex-id>;" suffix, with "thread:<hex-tid>;" for a
2699 // thread specific address space (see the "address-spaces" feature).
2701 std::optional<lldb::tid_t> tid;
2702 if (m_address_space_suffix_supported && packet.GetBytesLeft() > 0 &&
2703 packet.GetChar() == ';') {
2704 llvm::StringRef name, value;
2705 while (packet.GetNameColonValue(name, value)) {
2706 if (name == "address_space" && value.getAsInteger(16, address_space))
2707 return SendIllFormedResponse(packet, "invalid address_space suffix");
2708 if (name == "thread") {
2710 if (value.getAsInteger(16, parsed_tid))
2711 return SendIllFormedResponse(packet, "invalid thread suffix");
2712 tid = parsed_tid;
2713 }
2714 }
2715 }
2716
2717 // Allocate the response buffer.
2718 std::string buf(byte_count, '\0');
2719 if (buf.empty())
2720 return SendErrorResponse(0x78);
2721
2722 // Retrieve the process memory.
2723 size_t bytes_read = 0;
2724 Status error = m_current_process->ReadMemoryWithoutTrap(
2725 ProcessAddress(read_addr, address_space, tid), &buf[0], byte_count,
2726 bytes_read);
2727 LLDB_LOG(log,
2728 "read {2} of {1} requested bytes at {0:x} in address_space {4} "
2729 "thread {5} (error: {3})",
2730 read_addr, byte_count, bytes_read, error, address_space,
2731 tid ? *tid : LLDB_INVALID_THREAD_ID);
2732 if (bytes_read == 0)
2733 return SendErrorResponse(0x08);
2734
2735 StreamGDBRemote response;
2736 packet.SetFilePos(0);
2737 char kind = packet.GetChar('?');
2738 if (kind == 'x')
2739 response.PutEscapedBytes(buf.data(), bytes_read);
2740 else {
2741 assert(kind == 'm');
2742 for (size_t i = 0; i < bytes_read; ++i)
2743 response.PutHex8(buf[i]);
2744 }
2745
2746 return SendPacketNoLock(response.GetString());
2747}
2748
2751 Log *log = GetLog(LLDBLog::Process);
2752
2753 if (!m_current_process ||
2755 LLDB_LOGF(
2756 log,
2757 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2758 __FUNCTION__);
2759 return SendErrorResponse(0x15);
2760 }
2761
2762 // Parse out the memory address.
2763 packet.SetFilePos(strlen("_M"));
2764 if (packet.GetBytesLeft() < 1)
2765 return SendIllFormedResponse(packet, "Too short _M packet");
2766
2767 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2768 if (size == LLDB_INVALID_ADDRESS)
2769 return SendIllFormedResponse(packet, "Address not valid");
2770 if (packet.GetChar() != ',')
2771 return SendIllFormedResponse(packet, "Bad packet");
2772 Permissions perms = {};
2773 while (packet.GetBytesLeft() > 0) {
2774 switch (packet.GetChar()) {
2775 case 'r':
2776 perms |= ePermissionsReadable;
2777 break;
2778 case 'w':
2779 perms |= ePermissionsWritable;
2780 break;
2781 case 'x':
2782 perms |= ePermissionsExecutable;
2783 break;
2784 default:
2785 return SendIllFormedResponse(packet, "Bad permissions");
2786 }
2787 }
2788
2789 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2790 if (!addr)
2791 return SendErrorResponse(addr.takeError());
2792
2793 StreamGDBRemote response;
2794 response.PutHex64(*addr);
2795 return SendPacketNoLock(response.GetString());
2796}
2797
2800 Log *log = GetLog(LLDBLog::Process);
2801
2802 if (!m_current_process ||
2804 LLDB_LOGF(
2805 log,
2806 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2807 __FUNCTION__);
2808 return SendErrorResponse(0x15);
2809 }
2810
2811 // Parse out the memory address.
2812 packet.SetFilePos(strlen("_m"));
2813 if (packet.GetBytesLeft() < 1)
2814 return SendIllFormedResponse(packet, "Too short m packet");
2815
2816 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2817 if (addr == LLDB_INVALID_ADDRESS)
2818 return SendIllFormedResponse(packet, "Address not valid");
2819
2820 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2821 return SendErrorResponse(std::move(Err));
2822
2823 return SendOKResponse();
2824}
2825
2828 Log *log = GetLog(LLDBLog::Process);
2829
2830 if (!m_current_process ||
2832 LLDB_LOGF(
2833 log,
2834 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2835 __FUNCTION__);
2836 return SendErrorResponse(0x15);
2837 }
2838
2839 // Parse out the memory address.
2840 packet.SetFilePos(strlen("M"));
2841 if (packet.GetBytesLeft() < 1)
2842 return SendIllFormedResponse(packet, "Too short M packet");
2843
2844 // Read the address. Punting on validation.
2845 // FIXME replace with Hex U64 read with no default value that fails on failed
2846 // read.
2847 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2848
2849 // Validate comma.
2850 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2851 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2852
2853 // Get # bytes to read.
2854 if (packet.GetBytesLeft() < 1)
2855 return SendIllFormedResponse(packet, "Length missing in M packet");
2856
2857 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2858 if (byte_count == 0) {
2859 LLDB_LOG(log, "nothing to write: zero-length packet");
2860 return PacketResult::Success;
2861 }
2862
2863 // Validate colon.
2864 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2865 return SendIllFormedResponse(
2866 packet, "Comma sep missing in M packet after byte length");
2867
2868 // Allocate the conversion buffer.
2869 std::vector<uint8_t> buf(byte_count, 0);
2870 if (buf.empty())
2871 return SendErrorResponse(0x78);
2872
2873 // Convert the hex memory write contents to bytes.
2874 StreamGDBRemote response;
2875 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2876 if (convert_count != byte_count) {
2877 LLDB_LOG(log,
2878 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2879 "to convert.",
2880 m_current_process->GetID(), write_addr, byte_count, convert_count);
2881 return SendIllFormedResponse(packet, "M content byte length specified did "
2882 "not match hex-encoded content "
2883 "length");
2884 }
2885
2886 // Write the process memory.
2887 size_t bytes_written = 0;
2888 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2889 bytes_written);
2890 if (error.Fail()) {
2891 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2892 m_current_process->GetID(), write_addr, error);
2893 return SendErrorResponse(0x09);
2894 }
2895
2896 if (bytes_written == 0) {
2897 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2898 m_current_process->GetID(), write_addr, byte_count);
2899 return SendErrorResponse(0x09);
2900 }
2901
2902 return SendOKResponse();
2903}
2904
2907 StringExtractorGDBRemote &packet) {
2908 Log *log = GetLog(LLDBLog::Process);
2909
2910 // Currently only the NativeProcessProtocol knows if it can handle a
2911 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2912 // attached to a process. For now we'll assume the client only asks this
2913 // when a process is being debugged.
2914
2915 // Ensure we have a process running; otherwise, we can't figure this out
2916 // since we won't have a NativeProcessProtocol.
2917 if (!m_current_process ||
2919 LLDB_LOGF(
2920 log,
2921 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2922 __FUNCTION__);
2923 return SendErrorResponse(0x15);
2924 }
2925
2926 // Test if we can get any region back when asking for the region around NULL.
2927 MemoryRegionInfo region_info;
2928 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2929 if (error.Fail()) {
2930 // We don't support memory region info collection for this
2931 // NativeProcessProtocol.
2932 return SendUnimplementedResponse("");
2933 }
2934
2935 return SendOKResponse();
2936}
2937
2940 StringExtractorGDBRemote &packet) {
2941 Log *log = GetLog(LLDBLog::Process);
2942
2943 // Ensure we have a process.
2944 if (!m_current_process ||
2946 LLDB_LOGF(
2947 log,
2948 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2949 __FUNCTION__);
2950 return SendErrorResponse(0x15);
2951 }
2952
2953 // Parse out the memory address.
2954 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2955 if (packet.GetBytesLeft() < 1)
2956 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2957
2958 // Read the address. Punting on validation.
2959 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2960
2961 StreamGDBRemote response;
2962
2963 // Get the memory region info for the target address.
2964 MemoryRegionInfo region_info;
2965 const Status error =
2966 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2967 if (error.Fail()) {
2968 // Return the error message.
2969
2970 response.PutCString("error:");
2971 response.PutStringAsRawHex8(error.AsCString());
2972 response.PutChar(';');
2973 } else {
2974 // Range start and size.
2975 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2976 region_info.GetRange().GetRangeBase(),
2977 region_info.GetRange().GetByteSize());
2978
2979 // Permissions.
2980 if (region_info.GetReadable() || region_info.GetWritable() ||
2981 region_info.GetExecutable()) {
2982 // Write permissions info.
2983 response.PutCString("permissions:");
2984
2985 if (region_info.GetReadable())
2986 response.PutChar('r');
2987 if (region_info.GetWritable())
2988 response.PutChar('w');
2989 if (region_info.GetExecutable())
2990 response.PutChar('x');
2991
2992 response.PutChar(';');
2993 }
2994
2995 // Flags
2996 LazyBool memory_tagged = region_info.GetMemoryTagged();
2997 LazyBool is_shadow_stack = region_info.IsShadowStack();
2998
2999 if (memory_tagged != eLazyBoolDontKnow ||
3000 is_shadow_stack != eLazyBoolDontKnow) {
3001 response.PutCString("flags:");
3002 // Space is the separator.
3003 if (memory_tagged == eLazyBoolYes)
3004 response.PutCString("mt ");
3005 if (is_shadow_stack == eLazyBoolYes)
3006 response.PutCString("ss ");
3007
3008 response.PutChar(';');
3009 }
3010
3011 // Name
3012 ConstString name = region_info.GetName();
3013 if (name) {
3014 response.PutCString("name:");
3015 response.PutStringAsRawHex8(name.GetStringRef());
3016 response.PutChar(';');
3017 }
3018
3019 if (std::optional<unsigned> protection_key = region_info.GetProtectionKey())
3020 response.Printf("protection-key:%" PRIu32 ";", *protection_key);
3021
3022 LazyBool is_stack = region_info.IsStackMemory();
3023 if (is_stack != eLazyBoolDontKnow)
3024 response.Printf("type:%s;", is_stack ? "stack" : "heap");
3025 }
3026
3027 return SendPacketNoLock(response.GetString());
3028}
3029
3030namespace {
3031struct UseBreakpoint {
3032 bool want_hardware = false;
3033};
3034struct UseWatchpoint {
3035 uint32_t flags;
3036 static constexpr bool want_hardware = true;
3037};
3038struct InvalidStoppoint {};
3039
3040std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint>
3041getBreakpointKind(GDBStoppointType stoppoint_type) {
3042 switch (stoppoint_type) {
3044 return UseBreakpoint{/*want_hardware*/ false};
3046 return UseBreakpoint{/*want_hardware*/ true};
3047 case eWatchpointWrite:
3048 return UseWatchpoint{/*flags*/ 1};
3049 case eWatchpointRead:
3050 return UseWatchpoint{/*flags*/ 2};
3052 return UseWatchpoint{/*flags*/ 3};
3053 case eStoppointInvalid:
3054 return InvalidStoppoint();
3055 }
3056 llvm_unreachable("unhandled GDBStoppointType");
3057}
3058} // namespace
3059
3062 llvm::StringRef packet_str) {
3063 // Ensure we have a process.
3064 if (!m_current_process ||
3066 Log *log = GetLog(LLDBLog::Process);
3067 LLDB_LOG(log, "failed, no process available");
3068 return BreakpointError{0x15};
3069 }
3070
3071 StringExtractorGDBRemote packet(packet_str);
3072
3073 // Parse out software or hardware breakpoint or watchpoint requested.
3074 packet.SetFilePos(strlen("Z"));
3075 if (packet.GetBytesLeft() < 1)
3076 return BreakpointIllFormed{
3077 "Too short Z packet, missing software/hardware specifier"};
3078
3079 const GDBStoppointType stoppoint_type =
3081 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3082 getBreakpointKind(stoppoint_type);
3083 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3084 return BreakpointIllFormed{
3085 "Z packet had invalid software/hardware specifier"};
3086
3087 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3088 return BreakpointIllFormed{
3089 "Malformed Z packet, expecting comma after stoppoint type"};
3090
3091 // Parse out the stoppoint address.
3092 if (packet.GetBytesLeft() < 1)
3093 return BreakpointIllFormed{"Too short Z packet, missing address"};
3094 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3095
3096 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3097 return BreakpointIllFormed{
3098 "Malformed Z packet, expecting comma after address"};
3099
3100 // Parse out the stoppoint size (i.e. size hint for opcode size).
3101 const uint32_t size =
3102 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
3103 if (size == std::numeric_limits<uint32_t>::max())
3104 return BreakpointIllFormed{
3105 "Malformed Z packet, failed to parse size argument"};
3106
3107 // Try to set a breakpoint.
3108 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3109 const Status error =
3110 m_current_process->SetBreakpoint(addr, size, bp_kind->want_hardware);
3111 if (error.Success())
3112 return BreakpointOK();
3114 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
3115 m_current_process->GetID(), error);
3116 return BreakpointError{0x09};
3117 }
3118
3119 // Try to set a watchpoint.
3120 auto wp_kind = std::get<UseWatchpoint>(bp_variant);
3121 const Status error = m_current_process->SetWatchpoint(
3122 addr, size, wp_kind.flags, wp_kind.want_hardware);
3123 if (error.Success())
3124 return BreakpointOK();
3126 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
3127 m_current_process->GetID(), error);
3128 return BreakpointError{0x09};
3129}
3130
3133 llvm::StringRef packet_str) {
3134 // Ensure we have a process.
3135 if (!m_current_process ||
3137 Log *log = GetLog(LLDBLog::Process);
3138 LLDB_LOG(log, "failed, no process available");
3139 return BreakpointError{0x15};
3140 }
3141
3142 StringExtractorGDBRemote packet(packet_str);
3143
3144 // Parse out software or hardware breakpoint or watchpoint requested.
3145 packet.SetFilePos(strlen("z"));
3146 if (packet.GetBytesLeft() < 1)
3147 return BreakpointIllFormed{
3148 "Too short z packet, missing software/hardware specifier"};
3149
3150 const GDBStoppointType stoppoint_type =
3152 std::variant<UseBreakpoint, UseWatchpoint, InvalidStoppoint> bp_variant =
3153 getBreakpointKind(stoppoint_type);
3154 if (std::holds_alternative<InvalidStoppoint>(bp_variant))
3155 return BreakpointIllFormed{
3156 "z packet had invalid software/hardware specifier"};
3157
3158 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3159 return BreakpointIllFormed{
3160 "Malformed z packet, expecting comma after stoppoint type"};
3161
3162 // Parse out the stoppoint address.
3163 if (packet.GetBytesLeft() < 1)
3164 return BreakpointIllFormed{"Too short z packet, missing address"};
3165 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3166
3167 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
3168 return BreakpointIllFormed{
3169 "Malformed z packet, expecting comma after address"};
3170
3171 /*
3172 // Parse out the stoppoint size (i.e. size hint for opcode size).
3173 const uint32_t size = packet.GetHexMaxU32 (false,
3174 std::numeric_limits<uint32_t>::max ());
3175 if (size == std::numeric_limits<uint32_t>::max ())
3176 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
3177 size argument");
3178 */
3179
3180 // Try to clear the breakpoint.
3181 if (auto *bp_kind = std::get_if<UseBreakpoint>(&bp_variant)) {
3182 const Status error =
3183 m_current_process->RemoveBreakpoint(addr, bp_kind->want_hardware);
3184 if (error.Success())
3185 return BreakpointOK();
3187 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
3188 m_current_process->GetID(), error);
3189 return BreakpointError{0x09};
3190 }
3191 // Try to clear the watchpoint.
3192 const Status error = m_current_process->RemoveWatchpoint(addr);
3193 if (error.Success())
3194 return BreakpointOK();
3196 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3197 m_current_process->GetID(), error);
3198 return BreakpointError{0x09};
3199}
3200
3203 StringExtractorGDBRemote &packet, const BreakpointResult &result) {
3204 return std::visit(
3205 [&](auto &&arg) {
3206 using T = std::decay_t<decltype(arg)>;
3207 static_assert(std::is_same_v<T, BreakpointOK> ||
3208 std::is_same_v<T, BreakpointError> ||
3209 std::is_same_v<T, BreakpointIllFormed>,
3210 "non-exhaustive visitor!");
3211 if constexpr (std::is_same_v<T, BreakpointOK>)
3212 return SendOKResponse();
3213 else if constexpr (std::is_same_v<T, BreakpointError>)
3214 return SendErrorResponse(arg.error_code);
3215 else
3216 return SendIllFormedResponse(packet, arg.message.c_str());
3217 },
3218 result);
3219}
3220
3226
3232
3235 StringExtractorGDBRemote &packet) {
3236 llvm::StringRef packet_str = packet.GetStringRef();
3237 if (!packet_str.consume_front("jMultiBreakpoint:"))
3238 return SendIllFormedResponse(packet,
3239 "Invalid jMultiBreakpoint packet prefix");
3240
3241 llvm::Expected<llvm::json::Value> parsed = llvm::json::parse(packet_str);
3242 if (!parsed) {
3243 llvm::consumeError(parsed.takeError());
3244 return SendIllFormedResponse(packet,
3245 "jMultiBreakpoint did not contain valid JSON");
3246 }
3247 llvm::json::Object *request_dict = parsed->getAsObject();
3248 if (!request_dict)
3249 return SendIllFormedResponse(
3250 packet, "jMultiBreakpoint did not contain a JSON dictionary");
3251
3252 llvm::json::Array *request_array =
3253 request_dict->getArray("breakpoint_requests");
3254 if (!request_array)
3255 return SendIllFormedResponse(
3256 packet,
3257 "jMultiBreakpoint did not contain a valid 'breakpoint_requests' field");
3258
3259 llvm::json::Array reply_array;
3260 for (const llvm::json::Value &value : *request_array) {
3261 std::optional<llvm::StringRef> request = value.getAsString();
3262 if (!request)
3263 return SendIllFormedResponse(packet,
3264 "jMultiBreakpoint had a non-string entry");
3265 BreakpointResult result = request->starts_with("Z")
3266 ? ExecuteSetBreakpoint(*request)
3267 : ExecuteRemoveBreakpoint(*request);
3268 std::visit(
3269 [&](const auto &arg) {
3270 using T = std::decay_t<decltype(arg)>;
3271 static_assert(std::is_same_v<T, BreakpointOK> ||
3272 std::is_same_v<T, BreakpointError> ||
3273 std::is_same_v<T, BreakpointIllFormed>,
3274 "non-exhaustive visitor!");
3275 if constexpr (std::is_same_v<T, BreakpointOK>)
3276 reply_array.push_back("OK");
3277 else if constexpr (std::is_same_v<T, BreakpointError>)
3278 reply_array.push_back(
3279 llvm::formatv("E{0:X-2}", arg.error_code).str());
3280 else
3281 reply_array.push_back("E03");
3282 },
3283 result);
3284 }
3285
3286 llvm::json::Object dict;
3287 dict.try_emplace("results", std::move(reply_array));
3288
3289 StreamString stream;
3290 stream.AsRawOstream() << llvm::json::Value(std::move(dict));
3291 StringRef response_str = stream.GetString();
3292 StreamGDBRemote response;
3293 response.PutEscapedBytes(response_str.data(), response_str.size());
3294 return SendPacketNoLock(response.GetString());
3295}
3296
3300
3301 // Ensure we have a process.
3302 if (!m_continue_process ||
3304 LLDB_LOGF(
3305 log,
3306 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3307 __FUNCTION__);
3308 return SendErrorResponse(0x32);
3309 }
3310
3311 // We first try to use a continue thread id. If any one or any all set, use
3312 // the current thread. Bail out if we don't have a thread id.
3314 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3315 tid = GetCurrentThreadID();
3316 if (tid == LLDB_INVALID_THREAD_ID)
3317 return SendErrorResponse(0x33);
3318
3319 // Double check that we have such a thread.
3320 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3321 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3322 if (!thread)
3323 return SendErrorResponse(0x33);
3324
3325 // Create the step action for the given thread.
3327
3328 // Setup the actions list.
3329 ResumeActionList actions;
3330 actions.Append(action);
3331
3332 // All other threads stop while we're single stepping a thread.
3334
3335 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3336 if (resume_res != PacketResult::Success)
3337 return resume_res;
3338
3339 // No response here, unless in non-stop mode.
3340 // Otherwise, the stop or exit will come from the resulting action.
3342}
3343
3344llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3346 // Ensure we have a thread.
3347 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3348 if (!thread)
3349 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3350 "No thread available");
3351
3353 // Get the register context for the first thread.
3354 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3355
3356 StreamString response;
3357
3358 response.Printf("<?xml version=\"1.0\"?>\n");
3359 response.Printf("<target version=\"1.0\">\n");
3360 response.IndentMore();
3361
3362 response.Indent();
3363 const llvm::StringRef arch_name =
3364 m_current_process->GetArchitecture().GetTriple().getArchName();
3365 // Match gdbserver's expected architecture. We do the reverse when
3366 // decoding the architecture when receiving the target.xml
3367 // in ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess.
3368 const llvm::StringRef new_arch_name = StringSwitch<llvm::StringRef>(arch_name)
3369 .Case("x86_64", "i386:x86-64")
3370 .Case("riscv64", "riscv:rv64")
3371 .Case("riscv32", "riscv:rv32")
3372 .Default(arch_name);
3373 response.Format("<architecture>{}</architecture>\n", new_arch_name);
3374 response.Indent("<feature>\n");
3375
3376 const int registers_count = reg_context.GetUserRegisterCount();
3377 if (registers_count)
3378 response.IndentMore();
3379
3380 std::unordered_set<std::string> register_types_emitted;
3381 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3382 const RegisterInfo *reg_info =
3383 reg_context.GetRegisterInfoAtIndex(reg_index);
3384
3385 if (!reg_info) {
3386 LLDB_LOGF(log,
3387 "%s failed to get register info for register index %" PRIu32,
3388 "target.xml", reg_index);
3389 continue;
3390 }
3391
3392 if (reg_info->register_type)
3393 reg_info->register_type->ToXML(response, register_types_emitted);
3394
3395 response.Indent();
3396 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3397 "\" regnum=\"%d\" ",
3398 reg_info->name, reg_info->byte_size * 8, reg_index);
3399
3400 if (!reg_context.RegisterOffsetIsDynamic())
3401 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3402
3403 if (reg_info->alt_name && reg_info->alt_name[0])
3404 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3405
3406 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3407 if (!encoding.empty())
3408 response << "encoding=\"" << encoding << "\" ";
3409
3410 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3411 if (!format.empty())
3412 response << "format=\"" << format << "\" ";
3413
3414 if (reg_info->register_type)
3415 response << "type=\""
3417 << "\" ";
3418
3419 const char *const register_set_name =
3420 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3421 if (register_set_name)
3422 response << "group=\"" << register_set_name << "\" ";
3423
3426 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3428
3429 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3431 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3433
3434 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3435 if (!kind_generic.empty())
3436 response << "generic=\"" << kind_generic << "\" ";
3437
3438 if (reg_info->value_regs &&
3439 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3440 response.PutCString("value_regnums=\"");
3441 CollectRegNums(reg_info->value_regs, response, false);
3442 response.Printf("\" ");
3443 }
3444
3445 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3446 response.PutCString("invalidate_regnums=\"");
3447 CollectRegNums(reg_info->invalidate_regs, response, false);
3448 response.Printf("\" ");
3449 }
3450
3451 response.Printf("/>\n");
3452 }
3453
3454 if (registers_count)
3455 response.IndentLess();
3456
3457 response.Indent("</feature>\n");
3458 response.IndentLess();
3459 response.Indent("</target>\n");
3460 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3461}
3462
3463llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3465 llvm::StringRef annex) {
3466 // Make sure we have a valid process.
3467 if (!m_current_process ||
3469 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3470 "No process available");
3471 }
3472
3473 if (object == "auxv") {
3474 // Grab the auxv data.
3475 auto buffer_or_error = m_current_process->GetAuxvData();
3476 if (!buffer_or_error)
3477 return llvm::errorCodeToError(buffer_or_error.getError());
3478 return std::move(*buffer_or_error);
3479 }
3480
3481 if (object == "siginfo") {
3482 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3483 if (!thread)
3484 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3485 "no current thread");
3486
3487 auto buffer_or_error = thread->GetSiginfo();
3488 if (!buffer_or_error)
3489 return buffer_or_error.takeError();
3490 return std::move(*buffer_or_error);
3491 }
3492
3493 if (object == "libraries-svr4") {
3494 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3495 if (!library_list)
3496 return library_list.takeError();
3497
3498 StreamString response;
3499 response.Printf("<library-list-svr4 version=\"1.0\">");
3500 for (auto const &library : *library_list) {
3501 response.Printf("<library name=\"%s\" ",
3502 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3503 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3504 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3505 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3506 }
3507 response.Printf("</library-list-svr4>");
3508 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3509 }
3510
3511 if (object == "libraries") {
3512 auto library_list = m_current_process->GetLoadedLibraries();
3513 if (!library_list)
3514 return library_list.takeError();
3515
3516 StreamString response;
3517 response.Printf("<library-list>");
3518 for (auto const &library : *library_list) {
3519 response.Printf("<library name=\"%s\">",
3520 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3521 response.Printf("<section address=\"0x%" PRIx64 "\"/>",
3522 library.base_addr);
3523 response.Printf("</library>");
3524 }
3525 response.Printf("</library-list>");
3526 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3527 }
3528
3529 if (object == "features" && annex == "target.xml")
3530 return BuildTargetXml();
3531
3532 return llvm::make_error<UnimplementedError>();
3533}
3534
3537 StringExtractorGDBRemote &packet) {
3538 SmallVector<StringRef, 5> fields;
3539 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3540 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3541 if (fields.size() != 5)
3542 return SendIllFormedResponse(packet, "malformed qXfer packet");
3543 StringRef &xfer_object = fields[1];
3544 StringRef &xfer_action = fields[2];
3545 StringRef &xfer_annex = fields[3];
3546 StringExtractor offset_data(fields[4]);
3547 if (xfer_action != "read")
3548 return SendUnimplementedResponse("qXfer action not supported");
3549 // Parse offset.
3550 const uint64_t xfer_offset =
3551 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3552 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3553 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3554 // Parse out comma.
3555 if (offset_data.GetChar() != ',')
3556 return SendIllFormedResponse(packet,
3557 "qXfer packet missing comma after offset");
3558 // Parse out the length.
3559 const uint64_t xfer_length =
3560 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3561 if (xfer_length == std::numeric_limits<uint64_t>::max())
3562 return SendIllFormedResponse(packet, "qXfer packet missing length");
3563
3564 // Get a previously constructed buffer if it exists or create it now.
3565 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3566 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3567 if (buffer_it == m_xfer_buffer_map.end()) {
3568 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3569 if (!buffer_up)
3570 return SendErrorResponse(buffer_up.takeError());
3571 buffer_it = m_xfer_buffer_map
3572 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3573 .first;
3574 }
3575
3576 // Send back the response
3577 StreamGDBRemote response;
3578 bool done_with_buffer = false;
3579 llvm::StringRef buffer = buffer_it->second->getBuffer();
3580 if (xfer_offset >= buffer.size()) {
3581 // We have nothing left to send. Mark the buffer as complete.
3582 response.PutChar('l');
3583 done_with_buffer = true;
3584 } else {
3585 // Figure out how many bytes are available starting at the given offset.
3586 buffer = buffer.drop_front(xfer_offset);
3587 // Mark the response type according to whether we're reading the remainder
3588 // of the data.
3589 if (xfer_length >= buffer.size()) {
3590 // There will be nothing left to read after this
3591 response.PutChar('l');
3592 done_with_buffer = true;
3593 } else {
3594 // There will still be bytes to read after this request.
3595 response.PutChar('m');
3596 buffer = buffer.take_front(xfer_length);
3597 }
3598 // Now write the data in encoded binary form.
3599 response.PutEscapedBytes(buffer.data(), buffer.size());
3600 }
3601
3602 if (done_with_buffer)
3603 m_xfer_buffer_map.erase(buffer_it);
3604
3605 return SendPacketNoLock(response.GetString());
3606}
3607
3610 StringExtractorGDBRemote &packet) {
3611 Log *log = GetLog(LLDBLog::Thread);
3612
3613 // Move past packet name.
3614 packet.SetFilePos(strlen("QSaveRegisterState"));
3615
3616 // Get the thread to use.
3617 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3618 if (!thread) {
3620 return SendIllFormedResponse(
3621 packet, "No thread specified in QSaveRegisterState packet");
3622 else
3623 return SendIllFormedResponse(packet,
3624 "No thread was is set with the Hg packet");
3625 }
3626
3627 // Grab the register context for the thread.
3628 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3629
3630 // Save registers to a buffer.
3631 WritableDataBufferSP register_data_sp;
3632 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3633 if (error.Fail()) {
3634 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3635 m_current_process->GetID(), error);
3636 return SendErrorResponse(0x75);
3637 }
3638
3639 // Allocate a new save id.
3640 const uint32_t save_id = GetNextSavedRegistersID();
3641
3642 // Save the register data buffer under the save id.
3643 {
3644 auto saved_registers = m_saved_registers.Lock();
3645 assert((saved_registers->map.find(save_id) == saved_registers->map.end()) &&
3646 "GetNextRegisterSaveID() returned an existing register save id");
3647 saved_registers->map[save_id] = register_data_sp;
3648 }
3649
3650 // Write the response.
3651 StreamGDBRemote response;
3652 response.Printf("%" PRIu32, save_id);
3653 return SendPacketNoLock(response.GetString());
3654}
3655
3658 StringExtractorGDBRemote &packet) {
3659 Log *log = GetLog(LLDBLog::Thread);
3660
3661 // Parse out save id.
3662 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3663 if (packet.GetBytesLeft() < 1)
3664 return SendIllFormedResponse(
3665 packet, "QRestoreRegisterState packet missing register save id");
3666
3667 const uint32_t save_id = packet.GetU32(0);
3668 if (save_id == 0) {
3669 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3670 "expecting decimal uint32_t");
3671 return SendErrorResponse(0x76);
3672 }
3673
3674 // Get the thread to use.
3675 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3676 if (!thread) {
3678 return SendIllFormedResponse(
3679 packet, "No thread specified in QRestoreRegisterState packet");
3680 else
3681 return SendIllFormedResponse(packet,
3682 "No thread was is set with the Hg packet");
3683 }
3684
3685 // Grab the register context for the thread.
3686 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3687
3688 // Retrieve register state buffer, then remove from the list.
3689 DataBufferSP register_data_sp;
3690 {
3691 auto saved_registers = m_saved_registers.Lock();
3692
3693 // Find the register set buffer for the given save id.
3694 auto it = saved_registers->map.find(save_id);
3695 if (it == saved_registers->map.end()) {
3696 LLDB_LOG(log,
3697 "pid {0} does not have a register set save buffer for id {1}",
3698 m_current_process->GetID(), save_id);
3699 return SendErrorResponse(0x77);
3700 }
3701 register_data_sp = it->second;
3702
3703 // Remove it from the map.
3704 saved_registers->map.erase(it);
3705 }
3706
3707 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3708 if (error.Fail()) {
3709 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3710 m_current_process->GetID(), error);
3711 return SendErrorResponse(0x77);
3712 }
3713
3714 return SendOKResponse();
3715}
3716
3719 StringExtractorGDBRemote &packet) {
3720 Log *log = GetLog(LLDBLog::Process);
3721
3722 // Consume the ';' after vAttach.
3723 packet.SetFilePos(strlen("vAttach"));
3724 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3725 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3726
3727 // Grab the PID to which we will attach (assume hex encoding).
3728 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3729 if (pid == LLDB_INVALID_PROCESS_ID)
3730 return SendIllFormedResponse(packet,
3731 "vAttach failed to parse the process id");
3732
3733 // Attempt to attach.
3734 LLDB_LOGF(log,
3735 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3736 "pid %" PRIu64,
3737 __FUNCTION__, pid);
3738
3740
3741 if (error.Fail()) {
3742 LLDB_LOGF(log,
3743 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3744 "pid %" PRIu64 ": %s\n",
3745 __FUNCTION__, pid, error.AsCString());
3746 return SendErrorResponse(error);
3747 }
3748
3749 // Notify we attached by sending a stop packet.
3750 assert(m_current_process);
3752 m_current_process->GetState(),
3753 /*force_synchronous=*/false);
3754}
3755
3758 StringExtractorGDBRemote &packet) {
3759 Log *log = GetLog(LLDBLog::Process);
3760
3761 // Consume the ';' after the identifier.
3762 packet.SetFilePos(strlen("vAttachWait"));
3763
3764 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3765 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3766
3767 // Allocate the buffer for the process name from vAttachWait.
3768 std::string process_name;
3769 if (!packet.GetHexByteString(process_name))
3770 return SendIllFormedResponse(packet,
3771 "vAttachWait failed to parse process name");
3772
3773 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3774
3775 Status error = AttachWaitProcess(process_name, false);
3776 if (error.Fail()) {
3777 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3778 error);
3779 return SendErrorResponse(error);
3780 }
3781
3782 // Notify we attached by sending a stop packet.
3783 assert(m_current_process);
3785 m_current_process->GetState(),
3786 /*force_synchronous=*/false);
3787}
3788
3794
3797 StringExtractorGDBRemote &packet) {
3798 Log *log = GetLog(LLDBLog::Process);
3799
3800 // Consume the ';' after the identifier.
3801 packet.SetFilePos(strlen("vAttachOrWait"));
3802
3803 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3804 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3805
3806 // Allocate the buffer for the process name from vAttachWait.
3807 std::string process_name;
3808 if (!packet.GetHexByteString(process_name))
3809 return SendIllFormedResponse(packet,
3810 "vAttachOrWait failed to parse process name");
3811
3812 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3813
3814 Status error = AttachWaitProcess(process_name, true);
3815 if (error.Fail()) {
3816 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3817 error);
3818 return SendErrorResponse(error);
3819 }
3820
3821 // Notify we attached by sending a stop packet.
3822 assert(m_current_process);
3824 m_current_process->GetState(),
3825 /*force_synchronous=*/false);
3826}
3827
3830 StringExtractorGDBRemote &packet) {
3831 Log *log = GetLog(LLDBLog::Process);
3832
3833 llvm::StringRef s = packet.GetStringRef();
3834 if (!s.consume_front("vRun;"))
3835 return SendErrorResponse(8);
3836
3837 llvm::SmallVector<llvm::StringRef, 16> argv;
3838 s.split(argv, ';');
3839
3840 for (llvm::StringRef hex_arg : argv) {
3841 StringExtractor arg_ext{hex_arg};
3842 std::string arg;
3843 arg_ext.GetHexByteString(arg);
3844 m_process_launch_info.GetArguments().AppendArgument(arg);
3845 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3846 arg.c_str());
3847 }
3848
3849 if (argv.empty())
3850 return SendErrorResponse(Status::FromErrorString("No arguments"));
3851 m_process_launch_info.GetExecutableFile().SetFile(
3852 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3854 if (m_process_launch_error.Fail())
3856 assert(m_current_process);
3858 m_current_process->GetState(),
3859 /*force_synchronous=*/true);
3860}
3861
3864 Log *log = GetLog(LLDBLog::Process);
3865 if (!m_non_stop)
3867
3869
3870 // Consume the ';' after D.
3871 packet.SetFilePos(1);
3872 if (packet.GetBytesLeft()) {
3873 if (packet.GetChar() != ';')
3874 return SendIllFormedResponse(packet, "D missing expected ';'");
3875
3876 // Grab the PID from which we will detach (assume hex encoding).
3877 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3878 if (pid == LLDB_INVALID_PROCESS_ID)
3879 return SendIllFormedResponse(packet, "D failed to parse the process id");
3880 }
3881
3882 // Detach forked children if their PID was specified *or* no PID was requested
3883 // (i.e. detach-all packet).
3884 llvm::Error detach_error = llvm::Error::success();
3885 bool detached = false;
3886 for (auto it = m_debugged_processes.begin();
3887 it != m_debugged_processes.end();) {
3888 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3889 LLDB_LOGF(log,
3890 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3891 __FUNCTION__, it->first);
3892 if (llvm::Error e = it->second.process_up->Detach().ToError())
3893 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3894 else {
3895 if (it->second.process_up.get() == m_current_process)
3896 m_current_process = nullptr;
3897 if (it->second.process_up.get() == m_continue_process)
3898 m_continue_process = nullptr;
3899 it = m_debugged_processes.erase(it);
3900 detached = true;
3901 continue;
3902 }
3903 }
3904 ++it;
3905 }
3906
3907 if (detach_error)
3908 return SendErrorResponse(std::move(detach_error));
3909 if (!detached)
3910 return SendErrorResponse(
3911 Status::FromErrorStringWithFormat("PID %" PRIu64 " not traced", pid));
3912 return SendOKResponse();
3913}
3914
3917 StringExtractorGDBRemote &packet) {
3918 Log *log = GetLog(LLDBLog::Thread);
3919
3920 if (!m_current_process ||
3922 return SendErrorResponse(50);
3923
3924 packet.SetFilePos(strlen("qThreadStopInfo"));
3925 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3926 if (tid == LLDB_INVALID_THREAD_ID) {
3927 LLDB_LOGF(log,
3928 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3929 "parse thread id from request \"%s\"",
3930 __FUNCTION__, packet.GetStringRef().data());
3931 return SendErrorResponse(0x15);
3932 }
3934 /*force_synchronous=*/true);
3935}
3936
3941
3942 // Ensure we have a debugged process.
3943 if (!m_current_process ||
3945 return SendErrorResponse(50);
3946 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3947
3948 StreamString response;
3949 const bool threads_with_valid_stop_info_only = false;
3950 llvm::Expected<json::Value> threads_info =
3951 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3952 if (!threads_info) {
3953 LLDB_LOG_ERROR(log, threads_info.takeError(),
3954 "failed to prepare a packet for pid {1}: {0}",
3955 m_current_process->GetID());
3956 return SendErrorResponse(52);
3957 }
3958
3959 response.AsRawOstream() << *threads_info;
3960 StreamGDBRemote escaped_response;
3961 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3962 return SendPacketNoLock(escaped_response.GetString());
3963}
3964
3967 StringExtractorGDBRemote &packet) {
3968 Log *log = GetLog(LLDBLog::Process);
3969
3970 // Ensure we have a process.
3971 if (!m_current_process ||
3973 LLDB_LOG(log, "failed, no process available");
3974 return SendErrorResponse(Status::FromErrorString("invalid process"));
3975 }
3976
3977 std::vector<AddressSpaceInfo> address_spaces =
3978 m_current_process->GetAddressSpaces();
3979 if (address_spaces.empty())
3980 return SendUnimplementedResponse(packet.GetStringRef().data());
3981
3982 StreamGDBRemote response;
3983 response.PutAsJSONArray(address_spaces, /*hex_ascii=*/false);
3984 return SendPacketNoLock(response.GetString());
3985}
3986
3989 StringExtractorGDBRemote &packet) {
3990 // Fail if we don't have a current process.
3991 if (!m_current_process ||
3993 return SendErrorResponse(68);
3994
3995 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3996 if (packet.GetBytesLeft() == 0)
3997 return SendOKResponse();
3998 if (packet.GetChar() != ':')
3999 return SendErrorResponse(67);
4000
4001 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
4002
4003 StreamGDBRemote response;
4004 if (hw_debug_cap == std::nullopt)
4005 response.Printf("num:0;");
4006 else
4007 response.Printf("num:%d;", hw_debug_cap->second);
4008
4009 return SendPacketNoLock(response.GetString());
4010}
4011
4014 StringExtractorGDBRemote &packet) {
4015 // Fail if we don't have a current process.
4016 if (!m_current_process ||
4018 return SendErrorResponse(67);
4019
4020 packet.SetFilePos(strlen("qFileLoadAddress:"));
4021 if (packet.GetBytesLeft() == 0)
4022 return SendErrorResponse(68);
4023
4024 std::string file_name;
4025 packet.GetHexByteString(file_name);
4026
4027 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
4028 Status error =
4029 m_current_process->GetFileLoadAddress(file_name, file_load_address);
4030 if (error.Fail())
4031 return SendErrorResponse(69);
4032
4033 if (file_load_address == LLDB_INVALID_ADDRESS)
4034 return SendErrorResponse(1); // File not loaded
4035
4036 StreamGDBRemote response;
4037 response.PutHex64(file_load_address);
4038 return SendPacketNoLock(response.GetString());
4039}
4040
4043 StringExtractorGDBRemote &packet) {
4044 std::vector<int> signals;
4045 packet.SetFilePos(strlen("QPassSignals:"));
4046
4047 // Read sequence of hex signal numbers divided by a semicolon and optionally
4048 // spaces.
4049 while (packet.GetBytesLeft() > 0) {
4050 int signal = packet.GetS32(-1, 16);
4051 if (signal < 0)
4052 return SendIllFormedResponse(packet, "Failed to parse signal number.");
4053 signals.push_back(signal);
4054
4055 packet.SkipSpaces();
4056 char separator = packet.GetChar();
4057 if (separator == '\0')
4058 break; // End of string
4059 if (separator != ';')
4060 return SendIllFormedResponse(packet, "Invalid separator,"
4061 " expected semicolon.");
4062 }
4063
4064 // Fail if we don't have a current process.
4065 if (!m_current_process)
4066 return SendErrorResponse(68);
4067
4068 Status error = m_current_process->IgnoreSignals(signals);
4069 if (error.Fail())
4070 return SendErrorResponse(69);
4071
4072 return SendOKResponse();
4073}
4074
4077 StringExtractorGDBRemote &packet) {
4078 Log *log = GetLog(LLDBLog::Process);
4079
4080 // Ensure we have a process.
4081 if (!m_current_process ||
4083 LLDB_LOGF(
4084 log,
4085 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4086 __FUNCTION__);
4087 return SendErrorResponse(1);
4088 }
4089
4090 // We are expecting
4091 // qMemTags:<hex address>,<hex length>:<hex type>
4092
4093 // Address
4094 packet.SetFilePos(strlen("qMemTags:"));
4095 const char *current_char = packet.Peek();
4096 if (!current_char || *current_char == ',')
4097 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
4098 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4099
4100 // Length
4101 char previous_char = packet.GetChar();
4102 current_char = packet.Peek();
4103 // If we don't have a separator or the length field is empty
4104 if (previous_char != ',' || (current_char && *current_char == ':'))
4105 return SendIllFormedResponse(packet,
4106 "Invalid addr,length pair in qMemTags packet");
4107
4108 if (packet.GetBytesLeft() < 1)
4109 return SendIllFormedResponse(
4110 packet, "Too short qMemtags: packet (looking for length)");
4111 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4112
4113 // Type
4114 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
4115 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4116 return SendIllFormedResponse(packet, invalid_type_err);
4117
4118 // Type is a signed integer but packed into the packet as its raw bytes.
4119 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
4120 const char *first_type_char = packet.Peek();
4121 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4122 return SendIllFormedResponse(packet, invalid_type_err);
4123
4124 // Extract type as unsigned then cast to signed.
4125 // Using a uint64_t here so that we have some value outside of the 32 bit
4126 // range to use as the invalid return value.
4127 uint64_t raw_type =
4128 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4129
4130 if ( // Make sure the cast below would be valid
4131 raw_type > std::numeric_limits<uint32_t>::max() ||
4132 // To catch inputs like "123aardvark" that will parse but clearly aren't
4133 // valid in this case.
4134 packet.GetBytesLeft()) {
4135 return SendIllFormedResponse(packet, invalid_type_err);
4136 }
4137
4138 // First narrow to 32 bits otherwise the copy into type would take
4139 // the wrong 4 bytes on big endian.
4140 uint32_t raw_type_32 = raw_type;
4141 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4142
4143 StreamGDBRemote response;
4144 std::vector<uint8_t> tags;
4145 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
4146 if (error.Fail())
4147 return SendErrorResponse(1);
4148
4149 // This m is here in case we want to support multi part replies in the future.
4150 // In the same manner as qfThreadInfo/qsThreadInfo.
4151 response.PutChar('m');
4152 response.PutBytesAsRawHex8(tags.data(), tags.size());
4153 return SendPacketNoLock(response.GetString());
4154}
4155
4158 StringExtractorGDBRemote &packet) {
4159 Log *log = GetLog(LLDBLog::Process);
4160
4161 // Ensure we have a process.
4162 if (!m_current_process ||
4164 LLDB_LOGF(
4165 log,
4166 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
4167 __FUNCTION__);
4168 return SendErrorResponse(1);
4169 }
4170
4171 // We are expecting
4172 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
4173
4174 // Address
4175 packet.SetFilePos(strlen("QMemTags:"));
4176 const char *current_char = packet.Peek();
4177 if (!current_char || *current_char == ',')
4178 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
4179 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4180
4181 // Length
4182 char previous_char = packet.GetChar();
4183 current_char = packet.Peek();
4184 // If we don't have a separator or the length field is empty
4185 if (previous_char != ',' || (current_char && *current_char == ':'))
4186 return SendIllFormedResponse(packet,
4187 "Invalid addr,length pair in QMemTags packet");
4188
4189 if (packet.GetBytesLeft() < 1)
4190 return SendIllFormedResponse(
4191 packet, "Too short QMemtags: packet (looking for length)");
4192 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
4193
4194 // Type
4195 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
4196 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4197 return SendIllFormedResponse(packet, invalid_type_err);
4198
4199 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
4200 const char *first_type_char = packet.Peek();
4201 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
4202 return SendIllFormedResponse(packet, invalid_type_err);
4203
4204 // The type is a signed integer but is in the packet as its raw bytes.
4205 // So parse first as unsigned then cast to signed later.
4206 // We extract to 64 bit, even though we only expect 32, so that we've
4207 // got some invalid value we can check for.
4208 uint64_t raw_type =
4209 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
4210 if (raw_type > std::numeric_limits<uint32_t>::max())
4211 return SendIllFormedResponse(packet, invalid_type_err);
4212
4213 // First narrow to 32 bits. Otherwise the copy below would get the wrong
4214 // 4 bytes on big endian.
4215 uint32_t raw_type_32 = raw_type;
4216 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
4217
4218 // Tag data
4219 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
4220 return SendIllFormedResponse(packet,
4221 "Missing tag data in QMemTags: packet");
4222
4223 // Must be 2 chars per byte
4224 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
4225 if (packet.GetBytesLeft() % 2)
4226 return SendIllFormedResponse(packet, invalid_data_err);
4227
4228 // This is bytes here and is unpacked into target specific tags later
4229 // We cannot assume that number of bytes == length here because the server
4230 // can repeat tags to fill a given range.
4231 std::vector<uint8_t> tag_data;
4232 // Zero length writes will not have any tag data
4233 // (but we pass them on because it will still check that tagging is enabled)
4234 if (packet.GetBytesLeft()) {
4235 size_t byte_count = packet.GetBytesLeft() / 2;
4236 tag_data.resize(byte_count);
4237 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
4238 if (converted_bytes != byte_count) {
4239 return SendIllFormedResponse(packet, invalid_data_err);
4240 }
4241 }
4242
4243 Status status =
4244 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
4245 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
4246}
4247
4250 StringExtractorGDBRemote &packet) {
4251 // Fail if we don't have a current process.
4252 if (!m_current_process ||
4254 return SendErrorResponse(Status::FromErrorString("Process not running."));
4255
4256 std::string path_hint;
4257
4258 StringRef packet_str{packet.GetStringRef()};
4259 assert(packet_str.starts_with("qSaveCore"));
4260 if (packet_str.consume_front("qSaveCore;")) {
4261 for (auto x : llvm::split(packet_str, ';')) {
4262 if (x.consume_front("path-hint:"))
4263 StringExtractor(x).GetHexByteString(path_hint);
4264 else
4265 return SendErrorResponse(
4266 Status::FromErrorString("Unsupported qSaveCore option"));
4267 }
4268 }
4269
4270 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
4271 if (!ret)
4272 return SendErrorResponse(ret.takeError());
4273
4274 StreamString response;
4275 response.PutCString("core-path:");
4276 response.PutStringAsRawHex8(ret.get());
4277 return SendPacketNoLock(response.GetString());
4278}
4279
4282 StringExtractorGDBRemote &packet) {
4283 Log *log = GetLog(LLDBLog::Process);
4284
4285 StringRef packet_str{packet.GetStringRef()};
4286 assert(packet_str.starts_with("QNonStop:"));
4287 packet_str.consume_front("QNonStop:");
4288 if (packet_str == "0") {
4289 if (m_non_stop)
4291 for (auto &process_it : m_debugged_processes) {
4292 if (process_it.second.process_up->IsRunning()) {
4293 assert(m_non_stop);
4294 Status error = process_it.second.process_up->Interrupt();
4295 if (error.Fail()) {
4296 LLDB_LOG(log,
4297 "while disabling nonstop, failed to halt process {0}: {1}",
4298 process_it.first, error);
4299 return SendErrorResponse(0x41);
4300 }
4301 // we must not send stop reasons after QNonStop
4302 m_disabling_non_stop = true;
4303 }
4304 }
4307 m_non_stop = false;
4308 // If we are stopping anything, defer sending the OK response until we're
4309 // done.
4311 return PacketResult::Success;
4312 } else if (packet_str == "1") {
4313 if (!m_non_stop)
4315 m_non_stop = true;
4316 } else
4317 return SendErrorResponse(
4318 Status::FromErrorString("Invalid QNonStop packet"));
4319 return SendOKResponse();
4320}
4321
4324 std::deque<std::string> &queue) {
4325 // Per the protocol, the first message put into the queue is sent
4326 // immediately. However, it remains the queue until the client ACKs it --
4327 // then we pop it and send the next message. The process repeats until
4328 // the last message in the queue is ACK-ed, in which case the packet sends
4329 // an OK response.
4330 if (queue.empty())
4331 return SendErrorResponse(
4332 Status::FromErrorString("No pending notification to ack"));
4333 queue.pop_front();
4334 if (!queue.empty())
4335 return SendPacketNoLock(queue.front());
4336 return SendOKResponse();
4337}
4338
4344
4347 StringExtractorGDBRemote &packet) {
4349 // If this was the last notification and all the processes exited,
4350 // terminate the server.
4351 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4352 m_exit_now = true;
4353 m_mainloop.RequestTermination();
4354 }
4355 return ret;
4356}
4357
4360 StringExtractorGDBRemote &packet) {
4361 if (!m_non_stop)
4362 return SendErrorResponse(
4363 Status::FromErrorString("vCtrl is only valid in non-stop mode"));
4364
4365 PacketResult interrupt_res = Handle_interrupt(packet);
4366 // If interrupting the process failed, pass the result through.
4367 if (interrupt_res != PacketResult::Success)
4368 return interrupt_res;
4369 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4370 return SendOKResponse();
4371}
4372
4375 packet.SetFilePos(strlen("T"));
4376 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4378 if (!pid_tid)
4379 return SendErrorResponse(llvm::createStringError("malformed thread-id"));
4380
4381 lldb::pid_t pid = pid_tid->first;
4382 lldb::tid_t tid = pid_tid->second;
4383
4384 // Technically, this would also be caught by the PID check but let's be more
4385 // explicit about the error.
4386 if (pid == LLDB_INVALID_PROCESS_ID)
4387 return SendErrorResponse(
4388 llvm::createStringError("no current process and no PID provided"));
4389
4390 // Check the process ID and find respective process instance.
4391 auto new_process_it = m_debugged_processes.find(pid);
4392 if (new_process_it == m_debugged_processes.end())
4393 return SendErrorResponse(1);
4394
4395 // Check the thread ID
4396 if (!new_process_it->second.process_up->GetThreadByID(tid))
4397 return SendErrorResponse(2);
4398
4399 return SendOKResponse();
4400}
4401
4403 Log *log = GetLog(LLDBLog::Process);
4404
4405 // Tell the stdio connection to shut down.
4406 if (m_stdio_communication.IsConnected()) {
4407 auto connection = m_stdio_communication.GetConnection();
4408 if (connection) {
4409 Status error;
4410 connection->Disconnect(&error);
4411
4412 if (error.Success()) {
4413 LLDB_LOGF(log,
4414 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4415 "terminal stdio - SUCCESS",
4416 __FUNCTION__);
4417 } else {
4418 LLDB_LOGF(log,
4419 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4420 "terminal stdio - FAIL: %s",
4421 __FUNCTION__, error.AsCString());
4422 }
4423 }
4424 }
4425}
4426
4428 StringExtractorGDBRemote &packet) {
4429 // We have no thread if we don't have a process.
4430 if (!m_current_process ||
4432 return nullptr;
4433
4434 // If the client hasn't asked for thread suffix support, there will not be a
4435 // thread suffix. Use the current thread in that case.
4437 const lldb::tid_t current_tid = GetCurrentThreadID();
4438 if (current_tid == LLDB_INVALID_THREAD_ID)
4439 return nullptr;
4440 else if (current_tid == 0) {
4441 // Pick a thread.
4442 return m_current_process->GetThreadAtIndex(0);
4443 } else
4444 return m_current_process->GetThreadByID(current_tid);
4445 }
4446
4447 Log *log = GetLog(LLDBLog::Thread);
4448
4449 // Parse out the ';'.
4450 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4451 LLDB_LOGF(log,
4452 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4453 "error: expected ';' prior to start of thread suffix: packet "
4454 "contents = '%s'",
4455 __FUNCTION__, packet.GetStringRef().data());
4456 return nullptr;
4457 }
4458
4459 if (!packet.GetBytesLeft())
4460 return nullptr;
4461
4462 // Parse out thread: portion.
4463 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4464 LLDB_LOGF(log,
4465 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4466 "error: expected 'thread:' but not found, packet contents = "
4467 "'%s'",
4468 __FUNCTION__, packet.GetStringRef().data());
4469 return nullptr;
4470 }
4471 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4472 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4473 if (tid != 0)
4474 return m_current_process->GetThreadByID(tid);
4475
4476 return nullptr;
4477}
4478
4481 // Use whatever the debug process says is the current thread id since the
4482 // protocol either didn't specify or specified we want any/all threads
4483 // marked as the current thread.
4484 if (!m_current_process)
4486 return m_current_process->GetCurrentThreadID();
4487 }
4488 // Use the specific current thread id set by the gdb remote protocol.
4489 return m_current_tid;
4490}
4491
4495
4497 Log *log = GetLog(LLDBLog::Process);
4498
4499 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4500 m_xfer_buffer_map.clear();
4501}
4502
4505 const ArchSpec &arch) {
4506 if (m_current_process) {
4507 FileSpec file_spec;
4509 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4510 .Success()) {
4511 if (FileSystem::Instance().Exists(file_spec))
4512 return file_spec;
4513 }
4514 }
4515
4517}
4518
4520 llvm::StringRef value) {
4521 std::string result;
4522 for (const char &c : value) {
4523 switch (c) {
4524 case '&':
4525 result += "&amp;";
4526 break;
4527 case '\'':
4528 result += "&apos;";
4529 break;
4530 case '"':
4531 result += "&quot;";
4532 break;
4533 case '<':
4534 result += "&lt;";
4535 break;
4536 case '>':
4537 result += "&gt;";
4538 break;
4539 default:
4540 result += c;
4541 break;
4542 }
4543 }
4544 return result;
4545}
4546
4548 const llvm::ArrayRef<llvm::StringRef> client_features) {
4549 std::vector<std::string> ret =
4551 ret.insert(ret.end(), {
4552 "QThreadSuffixSupported+",
4553 "QListThreadsInStopReply+",
4554 "qXfer:features:read+",
4555 "QNonStop+",
4556 "jMultiBreakpoint+",
4557 });
4558
4559 // report server-only features
4560 using Extension = NativeProcessProtocol::Extension;
4561 Extension plugin_features = m_process_manager.GetSupportedExtensions();
4562 if (bool(plugin_features & Extension::pass_signals))
4563 ret.push_back("QPassSignals+");
4564 if (bool(plugin_features & Extension::auxv))
4565 ret.push_back("qXfer:auxv:read+");
4566 if (bool(plugin_features & Extension::libraries_svr4))
4567 ret.push_back("qXfer:libraries-svr4:read+");
4568 if (bool(plugin_features & Extension::libraries))
4569 ret.push_back("qXfer:libraries:read+");
4570 if (bool(plugin_features & Extension::siginfo_read))
4571 ret.push_back("qXfer:siginfo:read+");
4572 if (bool(plugin_features & Extension::memory_tagging))
4573 ret.push_back("memory-tagging+");
4574 if (bool(plugin_features & Extension::savecore))
4575 ret.push_back("qSaveCore+");
4576 if (bool(plugin_features & Extension::address_spaces)) {
4577 ret.push_back("address-spaces+");
4579 }
4580 if (!m_accelerator_plugins.empty())
4581 ret.push_back("accelerator-plugins+");
4582 if (bool(plugin_features & Extension::lldb_settings))
4583 ret.push_back("lldb-settings+");
4584
4585 // check for client features
4587 for (llvm::StringRef x : client_features)
4589 llvm::StringSwitch<Extension>(x)
4590 .Case("multiprocess+", Extension::multiprocess)
4591 .Case("fork-events+", Extension::fork)
4592 .Case("vfork-events+", Extension::vfork)
4593 .Case("qXfer:libraries:read+", Extension::libraries)
4594 .Case("qXfer:libraries-svr4:read+", Extension::libraries_svr4)
4595 .Default({});
4596
4597 // We consume lldb's swbreak/hwbreak feature, but it doesn't change the
4598 // behaviour of lldb-server. We always adjust the program counter for targets
4599 // like x86
4600
4601 m_extensions_supported &= plugin_features;
4602
4603 // fork & vfork require multiprocess
4604 if (!bool(m_extensions_supported & Extension::multiprocess))
4605 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4606
4607 // report only if actually supported
4608 if (bool(m_extensions_supported & Extension::multiprocess))
4609 ret.push_back("multiprocess+");
4610 if (bool(m_extensions_supported & Extension::fork))
4611 ret.push_back("fork-events+");
4612 if (bool(m_extensions_supported & Extension::vfork))
4613 ret.push_back("vfork-events+");
4614
4615 for (auto &x : m_debugged_processes)
4616 SetEnabledExtensions(*x.second.process_up);
4617 return ret;
4618}
4619
4621 NativeProcessProtocol &process) {
4623 assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));
4624 process.SetEnabledExtensions(flags);
4625}
4626
4634
4636 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4637 if (bool(m_extensions_supported &
4639 response.Format("p{0:x-}.", pid);
4640 response.Format("{0:x-}", tid);
4641}
4642
4643std::string
4645 bool reverse_connect) {
4646 // Try parsing the argument as URL.
4647 if (std::optional<URI> url = URI::Parse(url_arg)) {
4648 if (reverse_connect)
4649 return url_arg.str();
4650
4651 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4652 // If the scheme doesn't match any, pass it through to support using CFD
4653 // schemes directly.
4654 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4655 .Case("tcp", "listen")
4656 .Case("unix", "unix-accept")
4657 .Case("unix-abstract", "unix-abstract-accept")
4658 .Default(url->scheme.str());
4659 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4660 return new_url;
4661 }
4662
4663 std::string host_port = url_arg.str();
4664 // If host_and_port starts with ':', default the host to be "localhost" and
4665 // expect the remainder to be the port.
4666 if (url_arg.starts_with(":"))
4667 host_port.insert(0, "localhost");
4668
4669 // Try parsing the (preprocessed) argument as host:port pair.
4670 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4671 return (reverse_connect ? "connect://" : "listen://") + host_port;
4672
4673 // If none of the above applied, interpret the argument as UNIX socket path.
4674 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4675 url_arg.str();
4676}
4677
4679 std::unique_ptr<LLDBServerAcceleratorPlugin> plugin_up) {
4680 m_accelerator_plugins.emplace_back(std::move(plugin_up));
4681}
4682
4687 return SendErrorResponse(
4688 Status::FromErrorString("invalid accelerator plugin"));
4689
4690 std::optional<LLDBSettings> settings =
4691 m_connection_accelerator_plugin->GetLLDBSettings();
4692 if (!settings)
4693 return SendErrorResponse(
4694 Status::FromErrorString("no LLDB settings available"));
4695
4696 StreamGDBRemote response;
4697 response.PutAsJSON(*settings, /*hex_ascii=*/false);
4698 return SendPacketNoLock(response.GetString());
4699}
4700
4704 std::vector<AcceleratorActions> accelerator_actions;
4705 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4707 if (auto actions = plugin_up->GetInitializeActions())
4708 accelerator_actions.push_back(std::move(*actions));
4709 }
4710 StreamGDBRemote response;
4711 response.PutAsJSONArray(accelerator_actions, /*hex_ascii=*/false);
4712 return SendPacketNoLock(response.GetString());
4713}
4714
4717 StringExtractorGDBRemote &packet) {
4718 packet.ConsumeFront("jAcceleratorPluginBreakpointHit:");
4719 llvm::Expected<AcceleratorBreakpointHitArgs> args =
4720 llvm::json::parse<AcceleratorBreakpointHitArgs>(
4721 packet.Peek(), "AcceleratorBreakpointHitArgs");
4722 if (!args)
4723 return SendErrorResponse(args.takeError());
4724
4725 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4727 if (plugin_up->GetPluginName() == args->plugin_name) {
4728 llvm::Expected<AcceleratorBreakpointHitResponse> bp_response =
4729 plugin_up->BreakpointWasHit(*args);
4730 if (!bp_response)
4731 return SendErrorResponse(bp_response.takeError());
4732
4733 StreamGDBRemote response;
4734 response.PutAsJSON(*bp_response, /*hex_ascii=*/false);
4735 return SendPacketNoLock(response.GetString());
4736 }
4737 }
4738 return SendErrorResponse(
4739 Status::FromErrorString("unknown accelerator plugin name"));
4740}
4741
4744 StringExtractorGDBRemote &packet) {
4745 packet.ConsumeFront("jAcceleratorPluginGetDynamicLoaderLibraryInfo:");
4746 llvm::Expected<AcceleratorDynamicLoaderArgs> args =
4747 llvm::json::parse<AcceleratorDynamicLoaderArgs>(
4748 packet.Peek(), "AcceleratorDynamicLoaderArgs");
4749 if (!args)
4750 return SendErrorResponse(args.takeError());
4751
4752 // On the accelerator connection, ask the process directly.
4754 if (!m_current_process)
4755 return SendErrorResponse(Status::FromErrorString("no current process"));
4756 std::optional<AcceleratorDynamicLoaderResponse> response =
4757 m_current_process->GetAcceleratorDynamicLoaderLibraryInfos(*args);
4758 if (!response)
4759 return SendErrorResponse(
4760 Status::FromErrorString("dynamic loader library info not supported"));
4761 StreamGDBRemote stream;
4762 stream.PutAsJSON(*response, /*hex_ascii=*/false);
4763 return SendPacketNoLock(stream.GetString());
4764 }
4765
4766 // On the native connection, forward to the named accelerator plugin.
4767 for (std::unique_ptr<lldb_server::LLDBServerAcceleratorPlugin> &plugin_up :
4769 if (plugin_up->GetPluginName() == args->plugin_name) {
4770 std::optional<AcceleratorDynamicLoaderResponse> response =
4771 plugin_up->GetDynamicLoaderLibraryInfos(*args);
4772 if (!response)
4773 return SendErrorResponse(
4774 Status::FromErrorString("no dynamic loader info available"));
4775
4776 StreamGDBRemote stream;
4777 stream.PutAsJSON(*response, /*hex_ascii=*/false);
4778 return SendPacketNoLock(stream.GetString());
4779 }
4780 }
4781 return SendErrorResponse(
4782 Status::FromErrorString("unknown accelerator plugin name"));
4783}
4784
4787 StringExtractorGDBRemote &packet) {
4788 llvm::StringRef packet_str = packet.GetStringRef();
4789 if (!packet_str.consume_front("jThreadExtendedInfo:"))
4790 return SendIllFormedResponse(packet,
4791 "Invalid jThreadExtendedInfo packet prefix");
4792 // Empty packet is sent to check if we support jThreadExtendedInfo.
4793 if (packet_str.empty())
4794 return SendOKResponse();
4795
4796 llvm::Expected<llvm::json::Value> parsed = llvm::json::parse(packet_str);
4797 if (!parsed) {
4798 llvm::consumeError(parsed.takeError());
4799 return SendIllFormedResponse(
4800 packet, "jThreadExtendedInfo did not contain valid JSON");
4801 }
4802 llvm::json::Object *request_dict = parsed->getAsObject();
4803 if (!request_dict)
4804 return SendIllFormedResponse(
4805 packet, "jThreadExtendedInfo did not contain a JSON dictionary");
4806
4807 std::optional<int64_t> thread_id = request_dict->getInteger("thread");
4808 if (!thread_id)
4809 return SendIllFormedResponse(packet, "jThreadExtendedInfo did not contain "
4810 "a valid 'thread' field");
4811
4812 if (!m_current_process)
4813 return SendErrorResponse(createStringError("no current process"));
4814
4815 NativeThreadProtocol *thread = m_current_process->GetThreadByID(*thread_id);
4816 if (!thread)
4817 return SendErrorResponse(
4818 createStringErrorV("no thread with specified ID ({0:x})", *thread_id));
4819
4820 StructuredData::ObjectSP ext_info = thread->GetExtendedInfo();
4821
4822 StreamString stream;
4823 if (ext_info)
4824 ext_info->Dump(stream, false);
4825
4826 StringRef response_str = stream.GetString();
4827 StreamGDBRemote response;
4828 response.PutEscapedBytes(response_str.data(), response_str.size());
4829 return SendPacketNoLock(response.GetString());
4830}
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)
bool GetNameColonValue(llvm::StringRef &name, llvm::StringRef &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
An address in a process, qualified by an address space.
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
void SetNameMatchType(NameMatch name_match_type)
ProcessInstanceInfo & GetProcessInfo()
const std::string & GetID() const
virtual void ToXML(Stream &strm, std::unordered_set< std::string > &previously_emitted, const RegisterType *user=nullptr) const
Output XML that describes this type, to be inserted into a target XML file.
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
std::shared_ptr< Object > ObjectSP
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)
GDBRemoteCommunicationServerLLGS(MainLoop &mainloop, NativeProcessProtocol::Manager &process_manager, llvm::StringRef name)
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)
lldb_server::LLDBServerAcceleratorPlugin * m_connection_accelerator_plugin
The plugin that owns this accelerator connection.
PacketResult SendStopReplyPacketForThread(NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous)
PacketResult Handle_jAcceleratorPluginGetDynamicLoaderLibraryInfo(StringExtractorGDBRemote &packet)
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_DEFAULT_ADDRESS_SPACE_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
@ eStopReasonDynamicLoader
Indicates that execution stopped so a dynamic-loader plugin can update the loaded libraries.
@ eStopReasonHistoryBoundary
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonInterrupt
Thread requested interrupt.
@ eStopReasonProcessorTrace
@ eStopReasonThreadExiting
@ eStopReasonException
@ eStopReasonWatchpoint
uint64_t addr_space_t
Definition lldb-types.h:81
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