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