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