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