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