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
264 return Status("%s: no process command line specified to launch",
265 __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(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(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())
351 return Status("cannot attach to process %" PRIu64
352 " when another process with pid %" PRIu64
353 " 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(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.SetErrorString(error_stream.GetString());
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.SetErrorString("failed to create ConnectionFileDescriptor");
1216 return error;
1217 }
1218
1220 m_stdio_communication.SetConnection(std::move(conn_up));
1222 error.SetErrorString(
1223 "failed to set connection for inferior I/O communication");
1224 return error;
1225 }
1226
1227 return Status();
1228}
1229
1231 // Don't forward if not connected (e.g. when attaching).
1233 return;
1234
1235 Status error;
1236 assert(!m_stdio_handle_up);
1239 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1240
1241 if (!m_stdio_handle_up) {
1242 // Not much we can do about the failure. Log it and continue without
1243 // forwarding.
1244 if (Log *log = GetLog(LLDBLog::Process))
1245 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1246 }
1247}
1248
1250 m_stdio_handle_up.reset();
1251}
1252
1254 char buffer[1024];
1255 ConnectionStatus status;
1256 Status error;
1257 while (true) {
1258 size_t bytes_read = m_stdio_communication.Read(
1259 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1260 switch (status) {
1262 SendONotification(buffer, bytes_read);
1263 break;
1268 if (Log *log = GetLog(LLDBLog::Process))
1269 LLDB_LOGF(log,
1270 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1271 "forwarding as communication returned status %d (error: "
1272 "%s)",
1273 __FUNCTION__, status, error.AsCString());
1274 m_stdio_handle_up.reset();
1275 return;
1276
1279 return;
1280 }
1281 }
1282}
1283
1286 StringExtractorGDBRemote &packet) {
1287
1288 // Fail if we don't have a current process.
1289 if (!m_current_process ||
1291 return SendErrorResponse(Status("Process not running."));
1292
1294}
1295
1298 StringExtractorGDBRemote &packet) {
1299 // Fail if we don't have a current process.
1300 if (!m_current_process ||
1302 return SendErrorResponse(Status("Process not running."));
1303
1304 packet.ConsumeFront("jLLDBTraceStop:");
1305 Expected<TraceStopRequest> stop_request =
1306 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1307 if (!stop_request)
1308 return SendErrorResponse(stop_request.takeError());
1309
1310 if (Error err = m_current_process->TraceStop(*stop_request))
1311 return SendErrorResponse(std::move(err));
1312
1313 return SendOKResponse();
1314}
1315
1318 StringExtractorGDBRemote &packet) {
1319
1320 // Fail if we don't have a current process.
1321 if (!m_current_process ||
1323 return SendErrorResponse(Status("Process not running."));
1324
1325 packet.ConsumeFront("jLLDBTraceStart:");
1326 Expected<TraceStartRequest> request =
1327 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1328 if (!request)
1329 return SendErrorResponse(request.takeError());
1330
1331 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1332 return SendErrorResponse(std::move(err));
1333
1334 return SendOKResponse();
1335}
1336
1339 StringExtractorGDBRemote &packet) {
1340
1341 // Fail if we don't have a current process.
1342 if (!m_current_process ||
1344 return SendErrorResponse(Status("Process not running."));
1345
1346 packet.ConsumeFront("jLLDBTraceGetState:");
1347 Expected<TraceGetStateRequest> request =
1348 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1349 if (!request)
1350 return SendErrorResponse(request.takeError());
1351
1352 return SendJSONResponse(m_current_process->TraceGetState(request->type));
1353}
1354
1357 StringExtractorGDBRemote &packet) {
1358
1359 // Fail if we don't have a current process.
1360 if (!m_current_process ||
1362 return SendErrorResponse(Status("Process not running."));
1363
1364 packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1365 llvm::Expected<TraceGetBinaryDataRequest> request =
1366 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1367 "TraceGetBinaryDataRequest");
1368 if (!request)
1369 return SendErrorResponse(Status(request.takeError()));
1370
1371 if (Expected<std::vector<uint8_t>> bytes =
1373 StreamGDBRemote response;
1374 response.PutEscapedBytes(bytes->data(), bytes->size());
1375 return SendPacketNoLock(response.GetString());
1376 } else
1377 return SendErrorResponse(bytes.takeError());
1378}
1379
1382 StringExtractorGDBRemote &packet) {
1383 // Fail if we don't have a current process.
1384 if (!m_current_process ||
1386 return SendErrorResponse(68);
1387
1389
1390 if (pid == LLDB_INVALID_PROCESS_ID)
1391 return SendErrorResponse(1);
1392
1393 ProcessInstanceInfo proc_info;
1394 if (!Host::GetProcessInfo(pid, proc_info))
1395 return SendErrorResponse(1);
1396
1397 StreamString response;
1398 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1399 return SendPacketNoLock(response.GetString());
1400}
1401
1404 // Fail if we don't have a current process.
1405 if (!m_current_process ||
1407 return SendErrorResponse(68);
1408
1409 // Make sure we set the current thread so g and p packets return the data the
1410 // gdb will expect.
1412 SetCurrentThreadID(tid);
1413
1415 if (!thread)
1416 return SendErrorResponse(69);
1417
1418 StreamString response;
1419 response.PutCString("QC");
1421 thread->GetID());
1422
1423 return SendPacketNoLock(response.GetString());
1424}
1425
1428 Log *log = GetLog(LLDBLog::Process);
1429
1430 if (!m_non_stop)
1432
1433 if (m_debugged_processes.empty()) {
1434 LLDB_LOG(log, "No debugged process found.");
1435 return PacketResult::Success;
1436 }
1437
1438 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1439 ++it) {
1440 LLDB_LOG(log, "Killing process {0}", it->first);
1441 Status error = it->second.process_up->Kill();
1442 if (error.Fail())
1443 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1444 error);
1445 }
1446
1447 // The response to kill packet is undefined per the spec. LLDB
1448 // follows the same rules as for continue packets, i.e. no response
1449 // in all-stop mode, and "OK" in non-stop mode; in both cases this
1450 // is followed by the actual stop reason.
1452}
1453
1456 StringExtractorGDBRemote &packet) {
1457 if (!m_non_stop)
1459
1460 packet.SetFilePos(6); // vKill;
1461 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1462 if (pid == LLDB_INVALID_PROCESS_ID)
1463 return SendIllFormedResponse(packet,
1464 "vKill failed to parse the process id");
1465
1466 auto it = m_debugged_processes.find(pid);
1467 if (it == m_debugged_processes.end())
1468 return SendErrorResponse(42);
1469
1470 Status error = it->second.process_up->Kill();
1471 if (error.Fail())
1472 return SendErrorResponse(error.ToError());
1473
1474 // OK response is sent when the process dies.
1475 it->second.flags |= DebuggedProcess::Flag::vkilled;
1476 return PacketResult::Success;
1477}
1478
1481 StringExtractorGDBRemote &packet) {
1482 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1483 if (packet.GetU32(0))
1484 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1485 else
1486 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1487 return SendOKResponse();
1488}
1489
1492 StringExtractorGDBRemote &packet) {
1493 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1494 std::string path;
1495 packet.GetHexByteString(path);
1497 return SendOKResponse();
1498}
1499
1502 StringExtractorGDBRemote &packet) {
1504 if (working_dir) {
1505 StreamString response;
1506 response.PutStringAsRawHex8(working_dir.GetPath().c_str());
1507 return SendPacketNoLock(response.GetString());
1508 }
1509
1510 return SendErrorResponse(14);
1511}
1512
1515 StringExtractorGDBRemote &packet) {
1517 return SendOKResponse();
1518}
1519
1522 StringExtractorGDBRemote &packet) {
1524 return SendOKResponse();
1525}
1526
1529 NativeProcessProtocol &process, const ResumeActionList &actions) {
1531
1532 // In non-stop protocol mode, the process could be running already.
1533 // We do not support resuming threads independently, so just error out.
1534 if (!process.CanResume()) {
1535 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1536 process.GetState());
1537 return SendErrorResponse(0x37);
1538 }
1539
1540 Status error = process.Resume(actions);
1541 if (error.Fail()) {
1542 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1543 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1544 }
1545
1546 LLDB_LOG(log, "process {0} resumed", process.GetID());
1547
1548 return PacketResult::Success;
1549}
1550
1554 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1555
1556 // Ensure we have a native process.
1557 if (!m_continue_process) {
1558 LLDB_LOGF(log,
1559 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1560 "shared pointer",
1561 __FUNCTION__);
1562 return SendErrorResponse(0x36);
1563 }
1564
1565 // Pull out the signal number.
1566 packet.SetFilePos(::strlen("C"));
1567 if (packet.GetBytesLeft() < 1) {
1568 // Shouldn't be using a C without a signal.
1569 return SendIllFormedResponse(packet, "C packet specified without signal.");
1570 }
1571 const uint32_t signo =
1572 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1573 if (signo == std::numeric_limits<uint32_t>::max())
1574 return SendIllFormedResponse(packet, "failed to parse signal number");
1575
1576 // Handle optional continue address.
1577 if (packet.GetBytesLeft() > 0) {
1578 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1579 if (*packet.Peek() == ';')
1580 return SendUnimplementedResponse(packet.GetStringRef().data());
1581 else
1582 return SendIllFormedResponse(
1583 packet, "unexpected content after $C{signal-number}");
1584 }
1585
1586 // In non-stop protocol mode, the process could be running already.
1587 // We do not support resuming threads independently, so just error out.
1588 if (!m_continue_process->CanResume()) {
1589 LLDB_LOG(log, "process cannot be resumed (state={0})",
1591 return SendErrorResponse(0x37);
1592 }
1593
1594 ResumeActionList resume_actions(StateType::eStateRunning,
1596 Status error;
1597
1598 // We have two branches: what to do if a continue thread is specified (in
1599 // which case we target sending the signal to that thread), or when we don't
1600 // have a continue thread set (in which case we send a signal to the
1601 // process).
1602
1603 // TODO discuss with Greg Clayton, make sure this makes sense.
1604
1605 lldb::tid_t signal_tid = GetContinueThreadID();
1606 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1607 // The resume action for the continue thread (or all threads if a continue
1608 // thread is not set).
1609 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1610 static_cast<int>(signo)};
1611
1612 // Add the action for the continue thread (or all threads when the continue
1613 // thread isn't present).
1614 resume_actions.Append(action);
1615 } else {
1616 // Send the signal to the process since we weren't targeting a specific
1617 // continue thread with the signal.
1619 if (error.Fail()) {
1620 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1622
1623 return SendErrorResponse(0x52);
1624 }
1625 }
1626
1627 // NB: this checks CanResume() twice but using a single code path for
1628 // resuming still seems worth it.
1629 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1630 if (resume_res != PacketResult::Success)
1631 return resume_res;
1632
1633 // Don't send an "OK" packet, except in non-stop mode;
1634 // otherwise, the response is the stopped/exited message.
1636}
1637
1641 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1642
1643 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1644
1645 // For now just support all continue.
1646 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1647 if (has_continue_address) {
1648 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1649 packet.Peek());
1650 return SendUnimplementedResponse(packet.GetStringRef().data());
1651 }
1652
1653 // Ensure we have a native process.
1654 if (!m_continue_process) {
1655 LLDB_LOGF(log,
1656 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1657 "shared pointer",
1658 __FUNCTION__);
1659 return SendErrorResponse(0x36);
1660 }
1661
1662 // Build the ResumeActionList
1663 ResumeActionList actions(StateType::eStateRunning,
1665
1666 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1667 if (resume_res != PacketResult::Success)
1668 return resume_res;
1669
1671}
1672
1675 StringExtractorGDBRemote &packet) {
1676 StreamString response;
1677 response.Printf("vCont;c;C;s;S;t");
1678
1679 return SendPacketNoLock(response.GetString());
1680}
1681
1683 // We're doing a stop-all if and only if our only action is a "t" for all
1684 // threads.
1685 if (const ResumeAction *default_action =
1687 if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1688 return true;
1689 }
1690
1691 return false;
1692}
1693
1696 StringExtractorGDBRemote &packet) {
1697 Log *log = GetLog(LLDBLog::Process);
1698 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1699 __FUNCTION__);
1700
1701 packet.SetFilePos(::strlen("vCont"));
1702
1703 if (packet.GetBytesLeft() == 0) {
1704 LLDB_LOGF(log,
1705 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1706 "vCont package",
1707 __FUNCTION__);
1708 return SendIllFormedResponse(packet, "Missing action from vCont package");
1709 }
1710
1711 if (::strcmp(packet.Peek(), ";s") == 0) {
1712 // Move past the ';', then do a simple 's'.
1713 packet.SetFilePos(packet.GetFilePos() + 1);
1714 return Handle_s(packet);
1715 }
1716
1717 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1718
1719 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1720 // Skip the semi-colon.
1721 packet.GetChar();
1722
1723 // Build up the thread action.
1724 ResumeAction thread_action;
1725 thread_action.tid = LLDB_INVALID_THREAD_ID;
1726 thread_action.state = eStateInvalid;
1727 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1728
1729 const char action = packet.GetChar();
1730 switch (action) {
1731 case 'C':
1732 thread_action.signal = packet.GetHexMaxU32(false, 0);
1733 if (thread_action.signal == 0)
1734 return SendIllFormedResponse(
1735 packet, "Could not parse signal in vCont packet C action");
1736 [[fallthrough]];
1737
1738 case 'c':
1739 // Continue
1740 thread_action.state = eStateRunning;
1741 break;
1742
1743 case 'S':
1744 thread_action.signal = packet.GetHexMaxU32(false, 0);
1745 if (thread_action.signal == 0)
1746 return SendIllFormedResponse(
1747 packet, "Could not parse signal in vCont packet S action");
1748 [[fallthrough]];
1749
1750 case 's':
1751 // Step
1752 thread_action.state = eStateStepping;
1753 break;
1754
1755 case 't':
1756 // Stop
1757 thread_action.state = eStateSuspended;
1758 break;
1759
1760 default:
1761 return SendIllFormedResponse(packet, "Unsupported vCont action");
1762 break;
1763 }
1764
1765 // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".
1768
1769 // Parse out optional :{thread-id} value.
1770 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1771 // Consume the separator.
1772 packet.GetChar();
1773
1774 auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);
1775 if (!pid_tid)
1776 return SendIllFormedResponse(packet, "Malformed thread-id");
1777
1778 pid = pid_tid->first;
1779 tid = pid_tid->second;
1780 }
1781
1782 if (thread_action.state == eStateSuspended &&
1784 return SendIllFormedResponse(
1785 packet, "'t' action not supported for individual threads");
1786 }
1787
1788 // If we get TID without PID, it's the current process.
1789 if (pid == LLDB_INVALID_PROCESS_ID) {
1790 if (!m_continue_process) {
1791 LLDB_LOG(log, "no process selected via Hc");
1792 return SendErrorResponse(0x36);
1793 }
1794 pid = m_continue_process->GetID();
1795 }
1796
1797 assert(pid != LLDB_INVALID_PROCESS_ID);
1800 thread_action.tid = tid;
1801
1803 if (tid != LLDB_INVALID_THREAD_ID)
1804 return SendIllFormedResponse(
1805 packet, "vCont: p-1 is not valid with a specific tid");
1806 for (auto &process_it : m_debugged_processes)
1807 thread_actions[process_it.first].Append(thread_action);
1808 } else
1809 thread_actions[pid].Append(thread_action);
1810 }
1811
1812 assert(thread_actions.size() >= 1);
1813 if (thread_actions.size() > 1 && !m_non_stop)
1814 return SendIllFormedResponse(
1815 packet,
1816 "Resuming multiple processes is supported in non-stop mode only");
1817
1818 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1819 auto process_it = m_debugged_processes.find(x.first);
1820 if (process_it == m_debugged_processes.end()) {
1821 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1822 x.first);
1823 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1824 }
1825
1826 // There are four possible scenarios here. These are:
1827 // 1. vCont on a stopped process that resumes at least one thread.
1828 // In this case, we call Resume().
1829 // 2. vCont on a stopped process that leaves all threads suspended.
1830 // A no-op.
1831 // 3. vCont on a running process that requests suspending all
1832 // running threads. In this case, we call Interrupt().
1833 // 4. vCont on a running process that requests suspending a subset
1834 // of running threads or resuming a subset of suspended threads.
1835 // Since we do not support full nonstop mode, this is unsupported
1836 // and we return an error.
1837
1838 assert(process_it->second.process_up);
1839 if (ResumeActionListStopsAllThreads(x.second)) {
1840 if (process_it->second.process_up->IsRunning()) {
1841 assert(m_non_stop);
1842
1843 Status error = process_it->second.process_up->Interrupt();
1844 if (error.Fail()) {
1845 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1846 error);
1847 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1848 }
1849
1850 LLDB_LOG(log, "halted process {0}", x.first);
1851
1852 // hack to avoid enabling stdio forwarding after stop
1853 // TODO: remove this when we improve stdio forwarding for nonstop
1854 assert(thread_actions.size() == 1);
1855 return SendOKResponse();
1856 }
1857 } else {
1858 PacketResult resume_res =
1859 ResumeProcess(*process_it->second.process_up, x.second);
1860 if (resume_res != PacketResult::Success)
1861 return resume_res;
1862 }
1863 }
1864
1866}
1867
1869 Log *log = GetLog(LLDBLog::Thread);
1870 LLDB_LOG(log, "setting current thread id to {0}", tid);
1871
1872 m_current_tid = tid;
1875}
1876
1878 Log *log = GetLog(LLDBLog::Thread);
1879 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1880
1881 m_continue_tid = tid;
1882}
1883
1886 StringExtractorGDBRemote &packet) {
1887 // Handle the $? gdbremote command.
1888
1889 if (m_non_stop) {
1890 // Clear the notification queue first, except for pending exit
1891 // notifications.
1892 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
1893 return x.front() != 'W' && x.front() != 'X';
1894 });
1895
1896 if (m_current_process) {
1897 // Queue stop reply packets for all active threads. Start with
1898 // the current thread (for clients that don't actually support multiple
1899 // stop reasons).
1901 if (thread) {
1902 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
1903 if (!stop_reply.Empty())
1904 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1905 }
1906 EnqueueStopReplyPackets(thread ? thread->GetID()
1908 }
1909
1910 // If the notification queue is empty (i.e. everything is running), send OK.
1911 if (m_stop_notification_queue.empty())
1912 return SendOKResponse();
1913
1914 // Send the first item from the new notification queue synchronously.
1916 }
1917
1918 // If no process, indicate error
1919 if (!m_current_process)
1920 return SendErrorResponse(02);
1921
1924 /*force_synchronous=*/true);
1925}
1926
1929 NativeProcessProtocol &process, lldb::StateType process_state,
1930 bool force_synchronous) {
1931 Log *log = GetLog(LLDBLog::Process);
1932
1934 // Check if we are waiting for any more processes to stop. If we are,
1935 // do not send the OK response yet.
1936 for (const auto &it : m_debugged_processes) {
1937 if (it.second.process_up->IsRunning())
1938 return PacketResult::Success;
1939 }
1940
1941 // If all expected processes were stopped after a QNonStop:0 request,
1942 // send the OK response.
1943 m_disabling_non_stop = false;
1944 return SendOKResponse();
1945 }
1946
1947 switch (process_state) {
1948 case eStateAttaching:
1949 case eStateLaunching:
1950 case eStateRunning:
1951 case eStateStepping:
1952 case eStateDetached:
1953 // NOTE: gdb protocol doc looks like it should return $OK
1954 // when everything is running (i.e. no stopped result).
1955 return PacketResult::Success; // Ignore
1956
1957 case eStateSuspended:
1958 case eStateStopped:
1959 case eStateCrashed: {
1960 lldb::tid_t tid = process.GetCurrentThreadID();
1961 // Make sure we set the current thread so g and p packets return the data
1962 // the gdb will expect.
1963 SetCurrentThreadID(tid);
1964 return SendStopReplyPacketForThread(process, tid, force_synchronous);
1965 }
1966
1967 case eStateInvalid:
1968 case eStateUnloaded:
1969 case eStateExited:
1970 return SendWResponse(&process);
1971
1972 default:
1973 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1974 process.GetID(), process_state);
1975 break;
1976 }
1977
1978 return SendErrorResponse(0);
1979}
1980
1983 StringExtractorGDBRemote &packet) {
1984 // Fail if we don't have a current process.
1985 if (!m_current_process ||
1987 return SendErrorResponse(68);
1988
1989 // Ensure we have a thread.
1991 if (!thread)
1992 return SendErrorResponse(69);
1993
1994 // Get the register context for the first thread.
1995 NativeRegisterContext &reg_context = thread->GetRegisterContext();
1996
1997 // Parse out the register number from the request.
1998 packet.SetFilePos(strlen("qRegisterInfo"));
1999 const uint32_t reg_index =
2000 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2001 if (reg_index == std::numeric_limits<uint32_t>::max())
2002 return SendErrorResponse(69);
2003
2004 // Return the end of registers response if we've iterated one past the end of
2005 // the register set.
2006 if (reg_index >= reg_context.GetUserRegisterCount())
2007 return SendErrorResponse(69);
2008
2009 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2010 if (!reg_info)
2011 return SendErrorResponse(69);
2012
2013 // Build the reginfos response.
2014 StreamGDBRemote response;
2015
2016 response.PutCString("name:");
2017 response.PutCString(reg_info->name);
2018 response.PutChar(';');
2019
2020 if (reg_info->alt_name && reg_info->alt_name[0]) {
2021 response.PutCString("alt-name:");
2022 response.PutCString(reg_info->alt_name);
2023 response.PutChar(';');
2024 }
2025
2026 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2027
2028 if (!reg_context.RegisterOffsetIsDynamic())
2029 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2030
2031 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2032 if (!encoding.empty())
2033 response << "encoding:" << encoding << ';';
2034
2035 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2036 if (!format.empty())
2037 response << "format:" << format << ';';
2038
2039 const char *const register_set_name =
2040 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2041 if (register_set_name)
2042 response << "set:" << register_set_name << ';';
2043
2044 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2046 response.Printf("ehframe:%" PRIu32 ";",
2047 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2048
2049 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2050 response.Printf("dwarf:%" PRIu32 ";",
2051 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2052
2053 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2054 if (!kind_generic.empty())
2055 response << "generic:" << kind_generic << ';';
2056
2057 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2058 response.PutCString("container-regs:");
2059 CollectRegNums(reg_info->value_regs, response, true);
2060 response.PutChar(';');
2061 }
2062
2063 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2064 response.PutCString("invalidate-regs:");
2065 CollectRegNums(reg_info->invalidate_regs, response, true);
2066 response.PutChar(';');
2067 }
2068
2069 return SendPacketNoLock(response.GetString());
2070}
2071
2073 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2074 Log *log = GetLog(LLDBLog::Thread);
2075
2076 lldb::pid_t pid = process.GetID();
2077 if (pid == LLDB_INVALID_PROCESS_ID)
2078 return;
2079
2080 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2081 for (NativeThreadProtocol &thread : process.Threads()) {
2082 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2083 response.PutChar(had_any ? ',' : 'm');
2084 AppendThreadIDToResponse(response, pid, thread.GetID());
2085 had_any = true;
2086 }
2087}
2088
2091 StringExtractorGDBRemote &packet) {
2092 assert(m_debugged_processes.size() <= 1 ||
2095
2096 bool had_any = false;
2097 StreamGDBRemote response;
2098
2099 for (auto &pid_ptr : m_debugged_processes)
2100 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2101
2102 if (!had_any)
2103 return SendOKResponse();
2104 return SendPacketNoLock(response.GetString());
2105}
2106
2109 StringExtractorGDBRemote &packet) {
2110 // FIXME for now we return the full thread list in the initial packet and
2111 // always do nothing here.
2112 return SendPacketNoLock("l");
2113}
2114
2117 Log *log = GetLog(LLDBLog::Thread);
2118
2119 // Move past packet name.
2120 packet.SetFilePos(strlen("g"));
2121
2122 // Get the thread to use.
2123 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2124 if (!thread) {
2125 LLDB_LOG(log, "failed, no thread available");
2126 return SendErrorResponse(0x15);
2127 }
2128
2129 // Get the thread's register context.
2130 NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
2131
2132 std::vector<uint8_t> regs_buffer;
2133 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2134 ++reg_num) {
2135 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2136
2137 if (reg_info == nullptr) {
2138 LLDB_LOG(log, "failed to get register info for register index {0}",
2139 reg_num);
2140 return SendErrorResponse(0x15);
2141 }
2142
2143 if (reg_info->value_regs != nullptr)
2144 continue; // skip registers that are contained in other registers
2145
2146 RegisterValue reg_value;
2147 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2148 if (error.Fail()) {
2149 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2150 return SendErrorResponse(0x15);
2151 }
2152
2153 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2154 // Resize the buffer to guarantee it can store the register offsetted
2155 // data.
2156 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2157
2158 // Copy the register offsetted data to the buffer.
2159 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2160 reg_info->byte_size);
2161 }
2162
2163 // Write the response.
2164 StreamGDBRemote response;
2165 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2166
2167 return SendPacketNoLock(response.GetString());
2168}
2169
2172 Log *log = GetLog(LLDBLog::Thread);
2173
2174 // Parse out the register number from the request.
2175 packet.SetFilePos(strlen("p"));
2176 const uint32_t reg_index =
2177 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2178 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2179 LLDB_LOGF(log,
2180 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2181 "parse register number from request \"%s\"",
2182 __FUNCTION__, packet.GetStringRef().data());
2183 return SendErrorResponse(0x15);
2184 }
2185
2186 // Get the thread to use.
2187 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2188 if (!thread) {
2189 LLDB_LOG(log, "failed, no thread available");
2190 return SendErrorResponse(0x15);
2191 }
2192
2193 // Get the thread's register context.
2194 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2195
2196 // Return the end of registers response if we've iterated one past the end of
2197 // the register set.
2198 if (reg_index >= reg_context.GetUserRegisterCount()) {
2199 LLDB_LOGF(log,
2200 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2201 "register %" PRIu32 " beyond register count %" PRIu32,
2202 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2203 return SendErrorResponse(0x15);
2204 }
2205
2206 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2207 if (!reg_info) {
2208 LLDB_LOGF(log,
2209 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2210 "register %" PRIu32 " returned NULL",
2211 __FUNCTION__, reg_index);
2212 return SendErrorResponse(0x15);
2213 }
2214
2215 // Build the reginfos response.
2216 StreamGDBRemote response;
2217
2218 // Retrieve the value
2219 RegisterValue reg_value;
2220 Status error = reg_context.ReadRegister(reg_info, reg_value);
2221 if (error.Fail()) {
2222 LLDB_LOGF(log,
2223 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2224 "requested register %" PRIu32 " (%s) failed: %s",
2225 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2226 return SendErrorResponse(0x15);
2227 }
2228
2229 const uint8_t *const data =
2230 static_cast<const uint8_t *>(reg_value.GetBytes());
2231 if (!data) {
2232 LLDB_LOGF(log,
2233 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2234 "bytes from requested register %" PRIu32,
2235 __FUNCTION__, reg_index);
2236 return SendErrorResponse(0x15);
2237 }
2238
2239 // FIXME flip as needed to get data in big/little endian format for this host.
2240 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2241 response.PutHex8(data[i]);
2242
2243 return SendPacketNoLock(response.GetString());
2244}
2245
2248 Log *log = GetLog(LLDBLog::Thread);
2249
2250 // Ensure there is more content.
2251 if (packet.GetBytesLeft() < 1)
2252 return SendIllFormedResponse(packet, "Empty P packet");
2253
2254 // Parse out the register number from the request.
2255 packet.SetFilePos(strlen("P"));
2256 const uint32_t reg_index =
2257 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2258 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2259 LLDB_LOGF(log,
2260 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2261 "parse register number from request \"%s\"",
2262 __FUNCTION__, packet.GetStringRef().data());
2263 return SendErrorResponse(0x29);
2264 }
2265
2266 // Note debugserver would send an E30 here.
2267 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2268 return SendIllFormedResponse(
2269 packet, "P packet missing '=' char after register number");
2270
2271 // Parse out the value.
2272 size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);
2273
2274 // Get the thread to use.
2275 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2276 if (!thread) {
2277 LLDB_LOGF(log,
2278 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2279 "available (thread index 0)",
2280 __FUNCTION__);
2281 return SendErrorResponse(0x28);
2282 }
2283
2284 // Get the thread's register context.
2285 NativeRegisterContext &reg_context = thread->GetRegisterContext();
2286 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2287 if (!reg_info) {
2288 LLDB_LOGF(log,
2289 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2290 "register %" PRIu32 " returned NULL",
2291 __FUNCTION__, reg_index);
2292 return SendErrorResponse(0x48);
2293 }
2294
2295 // Return the end of registers response if we've iterated one past the end of
2296 // the register set.
2297 if (reg_index >= reg_context.GetUserRegisterCount()) {
2298 LLDB_LOGF(log,
2299 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2300 "register %" PRIu32 " beyond register count %" PRIu32,
2301 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2302 return SendErrorResponse(0x47);
2303 }
2304
2305 if (reg_size != reg_info->byte_size)
2306 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2307
2308 // Build the reginfos response.
2309 StreamGDBRemote response;
2310
2311 RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),
2313 Status error = reg_context.WriteRegister(reg_info, reg_value);
2314 if (error.Fail()) {
2315 LLDB_LOGF(log,
2316 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2317 "requested register %" PRIu32 " (%s) failed: %s",
2318 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2319 return SendErrorResponse(0x32);
2320 }
2321
2322 return SendOKResponse();
2323}
2324
2327 Log *log = GetLog(LLDBLog::Thread);
2328
2329 // Parse out which variant of $H is requested.
2330 packet.SetFilePos(strlen("H"));
2331 if (packet.GetBytesLeft() < 1) {
2332 LLDB_LOGF(log,
2333 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2334 "missing {g,c} variant",
2335 __FUNCTION__);
2336 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2337 }
2338
2339 const char h_variant = packet.GetChar();
2340 NativeProcessProtocol *default_process;
2341 switch (h_variant) {
2342 case 'g':
2343 default_process = m_current_process;
2344 break;
2345
2346 case 'c':
2347 default_process = m_continue_process;
2348 break;
2349
2350 default:
2351 LLDB_LOGF(
2352 log,
2353 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2354 __FUNCTION__, h_variant);
2355 return SendIllFormedResponse(packet,
2356 "H variant unsupported, should be c or g");
2357 }
2358
2359 // Parse out the thread number.
2360 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2362 if (!pid_tid)
2363 return SendErrorResponse(llvm::make_error<StringError>(
2364 inconvertibleErrorCode(), "Malformed thread-id"));
2365
2366 lldb::pid_t pid = pid_tid->first;
2367 lldb::tid_t tid = pid_tid->second;
2368
2370 return SendUnimplementedResponse("Selecting all processes not supported");
2371 if (pid == LLDB_INVALID_PROCESS_ID)
2372 return SendErrorResponse(llvm::make_error<StringError>(
2373 inconvertibleErrorCode(), "No current process and no PID provided"));
2374
2375 // Check the process ID and find respective process instance.
2376 auto new_process_it = m_debugged_processes.find(pid);
2377 if (new_process_it == m_debugged_processes.end())
2378 return SendErrorResponse(llvm::make_error<StringError>(
2379 inconvertibleErrorCode(),
2380 llvm::formatv("No process with PID {0} debugged", pid)));
2381
2382 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2383 // (any thread).
2384 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2385 NativeThreadProtocol *thread =
2386 new_process_it->second.process_up->GetThreadByID(tid);
2387 if (!thread) {
2388 LLDB_LOGF(log,
2389 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2390 " not found",
2391 __FUNCTION__, tid);
2392 return SendErrorResponse(0x15);
2393 }
2394 }
2395
2396 // Now switch the given process and thread type.
2397 switch (h_variant) {
2398 case 'g':
2399 m_current_process = new_process_it->second.process_up.get();
2400 SetCurrentThreadID(tid);
2401 break;
2402
2403 case 'c':
2404 m_continue_process = new_process_it->second.process_up.get();
2406 break;
2407
2408 default:
2409 assert(false && "unsupported $H variant - shouldn't get here");
2410 return SendIllFormedResponse(packet,
2411 "H variant unsupported, should be c or g");
2412 }
2413
2414 return SendOKResponse();
2415}
2416
2419 Log *log = GetLog(LLDBLog::Thread);
2420
2421 // Fail if we don't have a current process.
2422 if (!m_current_process ||
2424 LLDB_LOGF(
2425 log,
2426 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2427 __FUNCTION__);
2428 return SendErrorResponse(0x15);
2429 }
2430
2431 packet.SetFilePos(::strlen("I"));
2432 uint8_t tmp[4096];
2433 for (;;) {
2434 size_t read = packet.GetHexBytesAvail(tmp);
2435 if (read == 0) {
2436 break;
2437 }
2438 // write directly to stdin *this might block if stdin buffer is full*
2439 // TODO: enqueue this block in circular buffer and send window size to
2440 // remote host
2441 ConnectionStatus status;
2442 Status error;
2443 m_stdio_communication.WriteAll(tmp, read, status, &error);
2444 if (error.Fail()) {
2445 return SendErrorResponse(0x15);
2446 }
2447 }
2448
2449 return SendOKResponse();
2450}
2451
2454 StringExtractorGDBRemote &packet) {
2456
2457 // Fail if we don't have a current process.
2458 if (!m_current_process ||
2460 LLDB_LOG(log, "failed, no process available");
2461 return SendErrorResponse(0x15);
2462 }
2463
2464 // Interrupt the process.
2466 if (error.Fail()) {
2467 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2468 error);
2469 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2470 }
2471
2472 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2473
2474 // No response required from stop all.
2475 return PacketResult::Success;
2476}
2477
2480 StringExtractorGDBRemote &packet) {
2481 Log *log = GetLog(LLDBLog::Process);
2482
2483 if (!m_current_process ||
2485 LLDB_LOGF(
2486 log,
2487 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2488 __FUNCTION__);
2489 return SendErrorResponse(0x15);
2490 }
2491
2492 // Parse out the memory address.
2493 packet.SetFilePos(strlen("m"));
2494 if (packet.GetBytesLeft() < 1)
2495 return SendIllFormedResponse(packet, "Too short m packet");
2496
2497 // Read the address. Punting on validation.
2498 // FIXME replace with Hex U64 read with no default value that fails on failed
2499 // read.
2500 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2501
2502 // Validate comma.
2503 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2504 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2505
2506 // Get # bytes to read.
2507 if (packet.GetBytesLeft() < 1)
2508 return SendIllFormedResponse(packet, "Length missing in m packet");
2509
2510 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2511 if (byte_count == 0) {
2512 LLDB_LOGF(log,
2513 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2514 "zero-length packet",
2515 __FUNCTION__);
2516 return SendOKResponse();
2517 }
2518
2519 // Allocate the response buffer.
2520 std::string buf(byte_count, '\0');
2521 if (buf.empty())
2522 return SendErrorResponse(0x78);
2523
2524 // Retrieve the process memory.
2525 size_t bytes_read = 0;
2527 read_addr, &buf[0], byte_count, bytes_read);
2528 if (error.Fail()) {
2529 LLDB_LOGF(log,
2530 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2531 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2532 __FUNCTION__, m_current_process->GetID(), read_addr,
2533 error.AsCString());
2534 return SendErrorResponse(0x08);
2535 }
2536
2537 if (bytes_read == 0) {
2538 LLDB_LOGF(log,
2539 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2540 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2541 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2542 return SendErrorResponse(0x08);
2543 }
2544
2545 StreamGDBRemote response;
2546 packet.SetFilePos(0);
2547 char kind = packet.GetChar('?');
2548 if (kind == 'x')
2549 response.PutEscapedBytes(buf.data(), byte_count);
2550 else {
2551 assert(kind == 'm');
2552 for (size_t i = 0; i < bytes_read; ++i)
2553 response.PutHex8(buf[i]);
2554 }
2555
2556 return SendPacketNoLock(response.GetString());
2557}
2558
2561 Log *log = GetLog(LLDBLog::Process);
2562
2563 if (!m_current_process ||
2565 LLDB_LOGF(
2566 log,
2567 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2568 __FUNCTION__);
2569 return SendErrorResponse(0x15);
2570 }
2571
2572 // Parse out the memory address.
2573 packet.SetFilePos(strlen("_M"));
2574 if (packet.GetBytesLeft() < 1)
2575 return SendIllFormedResponse(packet, "Too short _M packet");
2576
2577 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2578 if (size == LLDB_INVALID_ADDRESS)
2579 return SendIllFormedResponse(packet, "Address not valid");
2580 if (packet.GetChar() != ',')
2581 return SendIllFormedResponse(packet, "Bad packet");
2582 Permissions perms = {};
2583 while (packet.GetBytesLeft() > 0) {
2584 switch (packet.GetChar()) {
2585 case 'r':
2586 perms |= ePermissionsReadable;
2587 break;
2588 case 'w':
2589 perms |= ePermissionsWritable;
2590 break;
2591 case 'x':
2592 perms |= ePermissionsExecutable;
2593 break;
2594 default:
2595 return SendIllFormedResponse(packet, "Bad permissions");
2596 }
2597 }
2598
2599 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2600 if (!addr)
2601 return SendErrorResponse(addr.takeError());
2602
2603 StreamGDBRemote response;
2604 response.PutHex64(*addr);
2605 return SendPacketNoLock(response.GetString());
2606}
2607
2610 Log *log = GetLog(LLDBLog::Process);
2611
2612 if (!m_current_process ||
2614 LLDB_LOGF(
2615 log,
2616 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2617 __FUNCTION__);
2618 return SendErrorResponse(0x15);
2619 }
2620
2621 // Parse out the memory address.
2622 packet.SetFilePos(strlen("_m"));
2623 if (packet.GetBytesLeft() < 1)
2624 return SendIllFormedResponse(packet, "Too short m packet");
2625
2626 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2627 if (addr == LLDB_INVALID_ADDRESS)
2628 return SendIllFormedResponse(packet, "Address not valid");
2629
2630 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2631 return SendErrorResponse(std::move(Err));
2632
2633 return SendOKResponse();
2634}
2635
2638 Log *log = GetLog(LLDBLog::Process);
2639
2640 if (!m_current_process ||
2642 LLDB_LOGF(
2643 log,
2644 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2645 __FUNCTION__);
2646 return SendErrorResponse(0x15);
2647 }
2648
2649 // Parse out the memory address.
2650 packet.SetFilePos(strlen("M"));
2651 if (packet.GetBytesLeft() < 1)
2652 return SendIllFormedResponse(packet, "Too short M packet");
2653
2654 // Read the address. Punting on validation.
2655 // FIXME replace with Hex U64 read with no default value that fails on failed
2656 // read.
2657 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2658
2659 // Validate comma.
2660 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2661 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2662
2663 // Get # bytes to read.
2664 if (packet.GetBytesLeft() < 1)
2665 return SendIllFormedResponse(packet, "Length missing in M packet");
2666
2667 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2668 if (byte_count == 0) {
2669 LLDB_LOG(log, "nothing to write: zero-length packet");
2670 return PacketResult::Success;
2671 }
2672
2673 // Validate colon.
2674 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2675 return SendIllFormedResponse(
2676 packet, "Comma sep missing in M packet after byte length");
2677
2678 // Allocate the conversion buffer.
2679 std::vector<uint8_t> buf(byte_count, 0);
2680 if (buf.empty())
2681 return SendErrorResponse(0x78);
2682
2683 // Convert the hex memory write contents to bytes.
2684 StreamGDBRemote response;
2685 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2686 if (convert_count != byte_count) {
2687 LLDB_LOG(log,
2688 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2689 "to convert.",
2690 m_current_process->GetID(), write_addr, byte_count, convert_count);
2691 return SendIllFormedResponse(packet, "M content byte length specified did "
2692 "not match hex-encoded content "
2693 "length");
2694 }
2695
2696 // Write the process memory.
2697 size_t bytes_written = 0;
2698 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2699 bytes_written);
2700 if (error.Fail()) {
2701 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2702 m_current_process->GetID(), write_addr, error);
2703 return SendErrorResponse(0x09);
2704 }
2705
2706 if (bytes_written == 0) {
2707 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2708 m_current_process->GetID(), write_addr, byte_count);
2709 return SendErrorResponse(0x09);
2710 }
2711
2712 return SendOKResponse();
2713}
2714
2717 StringExtractorGDBRemote &packet) {
2718 Log *log = GetLog(LLDBLog::Process);
2719
2720 // Currently only the NativeProcessProtocol knows if it can handle a
2721 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2722 // attached to a process. For now we'll assume the client only asks this
2723 // when a process is being debugged.
2724
2725 // Ensure we have a process running; otherwise, we can't figure this out
2726 // since we won't have a NativeProcessProtocol.
2727 if (!m_current_process ||
2729 LLDB_LOGF(
2730 log,
2731 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2732 __FUNCTION__);
2733 return SendErrorResponse(0x15);
2734 }
2735
2736 // Test if we can get any region back when asking for the region around NULL.
2737 MemoryRegionInfo region_info;
2738 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2739 if (error.Fail()) {
2740 // We don't support memory region info collection for this
2741 // NativeProcessProtocol.
2742 return SendUnimplementedResponse("");
2743 }
2744
2745 return SendOKResponse();
2746}
2747
2750 StringExtractorGDBRemote &packet) {
2751 Log *log = GetLog(LLDBLog::Process);
2752
2753 // Ensure we have a process.
2754 if (!m_current_process ||
2756 LLDB_LOGF(
2757 log,
2758 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2759 __FUNCTION__);
2760 return SendErrorResponse(0x15);
2761 }
2762
2763 // Parse out the memory address.
2764 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2765 if (packet.GetBytesLeft() < 1)
2766 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2767
2768 // Read the address. Punting on validation.
2769 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2770
2771 StreamGDBRemote response;
2772
2773 // Get the memory region info for the target address.
2774 MemoryRegionInfo region_info;
2775 const Status error =
2776 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2777 if (error.Fail()) {
2778 // Return the error message.
2779
2780 response.PutCString("error:");
2781 response.PutStringAsRawHex8(error.AsCString());
2782 response.PutChar(';');
2783 } else {
2784 // Range start and size.
2785 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2786 region_info.GetRange().GetRangeBase(),
2787 region_info.GetRange().GetByteSize());
2788
2789 // Permissions.
2790 if (region_info.GetReadable() || region_info.GetWritable() ||
2791 region_info.GetExecutable()) {
2792 // Write permissions info.
2793 response.PutCString("permissions:");
2794
2795 if (region_info.GetReadable())
2796 response.PutChar('r');
2797 if (region_info.GetWritable())
2798 response.PutChar('w');
2799 if (region_info.GetExecutable())
2800 response.PutChar('x');
2801
2802 response.PutChar(';');
2803 }
2804
2805 // Flags
2806 MemoryRegionInfo::OptionalBool memory_tagged =
2807 region_info.GetMemoryTagged();
2808 if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2809 response.PutCString("flags:");
2810 if (memory_tagged == MemoryRegionInfo::eYes) {
2811 response.PutCString("mt");
2812 }
2813 response.PutChar(';');
2814 }
2815
2816 // Name
2817 ConstString name = region_info.GetName();
2818 if (name) {
2819 response.PutCString("name:");
2820 response.PutStringAsRawHex8(name.GetStringRef());
2821 response.PutChar(';');
2822 }
2823 }
2824
2825 return SendPacketNoLock(response.GetString());
2826}
2827
2830 // Ensure we have a process.
2831 if (!m_current_process ||
2833 Log *log = GetLog(LLDBLog::Process);
2834 LLDB_LOG(log, "failed, no process available");
2835 return SendErrorResponse(0x15);
2836 }
2837
2838 // Parse out software or hardware breakpoint or watchpoint requested.
2839 packet.SetFilePos(strlen("Z"));
2840 if (packet.GetBytesLeft() < 1)
2841 return SendIllFormedResponse(
2842 packet, "Too short Z packet, missing software/hardware specifier");
2843
2844 bool want_breakpoint = true;
2845 bool want_hardware = false;
2846 uint32_t watch_flags = 0;
2847
2848 const GDBStoppointType stoppoint_type =
2850 switch (stoppoint_type) {
2852 want_hardware = false;
2853 want_breakpoint = true;
2854 break;
2856 want_hardware = true;
2857 want_breakpoint = true;
2858 break;
2859 case eWatchpointWrite:
2860 watch_flags = 1;
2861 want_hardware = true;
2862 want_breakpoint = false;
2863 break;
2864 case eWatchpointRead:
2865 watch_flags = 2;
2866 want_hardware = true;
2867 want_breakpoint = false;
2868 break;
2870 watch_flags = 3;
2871 want_hardware = true;
2872 want_breakpoint = false;
2873 break;
2874 case eStoppointInvalid:
2875 return SendIllFormedResponse(
2876 packet, "Z packet had invalid software/hardware specifier");
2877 }
2878
2879 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2880 return SendIllFormedResponse(
2881 packet, "Malformed Z packet, expecting comma after stoppoint type");
2882
2883 // Parse out the stoppoint address.
2884 if (packet.GetBytesLeft() < 1)
2885 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2886 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2887
2888 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2889 return SendIllFormedResponse(
2890 packet, "Malformed Z packet, expecting comma after address");
2891
2892 // Parse out the stoppoint size (i.e. size hint for opcode size).
2893 const uint32_t size =
2894 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2895 if (size == std::numeric_limits<uint32_t>::max())
2896 return SendIllFormedResponse(
2897 packet, "Malformed Z packet, failed to parse size argument");
2898
2899 if (want_breakpoint) {
2900 // Try to set the breakpoint.
2901 const Status error =
2902 m_current_process->SetBreakpoint(addr, size, want_hardware);
2903 if (error.Success())
2904 return SendOKResponse();
2906 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2908 return SendErrorResponse(0x09);
2909 } else {
2910 // Try to set the watchpoint.
2912 addr, size, watch_flags, want_hardware);
2913 if (error.Success())
2914 return SendOKResponse();
2916 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2918 return SendErrorResponse(0x09);
2919 }
2920}
2921
2924 // Ensure we have a process.
2925 if (!m_current_process ||
2927 Log *log = GetLog(LLDBLog::Process);
2928 LLDB_LOG(log, "failed, no process available");
2929 return SendErrorResponse(0x15);
2930 }
2931
2932 // Parse out software or hardware breakpoint or watchpoint requested.
2933 packet.SetFilePos(strlen("z"));
2934 if (packet.GetBytesLeft() < 1)
2935 return SendIllFormedResponse(
2936 packet, "Too short z packet, missing software/hardware specifier");
2937
2938 bool want_breakpoint = true;
2939 bool want_hardware = false;
2940
2941 const GDBStoppointType stoppoint_type =
2943 switch (stoppoint_type) {
2945 want_breakpoint = true;
2946 want_hardware = true;
2947 break;
2949 want_breakpoint = true;
2950 break;
2951 case eWatchpointWrite:
2952 want_breakpoint = false;
2953 break;
2954 case eWatchpointRead:
2955 want_breakpoint = false;
2956 break;
2958 want_breakpoint = false;
2959 break;
2960 default:
2961 return SendIllFormedResponse(
2962 packet, "z packet had invalid software/hardware specifier");
2963 }
2964
2965 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2966 return SendIllFormedResponse(
2967 packet, "Malformed z packet, expecting comma after stoppoint type");
2968
2969 // Parse out the stoppoint address.
2970 if (packet.GetBytesLeft() < 1)
2971 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2972 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2973
2974 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2975 return SendIllFormedResponse(
2976 packet, "Malformed z packet, expecting comma after address");
2977
2978 /*
2979 // Parse out the stoppoint size (i.e. size hint for opcode size).
2980 const uint32_t size = packet.GetHexMaxU32 (false,
2981 std::numeric_limits<uint32_t>::max ());
2982 if (size == std::numeric_limits<uint32_t>::max ())
2983 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2984 size argument");
2985 */
2986
2987 if (want_breakpoint) {
2988 // Try to clear the breakpoint.
2989 const Status error =
2990 m_current_process->RemoveBreakpoint(addr, want_hardware);
2991 if (error.Success())
2992 return SendOKResponse();
2994 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2996 return SendErrorResponse(0x09);
2997 } else {
2998 // Try to clear the watchpoint.
3000 if (error.Success())
3001 return SendOKResponse();
3003 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3005 return SendErrorResponse(0x09);
3006 }
3007}
3008
3012
3013 // Ensure we have a process.
3014 if (!m_continue_process ||
3016 LLDB_LOGF(
3017 log,
3018 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3019 __FUNCTION__);
3020 return SendErrorResponse(0x32);
3021 }
3022
3023 // We first try to use a continue thread id. If any one or any all set, use
3024 // the current thread. Bail out if we don't have a thread id.
3026 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3027 tid = GetCurrentThreadID();
3028 if (tid == LLDB_INVALID_THREAD_ID)
3029 return SendErrorResponse(0x33);
3030
3031 // Double check that we have such a thread.
3032 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3034 if (!thread)
3035 return SendErrorResponse(0x33);
3036
3037 // Create the step action for the given thread.
3039
3040 // Setup the actions list.
3041 ResumeActionList actions;
3042 actions.Append(action);
3043
3044 // All other threads stop while we're single stepping a thread.
3046
3047 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3048 if (resume_res != PacketResult::Success)
3049 return resume_res;
3050
3051 // No response here, unless in non-stop mode.
3052 // Otherwise, the stop or exit will come from the resulting action.
3054}
3055
3056llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3058 // Ensure we have a thread.
3060 if (!thread)
3061 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3062 "No thread available");
3063
3065 // Get the register context for the first thread.
3066 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3067
3068 StreamString response;
3069
3070 response.Printf("<?xml version=\"1.0\"?>\n");
3071 response.Printf("<target version=\"1.0\">\n");
3072 response.IndentMore();
3073
3074 response.Indent();
3075 response.Printf("<architecture>%s</architecture>\n",
3077 .GetTriple()
3078 .getArchName()
3079 .str()
3080 .c_str());
3081
3082 response.Indent("<feature>\n");
3083
3084 const int registers_count = reg_context.GetUserRegisterCount();
3085 if (registers_count)
3086 response.IndentMore();
3087
3088 llvm::StringSet<> field_enums_seen;
3089 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3090 const RegisterInfo *reg_info =
3091 reg_context.GetRegisterInfoAtIndex(reg_index);
3092
3093 if (!reg_info) {
3094 LLDB_LOGF(log,
3095 "%s failed to get register info for register index %" PRIu32,
3096 "target.xml", reg_index);
3097 continue;
3098 }
3099
3100 if (reg_info->flags_type) {
3101 response.IndentMore();
3102 reg_info->flags_type->EnumsToXML(response, field_enums_seen);
3103 reg_info->flags_type->ToXML(response);
3104 response.IndentLess();
3105 }
3106
3107 response.Indent();
3108 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3109 "\" regnum=\"%d\" ",
3110 reg_info->name, reg_info->byte_size * 8, reg_index);
3111
3112 if (!reg_context.RegisterOffsetIsDynamic())
3113 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3114
3115 if (reg_info->alt_name && reg_info->alt_name[0])
3116 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3117
3118 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3119 if (!encoding.empty())
3120 response << "encoding=\"" << encoding << "\" ";
3121
3122 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3123 if (!format.empty())
3124 response << "format=\"" << format << "\" ";
3125
3126 if (reg_info->flags_type)
3127 response << "type=\"" << reg_info->flags_type->GetID() << "\" ";
3128
3129 const char *const register_set_name =
3130 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3131 if (register_set_name)
3132 response << "group=\"" << register_set_name << "\" ";
3133
3134 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3136 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3137 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3138
3139 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3141 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3142 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3143
3144 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3145 if (!kind_generic.empty())
3146 response << "generic=\"" << kind_generic << "\" ";
3147
3148 if (reg_info->value_regs &&
3149 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3150 response.PutCString("value_regnums=\"");
3151 CollectRegNums(reg_info->value_regs, response, false);
3152 response.Printf("\" ");
3153 }
3154
3155 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3156 response.PutCString("invalidate_regnums=\"");
3157 CollectRegNums(reg_info->invalidate_regs, response, false);
3158 response.Printf("\" ");
3159 }
3160
3161 response.Printf("/>\n");
3162 }
3163
3164 if (registers_count)
3165 response.IndentLess();
3166
3167 response.Indent("</feature>\n");
3168 response.IndentLess();
3169 response.Indent("</target>\n");
3170 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3171}
3172
3173llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3175 llvm::StringRef annex) {
3176 // Make sure we have a valid process.
3177 if (!m_current_process ||
3179 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3180 "No process available");
3181 }
3182
3183 if (object == "auxv") {
3184 // Grab the auxv data.
3185 auto buffer_or_error = m_current_process->GetAuxvData();
3186 if (!buffer_or_error)
3187 return llvm::errorCodeToError(buffer_or_error.getError());
3188 return std::move(*buffer_or_error);
3189 }
3190
3191 if (object == "siginfo") {
3193 if (!thread)
3194 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3195 "no current thread");
3196
3197 auto buffer_or_error = thread->GetSiginfo();
3198 if (!buffer_or_error)
3199 return buffer_or_error.takeError();
3200 return std::move(*buffer_or_error);
3201 }
3202
3203 if (object == "libraries-svr4") {
3204 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3205 if (!library_list)
3206 return library_list.takeError();
3207
3208 StreamString response;
3209 response.Printf("<library-list-svr4 version=\"1.0\">");
3210 for (auto const &library : *library_list) {
3211 response.Printf("<library name=\"%s\" ",
3212 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3213 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3214 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3215 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3216 }
3217 response.Printf("</library-list-svr4>");
3218 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3219 }
3220
3221 if (object == "features" && annex == "target.xml")
3222 return BuildTargetXml();
3223
3224 return llvm::make_error<UnimplementedError>();
3225}
3226
3229 StringExtractorGDBRemote &packet) {
3230 SmallVector<StringRef, 5> fields;
3231 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3232 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3233 if (fields.size() != 5)
3234 return SendIllFormedResponse(packet, "malformed qXfer packet");
3235 StringRef &xfer_object = fields[1];
3236 StringRef &xfer_action = fields[2];
3237 StringRef &xfer_annex = fields[3];
3238 StringExtractor offset_data(fields[4]);
3239 if (xfer_action != "read")
3240 return SendUnimplementedResponse("qXfer action not supported");
3241 // Parse offset.
3242 const uint64_t xfer_offset =
3243 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3244 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3245 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3246 // Parse out comma.
3247 if (offset_data.GetChar() != ',')
3248 return SendIllFormedResponse(packet,
3249 "qXfer packet missing comma after offset");
3250 // Parse out the length.
3251 const uint64_t xfer_length =
3252 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3253 if (xfer_length == std::numeric_limits<uint64_t>::max())
3254 return SendIllFormedResponse(packet, "qXfer packet missing length");
3255
3256 // Get a previously constructed buffer if it exists or create it now.
3257 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3258 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3259 if (buffer_it == m_xfer_buffer_map.end()) {
3260 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3261 if (!buffer_up)
3262 return SendErrorResponse(buffer_up.takeError());
3263 buffer_it = m_xfer_buffer_map
3264 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3265 .first;
3266 }
3267
3268 // Send back the response
3269 StreamGDBRemote response;
3270 bool done_with_buffer = false;
3271 llvm::StringRef buffer = buffer_it->second->getBuffer();
3272 if (xfer_offset >= buffer.size()) {
3273 // We have nothing left to send. Mark the buffer as complete.
3274 response.PutChar('l');
3275 done_with_buffer = true;
3276 } else {
3277 // Figure out how many bytes are available starting at the given offset.
3278 buffer = buffer.drop_front(xfer_offset);
3279 // Mark the response type according to whether we're reading the remainder
3280 // of the data.
3281 if (xfer_length >= buffer.size()) {
3282 // There will be nothing left to read after this
3283 response.PutChar('l');
3284 done_with_buffer = true;
3285 } else {
3286 // There will still be bytes to read after this request.
3287 response.PutChar('m');
3288 buffer = buffer.take_front(xfer_length);
3289 }
3290 // Now write the data in encoded binary form.
3291 response.PutEscapedBytes(buffer.data(), buffer.size());
3292 }
3293
3294 if (done_with_buffer)
3295 m_xfer_buffer_map.erase(buffer_it);
3296
3297 return SendPacketNoLock(response.GetString());
3298}
3299
3302 StringExtractorGDBRemote &packet) {
3303 Log *log = GetLog(LLDBLog::Thread);
3304
3305 // Move past packet name.
3306 packet.SetFilePos(strlen("QSaveRegisterState"));
3307
3308 // Get the thread to use.
3309 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3310 if (!thread) {
3312 return SendIllFormedResponse(
3313 packet, "No thread specified in QSaveRegisterState packet");
3314 else
3315 return SendIllFormedResponse(packet,
3316 "No thread was is set with the Hg packet");
3317 }
3318
3319 // Grab the register context for the thread.
3320 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3321
3322 // Save registers to a buffer.
3323 WritableDataBufferSP register_data_sp;
3324 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3325 if (error.Fail()) {
3326 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3328 return SendErrorResponse(0x75);
3329 }
3330
3331 // Allocate a new save id.
3332 const uint32_t save_id = GetNextSavedRegistersID();
3333 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3334 "GetNextRegisterSaveID() returned an existing register save id");
3335
3336 // Save the register data buffer under the save id.
3337 {
3338 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3339 m_saved_registers_map[save_id] = register_data_sp;
3340 }
3341
3342 // Write the response.
3343 StreamGDBRemote response;
3344 response.Printf("%" PRIu32, save_id);
3345 return SendPacketNoLock(response.GetString());
3346}
3347
3350 StringExtractorGDBRemote &packet) {
3351 Log *log = GetLog(LLDBLog::Thread);
3352
3353 // Parse out save id.
3354 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3355 if (packet.GetBytesLeft() < 1)
3356 return SendIllFormedResponse(
3357 packet, "QRestoreRegisterState packet missing register save id");
3358
3359 const uint32_t save_id = packet.GetU32(0);
3360 if (save_id == 0) {
3361 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3362 "expecting decimal uint32_t");
3363 return SendErrorResponse(0x76);
3364 }
3365
3366 // Get the thread to use.
3367 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3368 if (!thread) {
3370 return SendIllFormedResponse(
3371 packet, "No thread specified in QRestoreRegisterState packet");
3372 else
3373 return SendIllFormedResponse(packet,
3374 "No thread was is set with the Hg packet");
3375 }
3376
3377 // Grab the register context for the thread.
3378 NativeRegisterContext &reg_context = thread->GetRegisterContext();
3379
3380 // Retrieve register state buffer, then remove from the list.
3381 DataBufferSP register_data_sp;
3382 {
3383 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3384
3385 // Find the register set buffer for the given save id.
3386 auto it = m_saved_registers_map.find(save_id);
3387 if (it == m_saved_registers_map.end()) {
3388 LLDB_LOG(log,
3389 "pid {0} does not have a register set save buffer for id {1}",
3390 m_current_process->GetID(), save_id);
3391 return SendErrorResponse(0x77);
3392 }
3393 register_data_sp = it->second;
3394
3395 // Remove it from the map.
3396 m_saved_registers_map.erase(it);
3397 }
3398
3399 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3400 if (error.Fail()) {
3401 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3403 return SendErrorResponse(0x77);
3404 }
3405
3406 return SendOKResponse();
3407}
3408
3411 StringExtractorGDBRemote &packet) {
3412 Log *log = GetLog(LLDBLog::Process);
3413
3414 // Consume the ';' after vAttach.
3415 packet.SetFilePos(strlen("vAttach"));
3416 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3417 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3418
3419 // Grab the PID to which we will attach (assume hex encoding).
3420 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3421 if (pid == LLDB_INVALID_PROCESS_ID)
3422 return SendIllFormedResponse(packet,
3423 "vAttach failed to parse the process id");
3424
3425 // Attempt to attach.
3426 LLDB_LOGF(log,
3427 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3428 "pid %" PRIu64,
3429 __FUNCTION__, pid);
3430
3432
3433 if (error.Fail()) {
3434 LLDB_LOGF(log,
3435 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3436 "pid %" PRIu64 ": %s\n",
3437 __FUNCTION__, pid, error.AsCString());
3438 return SendErrorResponse(error);
3439 }
3440
3441 // Notify we attached by sending a stop packet.
3442 assert(m_current_process);
3445 /*force_synchronous=*/false);
3446}
3447
3450 StringExtractorGDBRemote &packet) {
3451 Log *log = GetLog(LLDBLog::Process);
3452
3453 // Consume the ';' after the identifier.
3454 packet.SetFilePos(strlen("vAttachWait"));
3455
3456 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3457 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3458
3459 // Allocate the buffer for the process name from vAttachWait.
3460 std::string process_name;
3461 if (!packet.GetHexByteString(process_name))
3462 return SendIllFormedResponse(packet,
3463 "vAttachWait failed to parse process name");
3464
3465 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3466
3467 Status error = AttachWaitProcess(process_name, false);
3468 if (error.Fail()) {
3469 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3470 error);
3471 return SendErrorResponse(error);
3472 }
3473
3474 // Notify we attached by sending a stop packet.
3475 assert(m_current_process);
3478 /*force_synchronous=*/false);
3479}
3480
3483 StringExtractorGDBRemote &packet) {
3484 return SendOKResponse();
3485}
3486
3489 StringExtractorGDBRemote &packet) {
3490 Log *log = GetLog(LLDBLog::Process);
3491
3492 // Consume the ';' after the identifier.
3493 packet.SetFilePos(strlen("vAttachOrWait"));
3494
3495 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3496 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3497
3498 // Allocate the buffer for the process name from vAttachWait.
3499 std::string process_name;
3500 if (!packet.GetHexByteString(process_name))
3501 return SendIllFormedResponse(packet,
3502 "vAttachOrWait failed to parse process name");
3503
3504 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3505
3506 Status error = AttachWaitProcess(process_name, true);
3507 if (error.Fail()) {
3508 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3509 error);
3510 return SendErrorResponse(error);
3511 }
3512
3513 // Notify we attached by sending a stop packet.
3514 assert(m_current_process);
3517 /*force_synchronous=*/false);
3518}
3519
3522 StringExtractorGDBRemote &packet) {
3523 Log *log = GetLog(LLDBLog::Process);
3524
3525 llvm::StringRef s = packet.GetStringRef();
3526 if (!s.consume_front("vRun;"))
3527 return SendErrorResponse(8);
3528
3529 llvm::SmallVector<llvm::StringRef, 16> argv;
3530 s.split(argv, ';');
3531
3532 for (llvm::StringRef hex_arg : argv) {
3533 StringExtractor arg_ext{hex_arg};
3534 std::string arg;
3535 arg_ext.GetHexByteString(arg);
3537 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3538 arg.c_str());
3539 }
3540
3541 if (argv.empty())
3542 return SendErrorResponse(Status("No arguments"));
3544 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3548 assert(m_current_process);
3551 /*force_synchronous=*/true);
3552}
3553
3556 Log *log = GetLog(LLDBLog::Process);
3557 if (!m_non_stop)
3559
3561
3562 // Consume the ';' after D.
3563 packet.SetFilePos(1);
3564 if (packet.GetBytesLeft()) {
3565 if (packet.GetChar() != ';')
3566 return SendIllFormedResponse(packet, "D missing expected ';'");
3567
3568 // Grab the PID from which we will detach (assume hex encoding).
3569 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3570 if (pid == LLDB_INVALID_PROCESS_ID)
3571 return SendIllFormedResponse(packet, "D failed to parse the process id");
3572 }
3573
3574 // Detach forked children if their PID was specified *or* no PID was requested
3575 // (i.e. detach-all packet).
3576 llvm::Error detach_error = llvm::Error::success();
3577 bool detached = false;
3578 for (auto it = m_debugged_processes.begin();
3579 it != m_debugged_processes.end();) {
3580 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3581 LLDB_LOGF(log,
3582 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3583 __FUNCTION__, it->first);
3584 if (llvm::Error e = it->second.process_up->Detach().ToError())
3585 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3586 else {
3587 if (it->second.process_up.get() == m_current_process)
3588 m_current_process = nullptr;
3589 if (it->second.process_up.get() == m_continue_process)
3590 m_continue_process = nullptr;
3591 it = m_debugged_processes.erase(it);
3592 detached = true;
3593 continue;
3594 }
3595 }
3596 ++it;
3597 }
3598
3599 if (detach_error)
3600 return SendErrorResponse(std::move(detach_error));
3601 if (!detached)
3602 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3603 return SendOKResponse();
3604}
3605
3608 StringExtractorGDBRemote &packet) {
3609 Log *log = GetLog(LLDBLog::Thread);
3610
3611 if (!m_current_process ||
3613 return SendErrorResponse(50);
3614
3615 packet.SetFilePos(strlen("qThreadStopInfo"));
3616 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3617 if (tid == LLDB_INVALID_THREAD_ID) {
3618 LLDB_LOGF(log,
3619 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3620 "parse thread id from request \"%s\"",
3621 __FUNCTION__, packet.GetStringRef().data());
3622 return SendErrorResponse(0x15);
3623 }
3625 /*force_synchronous=*/true);
3626}
3627
3632
3633 // Ensure we have a debugged process.
3634 if (!m_current_process ||
3636 return SendErrorResponse(50);
3637 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3638
3639 StreamString response;
3640 const bool threads_with_valid_stop_info_only = false;
3641 llvm::Expected<json::Value> threads_info =
3642 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3643 if (!threads_info) {
3644 LLDB_LOG_ERROR(log, threads_info.takeError(),
3645 "failed to prepare a packet for pid {1}: {0}",
3647 return SendErrorResponse(52);
3648 }
3649
3650 response.AsRawOstream() << *threads_info;
3651 StreamGDBRemote escaped_response;
3652 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3653 return SendPacketNoLock(escaped_response.GetString());
3654}
3655
3658 StringExtractorGDBRemote &packet) {
3659 // Fail if we don't have a current process.
3660 if (!m_current_process ||
3662 return SendErrorResponse(68);
3663
3664 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3665 if (packet.GetBytesLeft() == 0)
3666 return SendOKResponse();
3667 if (packet.GetChar() != ':')
3668 return SendErrorResponse(67);
3669
3670 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3671
3672 StreamGDBRemote response;
3673 if (hw_debug_cap == std::nullopt)
3674 response.Printf("num:0;");
3675 else
3676 response.Printf("num:%d;", hw_debug_cap->second);
3677
3678 return SendPacketNoLock(response.GetString());
3679}
3680
3683 StringExtractorGDBRemote &packet) {
3684 // Fail if we don't have a current process.
3685 if (!m_current_process ||
3687 return SendErrorResponse(67);
3688
3689 packet.SetFilePos(strlen("qFileLoadAddress:"));
3690 if (packet.GetBytesLeft() == 0)
3691 return SendErrorResponse(68);
3692
3693 std::string file_name;
3694 packet.GetHexByteString(file_name);
3695
3696 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3697 Status error =
3698 m_current_process->GetFileLoadAddress(file_name, file_load_address);
3699 if (error.Fail())
3700 return SendErrorResponse(69);
3701
3702 if (file_load_address == LLDB_INVALID_ADDRESS)
3703 return SendErrorResponse(1); // File not loaded
3704
3705 StreamGDBRemote response;
3706 response.PutHex64(file_load_address);
3707 return SendPacketNoLock(response.GetString());
3708}
3709
3712 StringExtractorGDBRemote &packet) {
3713 std::vector<int> signals;
3714 packet.SetFilePos(strlen("QPassSignals:"));
3715
3716 // Read sequence of hex signal numbers divided by a semicolon and optionally
3717 // spaces.
3718 while (packet.GetBytesLeft() > 0) {
3719 int signal = packet.GetS32(-1, 16);
3720 if (signal < 0)
3721 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3722 signals.push_back(signal);
3723
3724 packet.SkipSpaces();
3725 char separator = packet.GetChar();
3726 if (separator == '\0')
3727 break; // End of string
3728 if (separator != ';')
3729 return SendIllFormedResponse(packet, "Invalid separator,"
3730 " expected semicolon.");
3731 }
3732
3733 // Fail if we don't have a current process.
3734 if (!m_current_process)
3735 return SendErrorResponse(68);
3736
3738 if (error.Fail())
3739 return SendErrorResponse(69);
3740
3741 return SendOKResponse();
3742}
3743
3746 StringExtractorGDBRemote &packet) {
3747 Log *log = GetLog(LLDBLog::Process);
3748
3749 // Ensure we have a process.
3750 if (!m_current_process ||
3752 LLDB_LOGF(
3753 log,
3754 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3755 __FUNCTION__);
3756 return SendErrorResponse(1);
3757 }
3758
3759 // We are expecting
3760 // qMemTags:<hex address>,<hex length>:<hex type>
3761
3762 // Address
3763 packet.SetFilePos(strlen("qMemTags:"));
3764 const char *current_char = packet.Peek();
3765 if (!current_char || *current_char == ',')
3766 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3767 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3768
3769 // Length
3770 char previous_char = packet.GetChar();
3771 current_char = packet.Peek();
3772 // If we don't have a separator or the length field is empty
3773 if (previous_char != ',' || (current_char && *current_char == ':'))
3774 return SendIllFormedResponse(packet,
3775 "Invalid addr,length pair in qMemTags packet");
3776
3777 if (packet.GetBytesLeft() < 1)
3778 return SendIllFormedResponse(
3779 packet, "Too short qMemtags: packet (looking for length)");
3780 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3781
3782 // Type
3783 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3784 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3785 return SendIllFormedResponse(packet, invalid_type_err);
3786
3787 // Type is a signed integer but packed into the packet as its raw bytes.
3788 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3789 const char *first_type_char = packet.Peek();
3790 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3791 return SendIllFormedResponse(packet, invalid_type_err);
3792
3793 // Extract type as unsigned then cast to signed.
3794 // Using a uint64_t here so that we have some value outside of the 32 bit
3795 // range to use as the invalid return value.
3796 uint64_t raw_type =
3797 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3798
3799 if ( // Make sure the cast below would be valid
3800 raw_type > std::numeric_limits<uint32_t>::max() ||
3801 // To catch inputs like "123aardvark" that will parse but clearly aren't
3802 // valid in this case.
3803 packet.GetBytesLeft()) {
3804 return SendIllFormedResponse(packet, invalid_type_err);
3805 }
3806
3807 // First narrow to 32 bits otherwise the copy into type would take
3808 // the wrong 4 bytes on big endian.
3809 uint32_t raw_type_32 = raw_type;
3810 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3811
3812 StreamGDBRemote response;
3813 std::vector<uint8_t> tags;
3814 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3815 if (error.Fail())
3816 return SendErrorResponse(1);
3817
3818 // This m is here in case we want to support multi part replies in the future.
3819 // In the same manner as qfThreadInfo/qsThreadInfo.
3820 response.PutChar('m');
3821 response.PutBytesAsRawHex8(tags.data(), tags.size());
3822 return SendPacketNoLock(response.GetString());
3823}
3824
3827 StringExtractorGDBRemote &packet) {
3828 Log *log = GetLog(LLDBLog::Process);
3829
3830 // Ensure we have a process.
3831 if (!m_current_process ||
3833 LLDB_LOGF(
3834 log,
3835 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3836 __FUNCTION__);
3837 return SendErrorResponse(1);
3838 }
3839
3840 // We are expecting
3841 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3842
3843 // Address
3844 packet.SetFilePos(strlen("QMemTags:"));
3845 const char *current_char = packet.Peek();
3846 if (!current_char || *current_char == ',')
3847 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3848 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3849
3850 // Length
3851 char previous_char = packet.GetChar();
3852 current_char = packet.Peek();
3853 // If we don't have a separator or the length field is empty
3854 if (previous_char != ',' || (current_char && *current_char == ':'))
3855 return SendIllFormedResponse(packet,
3856 "Invalid addr,length pair in QMemTags packet");
3857
3858 if (packet.GetBytesLeft() < 1)
3859 return SendIllFormedResponse(
3860 packet, "Too short QMemtags: packet (looking for length)");
3861 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3862
3863 // Type
3864 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3865 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3866 return SendIllFormedResponse(packet, invalid_type_err);
3867
3868 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3869 const char *first_type_char = packet.Peek();
3870 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3871 return SendIllFormedResponse(packet, invalid_type_err);
3872
3873 // The type is a signed integer but is in the packet as its raw bytes.
3874 // So parse first as unsigned then cast to signed later.
3875 // We extract to 64 bit, even though we only expect 32, so that we've
3876 // got some invalid value we can check for.
3877 uint64_t raw_type =
3878 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3879 if (raw_type > std::numeric_limits<uint32_t>::max())
3880 return SendIllFormedResponse(packet, invalid_type_err);
3881
3882 // First narrow to 32 bits. Otherwise the copy below would get the wrong
3883 // 4 bytes on big endian.
3884 uint32_t raw_type_32 = raw_type;
3885 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3886
3887 // Tag data
3888 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3889 return SendIllFormedResponse(packet,
3890 "Missing tag data in QMemTags: packet");
3891
3892 // Must be 2 chars per byte
3893 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3894 if (packet.GetBytesLeft() % 2)
3895 return SendIllFormedResponse(packet, invalid_data_err);
3896
3897 // This is bytes here and is unpacked into target specific tags later
3898 // We cannot assume that number of bytes == length here because the server
3899 // can repeat tags to fill a given range.
3900 std::vector<uint8_t> tag_data;
3901 // Zero length writes will not have any tag data
3902 // (but we pass them on because it will still check that tagging is enabled)
3903 if (packet.GetBytesLeft()) {
3904 size_t byte_count = packet.GetBytesLeft() / 2;
3905 tag_data.resize(byte_count);
3906 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3907 if (converted_bytes != byte_count) {
3908 return SendIllFormedResponse(packet, invalid_data_err);
3909 }
3910 }
3911
3912 Status status =
3913 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3914 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3915}
3916
3919 StringExtractorGDBRemote &packet) {
3920 // Fail if we don't have a current process.
3921 if (!m_current_process ||
3923 return SendErrorResponse(Status("Process not running."));
3924
3925 std::string path_hint;
3926
3927 StringRef packet_str{packet.GetStringRef()};
3928 assert(packet_str.starts_with("qSaveCore"));
3929 if (packet_str.consume_front("qSaveCore;")) {
3930 for (auto x : llvm::split(packet_str, ';')) {
3931 if (x.consume_front("path-hint:"))
3932 StringExtractor(x).GetHexByteString(path_hint);
3933 else
3934 return SendErrorResponse(Status("Unsupported qSaveCore option"));
3935 }
3936 }
3937
3938 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
3939 if (!ret)
3940 return SendErrorResponse(ret.takeError());
3941
3942 StreamString response;
3943 response.PutCString("core-path:");
3944 response.PutStringAsRawHex8(ret.get());
3945 return SendPacketNoLock(response.GetString());
3946}
3947
3950 StringExtractorGDBRemote &packet) {
3951 Log *log = GetLog(LLDBLog::Process);
3952
3953 StringRef packet_str{packet.GetStringRef()};
3954 assert(packet_str.starts_with("QNonStop:"));
3955 packet_str.consume_front("QNonStop:");
3956 if (packet_str == "0") {
3957 if (m_non_stop)
3959 for (auto &process_it : m_debugged_processes) {
3960 if (process_it.second.process_up->IsRunning()) {
3961 assert(m_non_stop);
3962 Status error = process_it.second.process_up->Interrupt();
3963 if (error.Fail()) {
3964 LLDB_LOG(log,
3965 "while disabling nonstop, failed to halt process {0}: {1}",
3966 process_it.first, error);
3967 return SendErrorResponse(0x41);
3968 }
3969 // we must not send stop reasons after QNonStop
3970 m_disabling_non_stop = true;
3971 }
3972 }
3975 m_non_stop = false;
3976 // If we are stopping anything, defer sending the OK response until we're
3977 // done.
3979 return PacketResult::Success;
3980 } else if (packet_str == "1") {
3981 if (!m_non_stop)
3983 m_non_stop = true;
3984 } else
3985 return SendErrorResponse(Status("Invalid QNonStop packet"));
3986 return SendOKResponse();
3987}
3988
3991 std::deque<std::string> &queue) {
3992 // Per the protocol, the first message put into the queue is sent
3993 // immediately. However, it remains the queue until the client ACKs it --
3994 // then we pop it and send the next message. The process repeats until
3995 // the last message in the queue is ACK-ed, in which case the packet sends
3996 // an OK response.
3997 if (queue.empty())
3998 return SendErrorResponse(Status("No pending notification to ack"));
3999 queue.pop_front();
4000 if (!queue.empty())
4001 return SendPacketNoLock(queue.front());
4002 return SendOKResponse();
4003}
4004
4007 StringExtractorGDBRemote &packet) {
4009}
4010
4013 StringExtractorGDBRemote &packet) {
4015 // If this was the last notification and all the processes exited,
4016 // terminate the server.
4017 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4018 m_exit_now = true;
4020 }
4021 return ret;
4022}
4023
4026 StringExtractorGDBRemote &packet) {
4027 if (!m_non_stop)
4028 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
4029
4030 PacketResult interrupt_res = Handle_interrupt(packet);
4031 // If interrupting the process failed, pass the result through.
4032 if (interrupt_res != PacketResult::Success)
4033 return interrupt_res;
4034 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4035 return SendOKResponse();
4036}
4037
4040 packet.SetFilePos(strlen("T"));
4041 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4043 if (!pid_tid)
4044 return SendErrorResponse(llvm::make_error<StringError>(
4045 inconvertibleErrorCode(), "Malformed thread-id"));
4046
4047 lldb::pid_t pid = pid_tid->first;
4048 lldb::tid_t tid = pid_tid->second;
4049
4050 // Technically, this would also be caught by the PID check but let's be more
4051 // explicit about the error.
4052 if (pid == LLDB_INVALID_PROCESS_ID)
4053 return SendErrorResponse(llvm::make_error<StringError>(
4054 inconvertibleErrorCode(), "No current process and no PID provided"));
4055
4056 // Check the process ID and find respective process instance.
4057 auto new_process_it = m_debugged_processes.find(pid);
4058 if (new_process_it == m_debugged_processes.end())
4059 return SendErrorResponse(1);
4060
4061 // Check the thread ID
4062 if (!new_process_it->second.process_up->GetThreadByID(tid))
4063 return SendErrorResponse(2);
4064
4065 return SendOKResponse();
4066}
4067
4069 Log *log = GetLog(LLDBLog::Process);
4070
4071 // Tell the stdio connection to shut down.
4073 auto connection = m_stdio_communication.GetConnection();
4074 if (connection) {
4075 Status error;
4076 connection->Disconnect(&error);
4077
4078 if (error.Success()) {
4079 LLDB_LOGF(log,
4080 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4081 "terminal stdio - SUCCESS",
4082 __FUNCTION__);
4083 } else {
4084 LLDB_LOGF(log,
4085 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4086 "terminal stdio - FAIL: %s",
4087 __FUNCTION__, error.AsCString());
4088 }
4089 }
4090 }
4091}
4092
4094 StringExtractorGDBRemote &packet) {
4095 // We have no thread if we don't have a process.
4096 if (!m_current_process ||
4098 return nullptr;
4099
4100 // If the client hasn't asked for thread suffix support, there will not be a
4101 // thread suffix. Use the current thread in that case.
4103 const lldb::tid_t current_tid = GetCurrentThreadID();
4104 if (current_tid == LLDB_INVALID_THREAD_ID)
4105 return nullptr;
4106 else if (current_tid == 0) {
4107 // Pick a thread.
4109 } else
4110 return m_current_process->GetThreadByID(current_tid);
4111 }
4112
4113 Log *log = GetLog(LLDBLog::Thread);
4114
4115 // Parse out the ';'.
4116 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4117 LLDB_LOGF(log,
4118 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4119 "error: expected ';' prior to start of thread suffix: packet "
4120 "contents = '%s'",
4121 __FUNCTION__, packet.GetStringRef().data());
4122 return nullptr;
4123 }
4124
4125 if (!packet.GetBytesLeft())
4126 return nullptr;
4127
4128 // Parse out thread: portion.
4129 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4130 LLDB_LOGF(log,
4131 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4132 "error: expected 'thread:' but not found, packet contents = "
4133 "'%s'",
4134 __FUNCTION__, packet.GetStringRef().data());
4135 return nullptr;
4136 }
4137 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4138 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4139 if (tid != 0)
4140 return m_current_process->GetThreadByID(tid);
4141
4142 return nullptr;
4143}
4144
4147 // Use whatever the debug process says is the current thread id since the
4148 // protocol either didn't specify or specified we want any/all threads
4149 // marked as the current thread.
4150 if (!m_current_process)
4153 }
4154 // Use the specific current thread id set by the gdb remote protocol.
4155 return m_current_tid;
4156}
4157
4159 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4161}
4162
4164 Log *log = GetLog(LLDBLog::Process);
4165
4166 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4167 m_xfer_buffer_map.clear();
4168}
4169
4172 const ArchSpec &arch) {
4173 if (m_current_process) {
4174 FileSpec file_spec;
4176 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4177 .Success()) {
4178 if (FileSystem::Instance().Exists(file_spec))
4179 return file_spec;
4180 }
4181 }
4182
4184}
4185
4187 llvm::StringRef value) {
4188 std::string result;
4189 for (const char &c : value) {
4190 switch (c) {
4191 case '\'':
4192 result += "&apos;";
4193 break;
4194 case '"':
4195 result += "&quot;";
4196 break;
4197 case '<':
4198 result += "&lt;";
4199 break;
4200 case '>':
4201 result += "&gt;";
4202 break;
4203 default:
4204 result += c;
4205 break;
4206 }
4207 }
4208 return result;
4209}
4210
4212 const llvm::ArrayRef<llvm::StringRef> client_features) {
4213 std::vector<std::string> ret =
4215 ret.insert(ret.end(), {
4216 "QThreadSuffixSupported+",
4217 "QListThreadsInStopReply+",
4218 "qXfer:features:read+",
4219 "QNonStop+",
4220 });
4221
4222 // report server-only features
4223 using Extension = NativeProcessProtocol::Extension;
4224 Extension plugin_features = m_process_manager.GetSupportedExtensions();
4225 if (bool(plugin_features & Extension::pass_signals))
4226 ret.push_back("QPassSignals+");
4227 if (bool(plugin_features & Extension::auxv))
4228 ret.push_back("qXfer:auxv:read+");
4229 if (bool(plugin_features & Extension::libraries_svr4))
4230 ret.push_back("qXfer:libraries-svr4:read+");
4231 if (bool(plugin_features & Extension::siginfo_read))
4232 ret.push_back("qXfer:siginfo:read+");
4233 if (bool(plugin_features & Extension::memory_tagging))
4234 ret.push_back("memory-tagging+");
4235 if (bool(plugin_features & Extension::savecore))
4236 ret.push_back("qSaveCore+");
4237
4238 // check for client features
4240 for (llvm::StringRef x : client_features)
4242 llvm::StringSwitch<Extension>(x)
4243 .Case("multiprocess+", Extension::multiprocess)
4244 .Case("fork-events+", Extension::fork)
4245 .Case("vfork-events+", Extension::vfork)
4246 .Default({});
4247
4248 // We consume lldb's swbreak/hwbreak feature, but it doesn't change the
4249 // behaviour of lldb-server. We always adjust the program counter for targets
4250 // like x86
4251
4252 m_extensions_supported &= plugin_features;
4253
4254 // fork & vfork require multiprocess
4255 if (!bool(m_extensions_supported & Extension::multiprocess))
4256 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4257
4258 // report only if actually supported
4259 if (bool(m_extensions_supported & Extension::multiprocess))
4260 ret.push_back("multiprocess+");
4261 if (bool(m_extensions_supported & Extension::fork))
4262 ret.push_back("fork-events+");
4263 if (bool(m_extensions_supported & Extension::vfork))
4264 ret.push_back("vfork-events+");
4265
4266 for (auto &x : m_debugged_processes)
4267 SetEnabledExtensions(*x.second.process_up);
4268 return ret;
4269}
4270
4272 NativeProcessProtocol &process) {
4274 assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));
4275 process.SetEnabledExtensions(flags);
4276}
4277
4280 if (m_non_stop)
4281 return SendOKResponse();
4283 return PacketResult::Success;
4284}
4285
4287 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4288 if (bool(m_extensions_supported &
4290 response.Format("p{0:x-}.", pid);
4291 response.Format("{0:x-}", tid);
4292}
4293
4294std::string
4296 bool reverse_connect) {
4297 // Try parsing the argument as URL.
4298 if (std::optional<URI> url = URI::Parse(url_arg)) {
4299 if (reverse_connect)
4300 return url_arg.str();
4301
4302 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4303 // If the scheme doesn't match any, pass it through to support using CFD
4304 // schemes directly.
4305 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4306 .Case("tcp", "listen")
4307 .Case("unix", "unix-accept")
4308 .Case("unix-abstract", "unix-abstract-accept")
4309 .Default(url->scheme.str());
4310 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4311 return new_url;
4312 }
4313
4314 std::string host_port = url_arg.str();
4315 // If host_and_port starts with ':', default the host to be "localhost" and
4316 // expect the remainder to be the port.
4317 if (url_arg.starts_with(":"))
4318 host_port.insert(0, "localhost");
4319
4320 // Try parsing the (preprocessed) argument as host:port pair.
4321 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4322 return (reverse_connect ? "connect://" : "listen://") + host_port;
4323
4324 // If none of the above applied, interpret the argument as UNIX socket path.
4325 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4326 url_arg.str();
4327}
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:359
#define LLDB_LOGF(log,...)
Definition: Log.h:366
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:382
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)