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