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