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