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