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