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