1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 #include "lldb/Host/Config.h"
13 #include "GDBRemoteCommunicationServerLLGS.h"
14 #include "lldb/Utility/GDBRemote.h"
20 #include "lldb/Host/ConnectionFileDescriptor.h"
21 #include "lldb/Host/Debug.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileAction.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/PosixApi.h"
28 #include "lldb/Host/common/NativeProcessProtocol.h"
29 #include "lldb/Host/common/NativeRegisterContext.h"
30 #include "lldb/Host/common/NativeThreadProtocol.h"
31 #include "lldb/Target/MemoryRegionInfo.h"
32 #include "lldb/Utility/Args.h"
33 #include "lldb/Utility/DataBuffer.h"
34 #include "lldb/Utility/Endian.h"
35 #include "lldb/Utility/LLDBAssert.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/RegisterValue.h"
38 #include "lldb/Utility/State.h"
39 #include "lldb/Utility/StreamString.h"
40 #include "lldb/Utility/UriParser.h"
41 #include "llvm/ADT/Triple.h"
42 #include "llvm/Support/JSON.h"
43 #include "llvm/Support/ScopedPrinter.h"
45 #include "ProcessGDBRemote.h"
46 #include "ProcessGDBRemoteLog.h"
47 #include "lldb/Utility/StringExtractorGDBRemote.h"
50 using namespace lldb_private;
51 using namespace lldb_private::process_gdb_remote;
57 enum GDBRemoteServerError {
58 // Set to the first unused error number in literal form below
60 eErrorNoProcess = eErrorFirst,
66 // GDBRemoteCommunicationServerLLGS constructor
67 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
68 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
69 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
70 "gdb-remote.server.rx_packet"),
71 m_mainloop(mainloop), m_process_factory(process_factory),
72 m_stdio_communication("process.stdio") {
73 RegisterPacketHandlers();
76 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
77 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
78 &GDBRemoteCommunicationServerLLGS::Handle_C);
79 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
80 &GDBRemoteCommunicationServerLLGS::Handle_c);
81 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
82 &GDBRemoteCommunicationServerLLGS::Handle_D);
83 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
84 &GDBRemoteCommunicationServerLLGS::Handle_H);
85 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
86 &GDBRemoteCommunicationServerLLGS::Handle_I);
87 RegisterMemberFunctionHandler(
88 StringExtractorGDBRemote::eServerPacketType_interrupt,
89 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
90 RegisterMemberFunctionHandler(
91 StringExtractorGDBRemote::eServerPacketType_m,
92 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
94 &GDBRemoteCommunicationServerLLGS::Handle_M);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
96 &GDBRemoteCommunicationServerLLGS::Handle_p);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
98 &GDBRemoteCommunicationServerLLGS::Handle_P);
99 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
100 &GDBRemoteCommunicationServerLLGS::Handle_qC);
101 RegisterMemberFunctionHandler(
102 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
103 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
104 RegisterMemberFunctionHandler(
105 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
106 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
107 RegisterMemberFunctionHandler(
108 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
109 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
110 RegisterMemberFunctionHandler(
111 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
112 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
115 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
118 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
121 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
124 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
127 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
130 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
133 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
136 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
139 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
142 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
145 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qXfer,
148 &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
149 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
150 &GDBRemoteCommunicationServerLLGS::Handle_s);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_stop_reason,
153 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_vAttach,
156 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
157 RegisterMemberFunctionHandler(
158 StringExtractorGDBRemote::eServerPacketType_vCont,
159 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
162 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_x,
165 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
167 &GDBRemoteCommunicationServerLLGS::Handle_Z);
168 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
169 &GDBRemoteCommunicationServerLLGS::Handle_z);
170 RegisterMemberFunctionHandler(
171 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
172 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
174 RegisterMemberFunctionHandler(
175 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
176 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
177 RegisterMemberFunctionHandler(
178 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
179 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
180 RegisterMemberFunctionHandler(
181 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
182 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
183 RegisterMemberFunctionHandler(
184 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
185 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
190 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
191 &GDBRemoteCommunicationServerLLGS::Handle_g);
193 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
194 [this](StringExtractorGDBRemote packet, Status &error,
195 bool &interrupt, bool &quit) {
197 return this->Handle_k(packet);
201 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
202 m_process_launch_info = info;
205 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
206 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
208 if (!m_process_launch_info.GetArguments().GetArgumentCount())
209 return Status("%s: no process command line specified to launch",
212 const bool should_forward_stdio =
213 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
214 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
215 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
216 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
217 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
219 if (should_forward_stdio) {
220 // Temporarily relax the following for Windows until we can take advantage
221 // of the recently added pty support. This doesn't really affect the use of
222 // lldb-server on Windows.
224 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
225 return Status(std::move(Err));
230 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
231 assert(!m_debugged_process_up && "lldb-server creating debugged "
232 "process but one already exists");
234 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
236 return Status(process_or.takeError());
237 m_debugged_process_up = std::move(*process_or);
240 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
241 // needed. llgs local-process debugging may specify PTY paths, which will
242 // make these file actions non-null process launch -i/e/o will also make
243 // these file actions non-null nullptr means that the traffic is expected to
244 // flow over gdb-remote protocol
245 if (should_forward_stdio) {
246 // nullptr means it's not redirected to file or pty (in case of LLGS local)
247 // at least one of stdio will be transferred pty<->gdb-remote we need to
248 // give the pty master handle to this object to read and/or write
250 "pid = {0}: setting up stdout/stderr redirection via $O "
251 "gdb-remote commands",
252 m_debugged_process_up->GetID());
254 // Setup stdout/stderr mapping from inferior to $O
255 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
256 if (terminal_fd >= 0) {
258 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
259 "inferior STDIO fd to %d",
260 __FUNCTION__, terminal_fd);
261 Status status = SetSTDIOFileDescriptor(terminal_fd);
266 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
267 "inferior STDIO since terminal fd reported as %d",
268 __FUNCTION__, terminal_fd);
272 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
273 "will communicate over client-provided file descriptors",
274 m_debugged_process_up->GetID());
277 printf("Launched '%s' as process %" PRIu64 "...\n",
278 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
279 m_debugged_process_up->GetID());
284 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
285 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
286 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
289 // Before we try to attach, make sure we aren't already monitoring something
291 if (m_debugged_process_up &&
292 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
293 return Status("cannot attach to process %" PRIu64
294 " when another process with pid %" PRIu64
295 " is being debugged.",
296 pid, m_debugged_process_up->GetID());
299 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
301 Status status(process_or.takeError());
302 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
306 m_debugged_process_up = std::move(*process_or);
308 // Setup stdout/stderr mapping from inferior.
309 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
310 if (terminal_fd >= 0) {
312 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
313 "inferior STDIO fd to %d",
314 __FUNCTION__, terminal_fd);
315 Status status = SetSTDIOFileDescriptor(terminal_fd);
320 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
321 "inferior STDIO since terminal fd reported as %d",
322 __FUNCTION__, terminal_fd);
325 printf("Attached to process %" PRIu64 "...\n", pid);
329 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
330 NativeProcessProtocol *process) {
331 assert(process && "process cannot be NULL");
332 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
335 "GDBRemoteCommunicationServerLLGS::%s called with "
336 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
337 __FUNCTION__, process->GetID(),
338 StateAsCString(process->GetState()));
342 GDBRemoteCommunication::PacketResult
343 GDBRemoteCommunicationServerLLGS::SendWResponse(
344 NativeProcessProtocol *process) {
345 assert(process && "process cannot be NULL");
346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
348 // send W notification
349 auto wait_status = process->GetExitStatus();
351 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
354 StreamGDBRemote response;
355 response.PutChar('E');
356 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
357 return SendPacketNoLock(response.GetString());
360 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
363 StreamGDBRemote response;
364 response.Format("{0:g}", *wait_status);
365 return SendPacketNoLock(response.GetString());
368 static void AppendHexValue(StreamString &response, const uint8_t *buf,
369 uint32_t buf_size, bool swap) {
372 for (i = buf_size - 1; i >= 0; i--)
373 response.PutHex8(buf[i]);
375 for (i = 0; i < buf_size; i++)
376 response.PutHex8(buf[i]);
380 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {
381 switch (reg_info.encoding) {
386 case eEncodingIEEE754:
388 case eEncodingVector:
395 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {
396 switch (reg_info.format) {
405 case eFormatVectorOfSInt8:
406 return "vector-sint8";
407 case eFormatVectorOfUInt8:
408 return "vector-uint8";
409 case eFormatVectorOfSInt16:
410 return "vector-sint16";
411 case eFormatVectorOfUInt16:
412 return "vector-uint16";
413 case eFormatVectorOfSInt32:
414 return "vector-sint32";
415 case eFormatVectorOfUInt32:
416 return "vector-uint32";
417 case eFormatVectorOfFloat32:
418 return "vector-float32";
419 case eFormatVectorOfUInt64:
420 return "vector-uint64";
421 case eFormatVectorOfUInt128:
422 return "vector-uint128";
428 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {
429 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
430 case LLDB_REGNUM_GENERIC_PC:
432 case LLDB_REGNUM_GENERIC_SP:
434 case LLDB_REGNUM_GENERIC_FP:
436 case LLDB_REGNUM_GENERIC_RA:
438 case LLDB_REGNUM_GENERIC_FLAGS:
440 case LLDB_REGNUM_GENERIC_ARG1:
442 case LLDB_REGNUM_GENERIC_ARG2:
444 case LLDB_REGNUM_GENERIC_ARG3:
446 case LLDB_REGNUM_GENERIC_ARG4:
448 case LLDB_REGNUM_GENERIC_ARG5:
450 case LLDB_REGNUM_GENERIC_ARG6:
452 case LLDB_REGNUM_GENERIC_ARG7:
454 case LLDB_REGNUM_GENERIC_ARG8:
461 static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
463 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
465 response.PutChar(',');
467 response.Printf("%" PRIx32, *reg_num);
469 response.Printf("%" PRIu32, *reg_num);
473 static void WriteRegisterValueInHexFixedWidth(
474 StreamString &response, NativeRegisterContext ®_ctx,
475 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
476 lldb::ByteOrder byte_order) {
477 RegisterValue reg_value;
479 Status error = reg_ctx.ReadRegister(®_info, reg_value);
481 reg_value_p = ®_value;
486 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
487 reg_value_p->GetByteSize(),
488 byte_order == lldb::eByteOrderLittle);
490 // Zero-out any unreadable values.
491 if (reg_info.byte_size > 0) {
492 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
493 AppendHexValue(response, zeros.data(), zeros.size(), false);
498 static llvm::Expected<json::Object>
499 GetRegistersAsJSON(NativeThreadProtocol &thread) {
500 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
502 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
504 json::Object register_object;
506 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
507 // Expedite all registers in the first register set (i.e. should be GPRs)
508 // that are not contained in other registers.
509 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
511 return llvm::make_error<llvm::StringError>("failed to get registers",
512 llvm::inconvertibleErrorCode());
513 for (const uint32_t *reg_num_p = reg_set_p->registers;
514 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
515 uint32_t reg_num = *reg_num_p;
517 // Expedite only a couple of registers until we figure out why sending
518 // registers is expensive.
519 static const uint32_t k_expedited_registers[] = {
520 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
521 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
523 for (const uint32_t *generic_reg_p = k_expedited_registers;
524 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
525 uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
526 eRegisterKindGeneric, *generic_reg_p);
527 if (reg_num == LLDB_INVALID_REGNUM)
528 continue; // Target does not support the given register.
531 const RegisterInfo *const reg_info_p =
532 reg_ctx.GetRegisterInfoAtIndex(reg_num);
533 if (reg_info_p == nullptr) {
535 "%s failed to get register info for register index %" PRIu32,
536 __FUNCTION__, reg_num);
540 if (reg_info_p->value_regs != nullptr)
541 continue; // Only expedite registers that are not contained in other
544 RegisterValue reg_value;
545 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
547 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
549 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
550 reg_num, error.AsCString());
555 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
556 ®_value, lldb::eByteOrderBig);
558 register_object.try_emplace(llvm::to_string(reg_num),
559 stream.GetString().str());
562 return register_object;
565 static const char *GetStopReasonString(StopReason stop_reason) {
566 switch (stop_reason) {
567 case eStopReasonTrace:
569 case eStopReasonBreakpoint:
571 case eStopReasonWatchpoint:
573 case eStopReasonSignal:
575 case eStopReasonException:
577 case eStopReasonExec:
579 case eStopReasonInstrumentation:
580 case eStopReasonInvalid:
581 case eStopReasonPlanComplete:
582 case eStopReasonThreadExiting:
583 case eStopReasonNone:
589 static llvm::Expected<json::Array>
590 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
591 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
593 json::Array threads_array;
595 // Ensure we can get info on the given thread.
596 uint32_t thread_idx = 0;
597 for (NativeThreadProtocol *thread;
598 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
601 lldb::tid_t tid = thread->GetID();
603 // Grab the reason this thread stopped.
604 struct ThreadStopInfo tid_stop_info;
605 std::string description;
606 if (!thread->GetStopReason(tid_stop_info, description))
607 return llvm::make_error<llvm::StringError>(
608 "failed to get stop reason", llvm::inconvertibleErrorCode());
610 const int signum = tid_stop_info.details.signal.signo;
613 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
615 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
616 __FUNCTION__, process.GetID(), tid, signum,
617 tid_stop_info.reason, tid_stop_info.details.exception.type);
620 json::Object thread_obj;
623 if (llvm::Expected<json::Object> registers =
624 GetRegistersAsJSON(*thread)) {
625 thread_obj.try_emplace("registers", std::move(*registers));
627 return registers.takeError();
631 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
634 thread_obj.try_emplace("signal", signum);
636 const std::string thread_name = thread->GetName();
637 if (!thread_name.empty())
638 thread_obj.try_emplace("name", thread_name);
640 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
642 thread_obj.try_emplace("reason", stop_reason);
644 if (!description.empty())
645 thread_obj.try_emplace("description", description);
647 if ((tid_stop_info.reason == eStopReasonException) &&
648 tid_stop_info.details.exception.type) {
649 thread_obj.try_emplace(
650 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
652 json::Array medata_array;
653 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
655 medata_array.push_back(
656 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
658 thread_obj.try_emplace("medata", std::move(medata_array));
660 threads_array.push_back(std::move(thread_obj));
662 return threads_array;
665 GDBRemoteCommunication::PacketResult
666 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
668 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
670 // Ensure we have a debugged process.
671 if (!m_debugged_process_up ||
672 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
673 return SendErrorResponse(50);
675 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
676 m_debugged_process_up->GetID(), tid);
678 // Ensure we can get info on the given thread.
679 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
681 return SendErrorResponse(51);
683 // Grab the reason this thread stopped.
684 struct ThreadStopInfo tid_stop_info;
685 std::string description;
686 if (!thread->GetStopReason(tid_stop_info, description))
687 return SendErrorResponse(52);
689 // FIXME implement register handling for exec'd inferiors.
690 // if (tid_stop_info.reason == eStopReasonExec) {
691 // const bool force = true;
692 // InitializeRegisters(force);
695 StreamString response;
696 // Output the T packet with the thread
697 response.PutChar('T');
698 int signum = tid_stop_info.details.signal.signo;
701 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
702 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
703 tid_stop_info.details.exception.type);
705 // Print the signal number.
706 response.PutHex8(signum & 0xff);
709 response.Printf("thread:%" PRIx64 ";", tid);
711 // Include the thread name if there is one.
712 const std::string thread_name = thread->GetName();
713 if (!thread_name.empty()) {
714 size_t thread_name_len = thread_name.length();
716 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
717 response.PutCString("name:");
718 response.PutCString(thread_name);
720 // The thread name contains special chars, send as hex bytes.
721 response.PutCString("hexname:");
722 response.PutStringAsRawHex8(thread_name);
724 response.PutChar(';');
727 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
728 // send all thread IDs back in the "threads" key whose value is a list of hex
729 // thread IDs separated by commas:
730 // "threads:10a,10b,10c;"
731 // This will save the debugger from having to send a pair of qfThreadInfo and
732 // qsThreadInfo packets, but it also might take a lot of room in the stop
733 // reply packet, so it must be enabled only on systems where there are no
734 // limits on packet lengths.
735 if (m_list_threads_in_stop_reply) {
736 response.PutCString("threads:");
738 uint32_t thread_index = 0;
739 NativeThreadProtocol *listed_thread;
740 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
741 listed_thread; ++thread_index,
742 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
743 if (thread_index > 0)
744 response.PutChar(',');
745 response.Printf("%" PRIx64, listed_thread->GetID());
747 response.PutChar(';');
749 // Include JSON info that describes the stop reason for any threads that
750 // actually have stop reasons. We use the new "jstopinfo" key whose values
751 // is hex ascii JSON that contains the thread IDs thread stop info only for
752 // threads that have stop reasons. Only send this if we have more than one
753 // thread otherwise this packet has all the info it needs.
754 if (thread_index > 1) {
755 const bool threads_with_valid_stop_info_only = true;
756 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
757 *m_debugged_process_up, threads_with_valid_stop_info_only);
759 response.PutCString("jstopinfo:");
760 StreamString unescaped_response;
761 unescaped_response.AsRawOstream() << std::move(*threads_info);
762 response.PutStringAsRawHex8(unescaped_response.GetData());
763 response.PutChar(';');
765 LLDB_LOG_ERROR(log, threads_info.takeError(),
766 "failed to prepare a jstopinfo field for pid {1}: {0}",
767 m_debugged_process_up->GetID());
772 response.PutCString("thread-pcs");
773 char delimiter = ':';
774 for (NativeThreadProtocol *thread;
775 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
777 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
779 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
780 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
781 const RegisterInfo *const reg_info_p =
782 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
784 RegisterValue reg_value;
785 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
787 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
789 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
790 reg_to_read, error.AsCString());
794 response.PutChar(delimiter);
796 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
797 ®_value, endian::InlHostByteOrder());
800 response.PutChar(';');
804 // Expedite registers.
807 // Grab the register context.
808 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
809 // Expedite all registers in the first register set (i.e. should be GPRs)
810 // that are not contained in other registers.
811 const RegisterSet *reg_set_p;
812 if (reg_ctx.GetRegisterSetCount() > 0 &&
813 ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
815 "GDBRemoteCommunicationServerLLGS::%s expediting registers "
816 "from set '%s' (registers set count: %zu)",
817 __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
818 reg_set_p->num_registers);
820 for (const uint32_t *reg_num_p = reg_set_p->registers;
821 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
822 const RegisterInfo *const reg_info_p =
823 reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
824 if (reg_info_p == nullptr) {
826 "GDBRemoteCommunicationServerLLGS::%s failed to get "
827 "register info for register set '%s', register index "
830 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
832 } else if (reg_info_p->value_regs == nullptr) {
833 // Only expediate registers that are not contained in other registers.
834 RegisterValue reg_value;
835 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
836 if (error.Success()) {
837 response.Printf("%.02x:", *reg_num_p);
838 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
839 ®_value, lldb::eByteOrderBig);
840 response.PutChar(';');
843 "GDBRemoteCommunicationServerLLGS::%s failed to read "
844 "register '%s' index %" PRIu32 ": %s",
846 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
847 *reg_num_p, error.AsCString());
853 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
854 if (reason_str != nullptr) {
855 response.Printf("reason:%s;", reason_str);
858 if (!description.empty()) {
859 // Description may contains special chars, send as hex bytes.
860 response.PutCString("description:");
861 response.PutStringAsRawHex8(description);
862 response.PutChar(';');
863 } else if ((tid_stop_info.reason == eStopReasonException) &&
864 tid_stop_info.details.exception.type) {
865 response.PutCString("metype:");
866 response.PutHex64(tid_stop_info.details.exception.type);
867 response.PutCString(";mecount:");
868 response.PutHex32(tid_stop_info.details.exception.data_count);
869 response.PutChar(';');
871 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
872 response.PutCString("medata:");
873 response.PutHex64(tid_stop_info.details.exception.data[i]);
874 response.PutChar(';');
878 return SendPacketNoLock(response.GetString());
881 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
882 NativeProcessProtocol *process) {
883 assert(process && "process cannot be NULL");
885 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
886 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
888 PacketResult result = SendStopReasonForState(StateType::eStateExited);
889 if (result != PacketResult::Success) {
891 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
892 "notification for PID %" PRIu64 ", state: eStateExited",
893 __FUNCTION__, process->GetID());
896 // Close the pipe to the inferior terminal i/o if we launched it and set one
898 MaybeCloseInferiorTerminalConnection();
900 // We are ready to exit the debug monitor.
902 m_mainloop.RequestTermination();
905 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
906 NativeProcessProtocol *process) {
907 assert(process && "process cannot be NULL");
909 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
910 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
912 // Send the stop reason unless this is the stop after the launch or attach.
913 switch (m_inferior_prev_state) {
914 case eStateLaunching:
915 case eStateAttaching:
916 // Don't send anything per debugserver behavior.
919 // In all other cases, send the stop reason.
920 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
921 if (result != PacketResult::Success) {
923 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
924 "notification for PID %" PRIu64 ", state: eStateExited",
925 __FUNCTION__, process->GetID());
931 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
932 NativeProcessProtocol *process, lldb::StateType state) {
933 assert(process && "process cannot be NULL");
934 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
937 "GDBRemoteCommunicationServerLLGS::%s called with "
938 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
939 __FUNCTION__, process->GetID(), StateAsCString(state));
943 case StateType::eStateRunning:
944 StartSTDIOForwarding();
947 case StateType::eStateStopped:
948 // Make sure we get all of the pending stdout/stderr from the inferior and
949 // send it to the lldb host before we send the state change notification
951 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
952 // does not interfere with our protocol.
953 StopSTDIOForwarding();
954 HandleInferiorState_Stopped(process);
957 case StateType::eStateExited:
960 StopSTDIOForwarding();
961 HandleInferiorState_Exited(process);
967 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
968 "change for pid %" PRIu64 ", new state: %s",
969 __FUNCTION__, process->GetID(), StateAsCString(state));
974 // Remember the previous state reported to us.
975 m_inferior_prev_state = state;
978 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
979 ClearProcessSpecificData();
982 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
983 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
985 if (!m_handshake_completed) {
986 if (!HandshakeWithClient()) {
988 "GDBRemoteCommunicationServerLLGS::%s handshake with "
989 "client failed, exiting",
991 m_mainloop.RequestTermination();
994 m_handshake_completed = true;
997 bool interrupt = false;
1001 const PacketResult result = GetPacketAndSendResponse(
1002 std::chrono::microseconds(0), error, interrupt, done);
1003 if (result == PacketResult::ErrorReplyTimeout)
1004 break; // No more packets in the queue
1006 if ((result != PacketResult::Success)) {
1008 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1010 __FUNCTION__, error.AsCString());
1011 m_mainloop.RequestTermination();
1017 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1018 std::unique_ptr<Connection> connection) {
1019 IOObjectSP read_object_sp = connection->GetReadObject();
1020 GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1023 m_network_handle_up = m_mainloop.RegisterReadObject(
1024 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1029 GDBRemoteCommunication::PacketResult
1030 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1032 if ((buffer == nullptr) || (len == 0)) {
1034 return PacketResult::Success;
1037 StreamString response;
1038 response.PutChar('O');
1039 response.PutBytesAsRawHex8(buffer, len);
1041 return SendPacketNoLock(response.GetString());
1044 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1047 // Set up the reading/handling of process I/O
1048 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1049 new ConnectionFileDescriptor(fd, true));
1051 error.SetErrorString("failed to create ConnectionFileDescriptor");
1055 m_stdio_communication.SetCloseOnEOF(false);
1056 m_stdio_communication.SetConnection(std::move(conn_up));
1057 if (!m_stdio_communication.IsConnected()) {
1058 error.SetErrorString(
1059 "failed to set connection for inferior I/O communication");
1066 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1067 // Don't forward if not connected (e.g. when attaching).
1068 if (!m_stdio_communication.IsConnected())
1072 lldbassert(!m_stdio_handle_up);
1073 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1074 m_stdio_communication.GetConnection()->GetReadObject(),
1075 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1077 if (!m_stdio_handle_up) {
1078 // Not much we can do about the failure. Log it and continue without
1080 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1082 "GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1084 __FUNCTION__, error.AsCString());
1088 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1089 m_stdio_handle_up.reset();
1092 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1094 ConnectionStatus status;
1097 size_t bytes_read = m_stdio_communication.Read(
1098 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1100 case eConnectionStatusSuccess:
1101 SendONotification(buffer, bytes_read);
1103 case eConnectionStatusLostConnection:
1104 case eConnectionStatusEndOfFile:
1105 case eConnectionStatusError:
1106 case eConnectionStatusNoConnection:
1107 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1109 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1110 "forwarding as communication returned status %d (error: "
1112 __FUNCTION__, status, error.AsCString());
1113 m_stdio_handle_up.reset();
1116 case eConnectionStatusInterrupted:
1117 case eConnectionStatusTimedOut:
1123 GDBRemoteCommunication::PacketResult
1124 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1125 StringExtractorGDBRemote &packet) {
1126 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1127 // Fail if we don't have a current process.
1128 if (!m_debugged_process_up ||
1129 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1130 return SendErrorResponse(68);
1132 if (!packet.ConsumeFront("jTraceStart:"))
1133 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1135 TraceOptions options;
1136 uint64_t type = std::numeric_limits<uint64_t>::max();
1137 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1138 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1139 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1141 auto json_object = StructuredData::ParseJSON(packet.Peek());
1144 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1145 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1147 auto json_dict = json_object->GetAsDictionary();
1149 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1150 options.setMetaDataBufferSize(metabuffersize);
1152 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1153 options.setTraceBufferSize(buffersize);
1155 json_dict->GetValueForKeyAsInteger("type", type);
1156 options.setType(static_cast<lldb::TraceType>(type));
1158 json_dict->GetValueForKeyAsInteger("threadid", tid);
1159 options.setThreadID(tid);
1161 StructuredData::ObjectSP custom_params_sp =
1162 json_dict->GetValueForKey("params");
1163 if (custom_params_sp &&
1164 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1165 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1167 options.setTraceParams(
1168 std::static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1170 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1171 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1172 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1174 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1178 lldb::user_id_t uid = LLDB_INVALID_UID;
1179 uid = m_debugged_process_up->StartTrace(options, error);
1180 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1182 return SendErrorResponse(error);
1184 StreamGDBRemote response;
1185 response.Printf("%" PRIx64, uid);
1186 return SendPacketNoLock(response.GetString());
1189 GDBRemoteCommunication::PacketResult
1190 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1191 StringExtractorGDBRemote &packet) {
1192 // Fail if we don't have a current process.
1193 if (!m_debugged_process_up ||
1194 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1195 return SendErrorResponse(68);
1197 if (!packet.ConsumeFront("jTraceStop:"))
1198 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1200 lldb::user_id_t uid = LLDB_INVALID_UID;
1201 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1203 auto json_object = StructuredData::ParseJSON(packet.Peek());
1206 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1207 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1209 auto json_dict = json_object->GetAsDictionary();
1211 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1212 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1214 json_dict->GetValueForKeyAsInteger("threadid", tid);
1216 Status error = m_debugged_process_up->StopTrace(uid, tid);
1219 return SendErrorResponse(error);
1221 return SendOKResponse();
1224 GDBRemoteCommunication::PacketResult
1225 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1226 StringExtractorGDBRemote &packet) {
1228 // Fail if we don't have a current process.
1229 if (!m_debugged_process_up ||
1230 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1231 return SendErrorResponse(68);
1233 if (!packet.ConsumeFront("jTraceConfigRead:"))
1234 return SendIllFormedResponse(packet,
1235 "jTraceConfigRead: Ill formed packet ");
1237 lldb::user_id_t uid = LLDB_INVALID_UID;
1238 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1240 auto json_object = StructuredData::ParseJSON(packet.Peek());
1243 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1244 return SendIllFormedResponse(packet,
1245 "jTraceConfigRead: Ill formed packet ");
1247 auto json_dict = json_object->GetAsDictionary();
1249 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1250 return SendIllFormedResponse(packet,
1251 "jTraceConfigRead: Ill formed packet ");
1253 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1255 TraceOptions options;
1256 StreamGDBRemote response;
1258 options.setThreadID(threadid);
1259 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1262 return SendErrorResponse(error);
1264 StreamGDBRemote escaped_response;
1265 StructuredData::Dictionary json_packet;
1267 json_packet.AddIntegerItem("type", options.getType());
1268 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1269 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1271 StructuredData::DictionarySP custom_params = options.getTraceParams();
1273 json_packet.AddItem("params", custom_params);
1275 StreamString json_string;
1276 json_packet.Dump(json_string, false);
1277 escaped_response.PutEscapedBytes(json_string.GetData(),
1278 json_string.GetSize());
1279 return SendPacketNoLock(escaped_response.GetString());
1282 GDBRemoteCommunication::PacketResult
1283 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1284 StringExtractorGDBRemote &packet) {
1286 // Fail if we don't have a current process.
1287 if (!m_debugged_process_up ||
1288 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1289 return SendErrorResponse(68);
1291 enum PacketType { MetaData, BufferData };
1292 PacketType tracetype = MetaData;
1294 if (packet.ConsumeFront("jTraceBufferRead:"))
1295 tracetype = BufferData;
1296 else if (packet.ConsumeFront("jTraceMetaRead:"))
1297 tracetype = MetaData;
1299 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1302 lldb::user_id_t uid = LLDB_INVALID_UID;
1304 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1305 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1306 uint64_t offset = std::numeric_limits<uint64_t>::max();
1308 auto json_object = StructuredData::ParseJSON(packet.Peek());
1311 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1312 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1314 auto json_dict = json_object->GetAsDictionary();
1316 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1317 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1318 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1319 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1321 json_dict->GetValueForKeyAsInteger("threadid", tid);
1323 // Allocate the response buffer.
1324 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1326 return SendErrorResponse(0x78);
1328 StreamGDBRemote response;
1330 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1332 if (tracetype == BufferData)
1333 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1334 else if (tracetype == MetaData)
1335 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1338 return SendErrorResponse(error);
1341 response.PutHex8(i);
1343 StreamGDBRemote escaped_response;
1344 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1345 return SendPacketNoLock(escaped_response.GetString());
1348 GDBRemoteCommunication::PacketResult
1349 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1350 StringExtractorGDBRemote &packet) {
1351 // Fail if we don't have a current process.
1352 if (!m_debugged_process_up ||
1353 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1354 return SendErrorResponse(68);
1356 lldb::pid_t pid = m_debugged_process_up->GetID();
1358 if (pid == LLDB_INVALID_PROCESS_ID)
1359 return SendErrorResponse(1);
1361 ProcessInstanceInfo proc_info;
1362 if (!Host::GetProcessInfo(pid, proc_info))
1363 return SendErrorResponse(1);
1365 StreamString response;
1366 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1367 return SendPacketNoLock(response.GetString());
1370 GDBRemoteCommunication::PacketResult
1371 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1372 // Fail if we don't have a current process.
1373 if (!m_debugged_process_up ||
1374 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1375 return SendErrorResponse(68);
1377 // Make sure we set the current thread so g and p packets return the data the
1379 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1380 SetCurrentThreadID(tid);
1382 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1384 return SendErrorResponse(69);
1386 StreamString response;
1387 response.Printf("QC%" PRIx64, thread->GetID());
1389 return SendPacketNoLock(response.GetString());
1392 GDBRemoteCommunication::PacketResult
1393 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1394 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1396 StopSTDIOForwarding();
1398 if (!m_debugged_process_up) {
1399 LLDB_LOG(log, "No debugged process found.");
1400 return PacketResult::Success;
1403 Status error = m_debugged_process_up->Kill();
1405 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1406 m_debugged_process_up->GetID(), error);
1408 // No OK response for kill packet.
1409 // return SendOKResponse ();
1410 return PacketResult::Success;
1413 GDBRemoteCommunication::PacketResult
1414 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1415 StringExtractorGDBRemote &packet) {
1416 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1417 if (packet.GetU32(0))
1418 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1420 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1421 return SendOKResponse();
1424 GDBRemoteCommunication::PacketResult
1425 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1426 StringExtractorGDBRemote &packet) {
1427 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1429 packet.GetHexByteString(path);
1430 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1431 return SendOKResponse();
1434 GDBRemoteCommunication::PacketResult
1435 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1436 StringExtractorGDBRemote &packet) {
1437 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1439 StreamString response;
1440 response.PutStringAsRawHex8(working_dir.GetCString());
1441 return SendPacketNoLock(response.GetString());
1444 return SendErrorResponse(14);
1447 GDBRemoteCommunication::PacketResult
1448 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1449 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1450 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1452 // Ensure we have a native process.
1453 if (!m_debugged_process_up) {
1455 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1458 return SendErrorResponse(0x36);
1461 // Pull out the signal number.
1462 packet.SetFilePos(::strlen("C"));
1463 if (packet.GetBytesLeft() < 1) {
1464 // Shouldn't be using a C without a signal.
1465 return SendIllFormedResponse(packet, "C packet specified without signal.");
1467 const uint32_t signo =
1468 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1469 if (signo == std::numeric_limits<uint32_t>::max())
1470 return SendIllFormedResponse(packet, "failed to parse signal number");
1472 // Handle optional continue address.
1473 if (packet.GetBytesLeft() > 0) {
1474 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1475 if (*packet.Peek() == ';')
1476 return SendUnimplementedResponse(packet.GetStringRef().data());
1478 return SendIllFormedResponse(
1479 packet, "unexpected content after $C{signal-number}");
1482 ResumeActionList resume_actions(StateType::eStateRunning,
1483 LLDB_INVALID_SIGNAL_NUMBER);
1486 // We have two branches: what to do if a continue thread is specified (in
1487 // which case we target sending the signal to that thread), or when we don't
1488 // have a continue thread set (in which case we send a signal to the
1491 // TODO discuss with Greg Clayton, make sure this makes sense.
1493 lldb::tid_t signal_tid = GetContinueThreadID();
1494 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1495 // The resume action for the continue thread (or all threads if a continue
1496 // thread is not set).
1497 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1498 static_cast<int>(signo)};
1500 // Add the action for the continue thread (or all threads when the continue
1501 // thread isn't present).
1502 resume_actions.Append(action);
1504 // Send the signal to the process since we weren't targeting a specific
1505 // continue thread with the signal.
1506 error = m_debugged_process_up->Signal(signo);
1508 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1509 m_debugged_process_up->GetID(), error);
1511 return SendErrorResponse(0x52);
1515 // Resume the threads.
1516 error = m_debugged_process_up->Resume(resume_actions);
1518 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1519 m_debugged_process_up->GetID(), error);
1521 return SendErrorResponse(0x38);
1524 // Don't send an "OK" packet; response is the stopped/exited message.
1525 return PacketResult::Success;
1528 GDBRemoteCommunication::PacketResult
1529 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1530 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1531 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1533 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1535 // For now just support all continue.
1536 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1537 if (has_continue_address) {
1538 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1540 return SendUnimplementedResponse(packet.GetStringRef().data());
1543 // Ensure we have a native process.
1544 if (!m_debugged_process_up) {
1546 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1549 return SendErrorResponse(0x36);
1552 // Build the ResumeActionList
1553 ResumeActionList actions(StateType::eStateRunning,
1554 LLDB_INVALID_SIGNAL_NUMBER);
1556 Status error = m_debugged_process_up->Resume(actions);
1558 LLDB_LOG(log, "c failed for process {0}: {1}",
1559 m_debugged_process_up->GetID(), error);
1560 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1563 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1564 // No response required from continue.
1565 return PacketResult::Success;
1568 GDBRemoteCommunication::PacketResult
1569 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1570 StringExtractorGDBRemote &packet) {
1571 StreamString response;
1572 response.Printf("vCont;c;C;s;S");
1574 return SendPacketNoLock(response.GetString());
1577 GDBRemoteCommunication::PacketResult
1578 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1579 StringExtractorGDBRemote &packet) {
1580 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1581 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1584 packet.SetFilePos(::strlen("vCont"));
1586 if (packet.GetBytesLeft() == 0) {
1588 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1591 return SendIllFormedResponse(packet, "Missing action from vCont package");
1594 // Check if this is all continue (no options or ";c").
1595 if (::strcmp(packet.Peek(), ";c") == 0) {
1596 // Move past the ';', then do a simple 'c'.
1597 packet.SetFilePos(packet.GetFilePos() + 1);
1598 return Handle_c(packet);
1599 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1600 // Move past the ';', then do a simple 's'.
1601 packet.SetFilePos(packet.GetFilePos() + 1);
1602 return Handle_s(packet);
1605 // Ensure we have a native process.
1606 if (!m_debugged_process_up) {
1607 LLDB_LOG(log, "no debugged process");
1608 return SendErrorResponse(0x36);
1611 ResumeActionList thread_actions;
1613 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1614 // Skip the semi-colon.
1617 // Build up the thread action.
1618 ResumeAction thread_action;
1619 thread_action.tid = LLDB_INVALID_THREAD_ID;
1620 thread_action.state = eStateInvalid;
1621 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1623 const char action = packet.GetChar();
1626 thread_action.signal = packet.GetHexMaxU32(false, 0);
1627 if (thread_action.signal == 0)
1628 return SendIllFormedResponse(
1629 packet, "Could not parse signal in vCont packet C action");
1634 thread_action.state = eStateRunning;
1638 thread_action.signal = packet.GetHexMaxU32(false, 0);
1639 if (thread_action.signal == 0)
1640 return SendIllFormedResponse(
1641 packet, "Could not parse signal in vCont packet S action");
1646 thread_action.state = eStateStepping;
1650 return SendIllFormedResponse(packet, "Unsupported vCont action");
1654 // Parse out optional :{thread-id} value.
1655 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1656 // Consume the separator.
1659 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1660 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1661 return SendIllFormedResponse(
1662 packet, "Could not parse thread number in vCont packet");
1665 thread_actions.Append(thread_action);
1668 Status error = m_debugged_process_up->Resume(thread_actions);
1670 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1671 m_debugged_process_up->GetID(), error);
1672 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1675 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1676 // No response required from vCont.
1677 return PacketResult::Success;
1680 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1681 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1682 LLDB_LOG(log, "setting current thread id to {0}", tid);
1684 m_current_tid = tid;
1685 if (m_debugged_process_up)
1686 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1689 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1690 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1691 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1693 m_continue_tid = tid;
1696 GDBRemoteCommunication::PacketResult
1697 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1698 StringExtractorGDBRemote &packet) {
1699 // Handle the $? gdbremote command.
1701 // If no process, indicate error
1702 if (!m_debugged_process_up)
1703 return SendErrorResponse(02);
1705 return SendStopReasonForState(m_debugged_process_up->GetState());
1708 GDBRemoteCommunication::PacketResult
1709 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1710 lldb::StateType process_state) {
1711 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1713 switch (process_state) {
1714 case eStateAttaching:
1715 case eStateLaunching:
1717 case eStateStepping:
1718 case eStateDetached:
1719 // NOTE: gdb protocol doc looks like it should return $OK
1720 // when everything is running (i.e. no stopped result).
1721 return PacketResult::Success; // Ignore
1723 case eStateSuspended:
1725 case eStateCrashed: {
1726 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1727 // Make sure we set the current thread so g and p packets return the data
1728 // the gdb will expect.
1729 SetCurrentThreadID(tid);
1730 return SendStopReplyPacketForThread(tid);
1734 case eStateUnloaded:
1736 return SendWResponse(m_debugged_process_up.get());
1739 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1740 m_debugged_process_up->GetID(), process_state);
1744 return SendErrorResponse(0);
1747 GDBRemoteCommunication::PacketResult
1748 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1749 StringExtractorGDBRemote &packet) {
1750 // Fail if we don't have a current process.
1751 if (!m_debugged_process_up ||
1752 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1753 return SendErrorResponse(68);
1755 // Ensure we have a thread.
1756 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1758 return SendErrorResponse(69);
1760 // Get the register context for the first thread.
1761 NativeRegisterContext ®_context = thread->GetRegisterContext();
1763 // Parse out the register number from the request.
1764 packet.SetFilePos(strlen("qRegisterInfo"));
1765 const uint32_t reg_index =
1766 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1767 if (reg_index == std::numeric_limits<uint32_t>::max())
1768 return SendErrorResponse(69);
1770 // Return the end of registers response if we've iterated one past the end of
1771 // the register set.
1772 if (reg_index >= reg_context.GetUserRegisterCount())
1773 return SendErrorResponse(69);
1775 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1777 return SendErrorResponse(69);
1779 // Build the reginfos response.
1780 StreamGDBRemote response;
1782 response.PutCString("name:");
1783 response.PutCString(reg_info->name);
1784 response.PutChar(';');
1786 if (reg_info->alt_name && reg_info->alt_name[0]) {
1787 response.PutCString("alt-name:");
1788 response.PutCString(reg_info->alt_name);
1789 response.PutChar(';');
1792 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1793 reg_info->byte_size * 8, reg_info->byte_offset);
1795 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
1796 if (!encoding.empty())
1797 response << "encoding:" << encoding << ';';
1799 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
1800 if (!format.empty())
1801 response << "format:" << format << ';';
1803 const char *const register_set_name =
1804 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1805 if (register_set_name)
1806 response << "set:" << register_set_name << ';';
1808 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1809 LLDB_INVALID_REGNUM)
1810 response.Printf("ehframe:%" PRIu32 ";",
1811 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1813 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1814 response.Printf("dwarf:%" PRIu32 ";",
1815 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1817 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
1818 if (!kind_generic.empty())
1819 response << "generic:" << kind_generic << ';';
1821 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1822 response.PutCString("container-regs:");
1823 CollectRegNums(reg_info->value_regs, response, true);
1824 response.PutChar(';');
1827 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1828 response.PutCString("invalidate-regs:");
1829 CollectRegNums(reg_info->invalidate_regs, response, true);
1830 response.PutChar(';');
1833 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1834 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1835 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1836 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1837 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1838 response.PutChar(';');
1840 return SendPacketNoLock(response.GetString());
1843 GDBRemoteCommunication::PacketResult
1844 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1845 StringExtractorGDBRemote &packet) {
1846 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1848 // Fail if we don't have a current process.
1849 if (!m_debugged_process_up ||
1850 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1851 LLDB_LOG(log, "no process ({0}), returning OK",
1852 m_debugged_process_up ? "invalid process id"
1853 : "null m_debugged_process_up");
1854 return SendOKResponse();
1857 StreamGDBRemote response;
1858 response.PutChar('m');
1860 LLDB_LOG(log, "starting thread iteration");
1861 NativeThreadProtocol *thread;
1862 uint32_t thread_index;
1863 for (thread_index = 0,
1864 thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1865 thread; ++thread_index,
1866 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1867 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1869 if (thread_index > 0)
1870 response.PutChar(',');
1871 response.Printf("%" PRIx64, thread->GetID());
1874 LLDB_LOG(log, "finished thread iteration");
1875 return SendPacketNoLock(response.GetString());
1878 GDBRemoteCommunication::PacketResult
1879 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1880 StringExtractorGDBRemote &packet) {
1881 // FIXME for now we return the full thread list in the initial packet and
1882 // always do nothing here.
1883 return SendPacketNoLock("l");
1886 GDBRemoteCommunication::PacketResult
1887 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
1888 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1890 // Move past packet name.
1891 packet.SetFilePos(strlen("g"));
1893 // Get the thread to use.
1894 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1896 LLDB_LOG(log, "failed, no thread available");
1897 return SendErrorResponse(0x15);
1900 // Get the thread's register context.
1901 NativeRegisterContext ®_ctx = thread->GetRegisterContext();
1903 std::vector<uint8_t> regs_buffer;
1904 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
1906 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
1908 if (reg_info == nullptr) {
1909 LLDB_LOG(log, "failed to get register info for register index {0}",
1911 return SendErrorResponse(0x15);
1914 if (reg_info->value_regs != nullptr)
1915 continue; // skip registers that are contained in other registers
1917 RegisterValue reg_value;
1918 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
1920 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
1921 return SendErrorResponse(0x15);
1924 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
1925 // Resize the buffer to guarantee it can store the register offsetted
1927 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
1929 // Copy the register offsetted data to the buffer.
1930 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
1931 reg_info->byte_size);
1934 // Write the response.
1935 StreamGDBRemote response;
1936 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
1938 return SendPacketNoLock(response.GetString());
1941 GDBRemoteCommunication::PacketResult
1942 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1943 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1945 // Parse out the register number from the request.
1946 packet.SetFilePos(strlen("p"));
1947 const uint32_t reg_index =
1948 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1949 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1951 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
1952 "parse register number from request \"%s\"",
1953 __FUNCTION__, packet.GetStringRef().data());
1954 return SendErrorResponse(0x15);
1957 // Get the thread to use.
1958 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1960 LLDB_LOG(log, "failed, no thread available");
1961 return SendErrorResponse(0x15);
1964 // Get the thread's register context.
1965 NativeRegisterContext ®_context = thread->GetRegisterContext();
1967 // Return the end of registers response if we've iterated one past the end of
1968 // the register set.
1969 if (reg_index >= reg_context.GetUserRegisterCount()) {
1971 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1972 "register %" PRIu32 " beyond register count %" PRIu32,
1973 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
1974 return SendErrorResponse(0x15);
1977 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1980 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1981 "register %" PRIu32 " returned NULL",
1982 __FUNCTION__, reg_index);
1983 return SendErrorResponse(0x15);
1986 // Build the reginfos response.
1987 StreamGDBRemote response;
1989 // Retrieve the value
1990 RegisterValue reg_value;
1991 Status error = reg_context.ReadRegister(reg_info, reg_value);
1994 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
1995 "requested register %" PRIu32 " (%s) failed: %s",
1996 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1997 return SendErrorResponse(0x15);
2000 const uint8_t *const data =
2001 static_cast<const uint8_t *>(reg_value.GetBytes());
2004 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2005 "bytes from requested register %" PRIu32,
2006 __FUNCTION__, reg_index);
2007 return SendErrorResponse(0x15);
2010 // FIXME flip as needed to get data in big/little endian format for this host.
2011 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2012 response.PutHex8(data[i]);
2014 return SendPacketNoLock(response.GetString());
2017 GDBRemoteCommunication::PacketResult
2018 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2019 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2021 // Ensure there is more content.
2022 if (packet.GetBytesLeft() < 1)
2023 return SendIllFormedResponse(packet, "Empty P packet");
2025 // Parse out the register number from the request.
2026 packet.SetFilePos(strlen("P"));
2027 const uint32_t reg_index =
2028 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2029 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2031 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2032 "parse register number from request \"%s\"",
2033 __FUNCTION__, packet.GetStringRef().data());
2034 return SendErrorResponse(0x29);
2037 // Note debugserver would send an E30 here.
2038 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2039 return SendIllFormedResponse(
2040 packet, "P packet missing '=' char after register number");
2042 // Parse out the value.
2043 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2044 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2046 // Get the thread to use.
2047 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2050 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2051 "available (thread index 0)",
2053 return SendErrorResponse(0x28);
2056 // Get the thread's register context.
2057 NativeRegisterContext ®_context = thread->GetRegisterContext();
2058 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2061 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2062 "register %" PRIu32 " returned NULL",
2063 __FUNCTION__, reg_index);
2064 return SendErrorResponse(0x48);
2067 // Return the end of registers response if we've iterated one past the end of
2068 // the register set.
2069 if (reg_index >= reg_context.GetUserRegisterCount()) {
2071 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2072 "register %" PRIu32 " beyond register count %" PRIu32,
2073 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2074 return SendErrorResponse(0x47);
2077 // The dwarf expression are evaluate on host site which may cause register
2078 // size to change Hence the reg_size may not be same as reg_info->bytes_size
2079 if ((reg_size != reg_info->byte_size) &&
2080 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2081 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2084 // Build the reginfos response.
2085 StreamGDBRemote response;
2087 RegisterValue reg_value(
2088 reg_bytes, reg_size,
2089 m_debugged_process_up->GetArchitecture().GetByteOrder());
2090 Status error = reg_context.WriteRegister(reg_info, reg_value);
2093 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2094 "requested register %" PRIu32 " (%s) failed: %s",
2095 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2096 return SendErrorResponse(0x32);
2099 return SendOKResponse();
2102 GDBRemoteCommunication::PacketResult
2103 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2104 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2106 // Fail if we don't have a current process.
2107 if (!m_debugged_process_up ||
2108 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2111 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2113 return SendErrorResponse(0x15);
2116 // Parse out which variant of $H is requested.
2117 packet.SetFilePos(strlen("H"));
2118 if (packet.GetBytesLeft() < 1) {
2120 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2121 "missing {g,c} variant",
2123 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2126 const char h_variant = packet.GetChar();
2127 switch (h_variant) {
2137 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2138 __FUNCTION__, h_variant);
2139 return SendIllFormedResponse(packet,
2140 "H variant unsupported, should be c or g");
2143 // Parse out the thread number.
2144 // FIXME return a parse success/fail value. All values are valid here.
2145 const lldb::tid_t tid =
2146 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2148 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2150 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2151 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2154 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2157 return SendErrorResponse(0x15);
2161 // Now switch the given thread type.
2162 switch (h_variant) {
2164 SetCurrentThreadID(tid);
2168 SetContinueThreadID(tid);
2172 assert(false && "unsupported $H variant - shouldn't get here");
2173 return SendIllFormedResponse(packet,
2174 "H variant unsupported, should be c or g");
2177 return SendOKResponse();
2180 GDBRemoteCommunication::PacketResult
2181 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2182 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2184 // Fail if we don't have a current process.
2185 if (!m_debugged_process_up ||
2186 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2189 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2191 return SendErrorResponse(0x15);
2194 packet.SetFilePos(::strlen("I"));
2197 size_t read = packet.GetHexBytesAvail(tmp);
2201 // write directly to stdin *this might block if stdin buffer is full*
2202 // TODO: enqueue this block in circular buffer and send window size to
2204 ConnectionStatus status;
2206 m_stdio_communication.Write(tmp, read, status, &error);
2208 return SendErrorResponse(0x15);
2212 return SendOKResponse();
2215 GDBRemoteCommunication::PacketResult
2216 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2217 StringExtractorGDBRemote &packet) {
2218 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2220 // Fail if we don't have a current process.
2221 if (!m_debugged_process_up ||
2222 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2223 LLDB_LOG(log, "failed, no process available");
2224 return SendErrorResponse(0x15);
2227 // Interrupt the process.
2228 Status error = m_debugged_process_up->Interrupt();
2230 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2232 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2235 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2237 // No response required from stop all.
2238 return PacketResult::Success;
2241 GDBRemoteCommunication::PacketResult
2242 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2243 StringExtractorGDBRemote &packet) {
2244 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2246 if (!m_debugged_process_up ||
2247 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2250 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2252 return SendErrorResponse(0x15);
2255 // Parse out the memory address.
2256 packet.SetFilePos(strlen("m"));
2257 if (packet.GetBytesLeft() < 1)
2258 return SendIllFormedResponse(packet, "Too short m packet");
2260 // Read the address. Punting on validation.
2261 // FIXME replace with Hex U64 read with no default value that fails on failed
2263 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2266 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2267 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2269 // Get # bytes to read.
2270 if (packet.GetBytesLeft() < 1)
2271 return SendIllFormedResponse(packet, "Length missing in m packet");
2273 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2274 if (byte_count == 0) {
2276 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2277 "zero-length packet",
2279 return SendOKResponse();
2282 // Allocate the response buffer.
2283 std::string buf(byte_count, '\0');
2285 return SendErrorResponse(0x78);
2287 // Retrieve the process memory.
2288 size_t bytes_read = 0;
2289 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2290 read_addr, &buf[0], byte_count, bytes_read);
2293 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2294 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2295 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2297 return SendErrorResponse(0x08);
2300 if (bytes_read == 0) {
2302 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2303 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2304 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2306 return SendErrorResponse(0x08);
2309 StreamGDBRemote response;
2310 packet.SetFilePos(0);
2311 char kind = packet.GetChar('?');
2313 response.PutEscapedBytes(buf.data(), byte_count);
2315 assert(kind == 'm');
2316 for (size_t i = 0; i < bytes_read; ++i)
2317 response.PutHex8(buf[i]);
2320 return SendPacketNoLock(response.GetString());
2323 GDBRemoteCommunication::PacketResult
2324 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2325 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2327 if (!m_debugged_process_up ||
2328 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2331 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2333 return SendErrorResponse(0x15);
2336 // Parse out the memory address.
2337 packet.SetFilePos(strlen("M"));
2338 if (packet.GetBytesLeft() < 1)
2339 return SendIllFormedResponse(packet, "Too short M packet");
2341 // Read the address. Punting on validation.
2342 // FIXME replace with Hex U64 read with no default value that fails on failed
2344 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2347 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2348 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2350 // Get # bytes to read.
2351 if (packet.GetBytesLeft() < 1)
2352 return SendIllFormedResponse(packet, "Length missing in M packet");
2354 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2355 if (byte_count == 0) {
2356 LLDB_LOG(log, "nothing to write: zero-length packet");
2357 return PacketResult::Success;
2361 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2362 return SendIllFormedResponse(
2363 packet, "Comma sep missing in M packet after byte length");
2365 // Allocate the conversion buffer.
2366 std::vector<uint8_t> buf(byte_count, 0);
2368 return SendErrorResponse(0x78);
2370 // Convert the hex memory write contents to bytes.
2371 StreamGDBRemote response;
2372 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2373 if (convert_count != byte_count) {
2375 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2377 m_debugged_process_up->GetID(), write_addr, byte_count,
2379 return SendIllFormedResponse(packet, "M content byte length specified did "
2380 "not match hex-encoded content "
2384 // Write the process memory.
2385 size_t bytes_written = 0;
2386 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2387 byte_count, bytes_written);
2389 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2390 m_debugged_process_up->GetID(), write_addr, error);
2391 return SendErrorResponse(0x09);
2394 if (bytes_written == 0) {
2395 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2396 m_debugged_process_up->GetID(), write_addr, byte_count);
2397 return SendErrorResponse(0x09);
2400 return SendOKResponse();
2403 GDBRemoteCommunication::PacketResult
2404 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2405 StringExtractorGDBRemote &packet) {
2406 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2408 // Currently only the NativeProcessProtocol knows if it can handle a
2409 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2410 // attached to a process. For now we'll assume the client only asks this
2411 // when a process is being debugged.
2413 // Ensure we have a process running; otherwise, we can't figure this out
2414 // since we won't have a NativeProcessProtocol.
2415 if (!m_debugged_process_up ||
2416 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2419 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2421 return SendErrorResponse(0x15);
2424 // Test if we can get any region back when asking for the region around NULL.
2425 MemoryRegionInfo region_info;
2426 const Status error =
2427 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2429 // We don't support memory region info collection for this
2430 // NativeProcessProtocol.
2431 return SendUnimplementedResponse("");
2434 return SendOKResponse();
2437 GDBRemoteCommunication::PacketResult
2438 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2439 StringExtractorGDBRemote &packet) {
2440 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2442 // Ensure we have a process.
2443 if (!m_debugged_process_up ||
2444 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2447 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2449 return SendErrorResponse(0x15);
2452 // Parse out the memory address.
2453 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2454 if (packet.GetBytesLeft() < 1)
2455 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2457 // Read the address. Punting on validation.
2458 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2460 StreamGDBRemote response;
2462 // Get the memory region info for the target address.
2463 MemoryRegionInfo region_info;
2464 const Status error =
2465 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2467 // Return the error message.
2469 response.PutCString("error:");
2470 response.PutStringAsRawHex8(error.AsCString());
2471 response.PutChar(';');
2473 // Range start and size.
2474 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2475 region_info.GetRange().GetRangeBase(),
2476 region_info.GetRange().GetByteSize());
2479 if (region_info.GetReadable() || region_info.GetWritable() ||
2480 region_info.GetExecutable()) {
2481 // Write permissions info.
2482 response.PutCString("permissions:");
2484 if (region_info.GetReadable())
2485 response.PutChar('r');
2486 if (region_info.GetWritable())
2487 response.PutChar('w');
2488 if (region_info.GetExecutable())
2489 response.PutChar('x');
2491 response.PutChar(';');
2495 ConstString name = region_info.GetName();
2497 response.PutCString("name:");
2498 response.PutStringAsRawHex8(name.GetStringRef());
2499 response.PutChar(';');
2503 return SendPacketNoLock(response.GetString());
2506 GDBRemoteCommunication::PacketResult
2507 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2508 // Ensure we have a process.
2509 if (!m_debugged_process_up ||
2510 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2511 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2512 LLDB_LOG(log, "failed, no process available");
2513 return SendErrorResponse(0x15);
2516 // Parse out software or hardware breakpoint or watchpoint requested.
2517 packet.SetFilePos(strlen("Z"));
2518 if (packet.GetBytesLeft() < 1)
2519 return SendIllFormedResponse(
2520 packet, "Too short Z packet, missing software/hardware specifier");
2522 bool want_breakpoint = true;
2523 bool want_hardware = false;
2524 uint32_t watch_flags = 0;
2526 const GDBStoppointType stoppoint_type =
2527 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2528 switch (stoppoint_type) {
2529 case eBreakpointSoftware:
2530 want_hardware = false;
2531 want_breakpoint = true;
2533 case eBreakpointHardware:
2534 want_hardware = true;
2535 want_breakpoint = true;
2537 case eWatchpointWrite:
2539 want_hardware = true;
2540 want_breakpoint = false;
2542 case eWatchpointRead:
2544 want_hardware = true;
2545 want_breakpoint = false;
2547 case eWatchpointReadWrite:
2549 want_hardware = true;
2550 want_breakpoint = false;
2552 case eStoppointInvalid:
2553 return SendIllFormedResponse(
2554 packet, "Z packet had invalid software/hardware specifier");
2557 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2558 return SendIllFormedResponse(
2559 packet, "Malformed Z packet, expecting comma after stoppoint type");
2561 // Parse out the stoppoint address.
2562 if (packet.GetBytesLeft() < 1)
2563 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2564 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2566 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2567 return SendIllFormedResponse(
2568 packet, "Malformed Z packet, expecting comma after address");
2570 // Parse out the stoppoint size (i.e. size hint for opcode size).
2571 const uint32_t size =
2572 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2573 if (size == std::numeric_limits<uint32_t>::max())
2574 return SendIllFormedResponse(
2575 packet, "Malformed Z packet, failed to parse size argument");
2577 if (want_breakpoint) {
2578 // Try to set the breakpoint.
2579 const Status error =
2580 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2581 if (error.Success())
2582 return SendOKResponse();
2583 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2584 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2585 m_debugged_process_up->GetID(), error);
2586 return SendErrorResponse(0x09);
2588 // Try to set the watchpoint.
2589 const Status error = m_debugged_process_up->SetWatchpoint(
2590 addr, size, watch_flags, want_hardware);
2591 if (error.Success())
2592 return SendOKResponse();
2593 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2594 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2595 m_debugged_process_up->GetID(), error);
2596 return SendErrorResponse(0x09);
2600 GDBRemoteCommunication::PacketResult
2601 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2602 // Ensure we have a process.
2603 if (!m_debugged_process_up ||
2604 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2605 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2606 LLDB_LOG(log, "failed, no process available");
2607 return SendErrorResponse(0x15);
2610 // Parse out software or hardware breakpoint or watchpoint requested.
2611 packet.SetFilePos(strlen("z"));
2612 if (packet.GetBytesLeft() < 1)
2613 return SendIllFormedResponse(
2614 packet, "Too short z packet, missing software/hardware specifier");
2616 bool want_breakpoint = true;
2617 bool want_hardware = false;
2619 const GDBStoppointType stoppoint_type =
2620 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2621 switch (stoppoint_type) {
2622 case eBreakpointHardware:
2623 want_breakpoint = true;
2624 want_hardware = true;
2626 case eBreakpointSoftware:
2627 want_breakpoint = true;
2629 case eWatchpointWrite:
2630 want_breakpoint = false;
2632 case eWatchpointRead:
2633 want_breakpoint = false;
2635 case eWatchpointReadWrite:
2636 want_breakpoint = false;
2639 return SendIllFormedResponse(
2640 packet, "z packet had invalid software/hardware specifier");
2643 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2644 return SendIllFormedResponse(
2645 packet, "Malformed z packet, expecting comma after stoppoint type");
2647 // Parse out the stoppoint address.
2648 if (packet.GetBytesLeft() < 1)
2649 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2650 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2652 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2653 return SendIllFormedResponse(
2654 packet, "Malformed z packet, expecting comma after address");
2657 // Parse out the stoppoint size (i.e. size hint for opcode size).
2658 const uint32_t size = packet.GetHexMaxU32 (false,
2659 std::numeric_limits<uint32_t>::max ());
2660 if (size == std::numeric_limits<uint32_t>::max ())
2661 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2665 if (want_breakpoint) {
2666 // Try to clear the breakpoint.
2667 const Status error =
2668 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2669 if (error.Success())
2670 return SendOKResponse();
2671 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2672 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2673 m_debugged_process_up->GetID(), error);
2674 return SendErrorResponse(0x09);
2676 // Try to clear the watchpoint.
2677 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2678 if (error.Success())
2679 return SendOKResponse();
2680 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2681 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2682 m_debugged_process_up->GetID(), error);
2683 return SendErrorResponse(0x09);
2687 GDBRemoteCommunication::PacketResult
2688 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2689 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2691 // Ensure we have a process.
2692 if (!m_debugged_process_up ||
2693 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2696 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2698 return SendErrorResponse(0x32);
2701 // We first try to use a continue thread id. If any one or any all set, use
2702 // the current thread. Bail out if we don't have a thread id.
2703 lldb::tid_t tid = GetContinueThreadID();
2704 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2705 tid = GetCurrentThreadID();
2706 if (tid == LLDB_INVALID_THREAD_ID)
2707 return SendErrorResponse(0x33);
2709 // Double check that we have such a thread.
2710 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2711 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2713 return SendErrorResponse(0x33);
2715 // Create the step action for the given thread.
2716 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
2718 // Setup the actions list.
2719 ResumeActionList actions;
2720 actions.Append(action);
2722 // All other threads stop while we're single stepping a thread.
2723 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2724 Status error = m_debugged_process_up->Resume(actions);
2727 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2728 " tid %" PRIu64 " Resume() failed with error: %s",
2729 __FUNCTION__, m_debugged_process_up->GetID(), tid,
2731 return SendErrorResponse(0x49);
2734 // No response here - the stop or exit will come from the resulting action.
2735 return PacketResult::Success;
2738 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2739 GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
2740 // Ensure we have a thread.
2741 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
2743 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2744 "No thread available");
2746 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2747 // Get the register context for the first thread.
2748 NativeRegisterContext ®_context = thread->GetRegisterContext();
2750 StreamString response;
2752 response.Printf("<?xml version=\"1.0\"?>");
2753 response.Printf("<target version=\"1.0\">");
2755 response.Printf("<architecture>%s</architecture>",
2756 m_debugged_process_up->GetArchitecture()
2762 response.Printf("<feature>");
2764 const int registers_count = reg_context.GetUserRegisterCount();
2765 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
2766 const RegisterInfo *reg_info =
2767 reg_context.GetRegisterInfoAtIndex(reg_index);
2771 "%s failed to get register info for register index %" PRIu32,
2772 "target.xml", reg_index);
2776 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" offset=\"%" PRIu32
2777 "\" regnum=\"%d\" ",
2778 reg_info->name, reg_info->byte_size * 8,
2779 reg_info->byte_offset, reg_index);
2781 if (reg_info->alt_name && reg_info->alt_name[0])
2782 response.Printf("altname=\"%s\" ", reg_info->alt_name);
2784 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2785 if (!encoding.empty())
2786 response << "encoding=\"" << encoding << "\" ";
2788 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2789 if (!format.empty())
2790 response << "format=\"" << format << "\" ";
2792 const char *const register_set_name =
2793 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2794 if (register_set_name)
2795 response << "group=\"" << register_set_name << "\" ";
2797 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2798 LLDB_INVALID_REGNUM)
2799 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
2800 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2802 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
2803 LLDB_INVALID_REGNUM)
2804 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
2805 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2807 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2808 if (!kind_generic.empty())
2809 response << "generic=\"" << kind_generic << "\" ";
2811 if (reg_info->value_regs &&
2812 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2813 response.PutCString("value_regnums=\"");
2814 CollectRegNums(reg_info->value_regs, response, false);
2815 response.Printf("\" ");
2818 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2819 response.PutCString("invalidate_regnums=\"");
2820 CollectRegNums(reg_info->invalidate_regs, response, false);
2821 response.Printf("\" ");
2824 if (reg_info->dynamic_size_dwarf_expr_bytes) {
2825 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
2826 response.PutCString("dynamic_size_dwarf_expr_bytes=\"");
2827 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
2828 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
2829 response.Printf("\" ");
2832 response.Printf("/>");
2835 response.Printf("</feature>");
2836 response.Printf("</target>");
2837 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
2840 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2841 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
2842 llvm::StringRef annex) {
2843 // Make sure we have a valid process.
2844 if (!m_debugged_process_up ||
2845 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2846 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2847 "No process available");
2850 if (object == "auxv") {
2851 // Grab the auxv data.
2852 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2853 if (!buffer_or_error)
2854 return llvm::errorCodeToError(buffer_or_error.getError());
2855 return std::move(*buffer_or_error);
2858 if (object == "libraries-svr4") {
2859 auto library_list = m_debugged_process_up->GetLoadedSVR4Libraries();
2861 return library_list.takeError();
2863 StreamString response;
2864 response.Printf("<library-list-svr4 version=\"1.0\">");
2865 for (auto const &library : *library_list) {
2866 response.Printf("<library name=\"%s\" ",
2867 XMLEncodeAttributeValue(library.name.c_str()).c_str());
2868 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
2869 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
2870 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
2872 response.Printf("</library-list-svr4>");
2873 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
2876 if (object == "features" && annex == "target.xml")
2877 return BuildTargetXml();
2879 return llvm::make_error<PacketUnimplementedError>(
2880 "Xfer object not supported");
2883 GDBRemoteCommunication::PacketResult
2884 GDBRemoteCommunicationServerLLGS::Handle_qXfer(
2885 StringExtractorGDBRemote &packet) {
2886 SmallVector<StringRef, 5> fields;
2887 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
2888 StringRef(packet.GetStringRef()).split(fields, ':', 4);
2889 if (fields.size() != 5)
2890 return SendIllFormedResponse(packet, "malformed qXfer packet");
2891 StringRef &xfer_object = fields[1];
2892 StringRef &xfer_action = fields[2];
2893 StringRef &xfer_annex = fields[3];
2894 StringExtractor offset_data(fields[4]);
2895 if (xfer_action != "read")
2896 return SendUnimplementedResponse("qXfer action not supported");
2898 const uint64_t xfer_offset =
2899 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2900 if (xfer_offset == std::numeric_limits<uint64_t>::max())
2901 return SendIllFormedResponse(packet, "qXfer packet missing offset");
2903 if (offset_data.GetChar() != ',')
2904 return SendIllFormedResponse(packet,
2905 "qXfer packet missing comma after offset");
2906 // Parse out the length.
2907 const uint64_t xfer_length =
2908 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2909 if (xfer_length == std::numeric_limits<uint64_t>::max())
2910 return SendIllFormedResponse(packet, "qXfer packet missing length");
2912 // Get a previously constructed buffer if it exists or create it now.
2913 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
2914 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
2915 if (buffer_it == m_xfer_buffer_map.end()) {
2916 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
2918 return SendErrorResponse(buffer_up.takeError());
2919 buffer_it = m_xfer_buffer_map
2920 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
2924 // Send back the response
2925 StreamGDBRemote response;
2926 bool done_with_buffer = false;
2927 llvm::StringRef buffer = buffer_it->second->getBuffer();
2928 if (xfer_offset >= buffer.size()) {
2929 // We have nothing left to send. Mark the buffer as complete.
2930 response.PutChar('l');
2931 done_with_buffer = true;
2933 // Figure out how many bytes are available starting at the given offset.
2934 buffer = buffer.drop_front(xfer_offset);
2935 // Mark the response type according to whether we're reading the remainder
2937 if (xfer_length >= buffer.size()) {
2938 // There will be nothing left to read after this
2939 response.PutChar('l');
2940 done_with_buffer = true;
2942 // There will still be bytes to read after this request.
2943 response.PutChar('m');
2944 buffer = buffer.take_front(xfer_length);
2946 // Now write the data in encoded binary form.
2947 response.PutEscapedBytes(buffer.data(), buffer.size());
2950 if (done_with_buffer)
2951 m_xfer_buffer_map.erase(buffer_it);
2953 return SendPacketNoLock(response.GetString());
2956 GDBRemoteCommunication::PacketResult
2957 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2958 StringExtractorGDBRemote &packet) {
2959 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2961 // Move past packet name.
2962 packet.SetFilePos(strlen("QSaveRegisterState"));
2964 // Get the thread to use.
2965 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2967 if (m_thread_suffix_supported)
2968 return SendIllFormedResponse(
2969 packet, "No thread specified in QSaveRegisterState packet");
2971 return SendIllFormedResponse(packet,
2972 "No thread was is set with the Hg packet");
2975 // Grab the register context for the thread.
2976 NativeRegisterContext& reg_context = thread->GetRegisterContext();
2978 // Save registers to a buffer.
2979 DataBufferSP register_data_sp;
2980 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2982 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2983 m_debugged_process_up->GetID(), error);
2984 return SendErrorResponse(0x75);
2987 // Allocate a new save id.
2988 const uint32_t save_id = GetNextSavedRegistersID();
2989 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2990 "GetNextRegisterSaveID() returned an existing register save id");
2992 // Save the register data buffer under the save id.
2994 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2995 m_saved_registers_map[save_id] = register_data_sp;
2998 // Write the response.
2999 StreamGDBRemote response;
3000 response.Printf("%" PRIu32, save_id);
3001 return SendPacketNoLock(response.GetString());
3004 GDBRemoteCommunication::PacketResult
3005 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3006 StringExtractorGDBRemote &packet) {
3007 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3009 // Parse out save id.
3010 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3011 if (packet.GetBytesLeft() < 1)
3012 return SendIllFormedResponse(
3013 packet, "QRestoreRegisterState packet missing register save id");
3015 const uint32_t save_id = packet.GetU32(0);
3017 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3018 "expecting decimal uint32_t");
3019 return SendErrorResponse(0x76);
3022 // Get the thread to use.
3023 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3025 if (m_thread_suffix_supported)
3026 return SendIllFormedResponse(
3027 packet, "No thread specified in QRestoreRegisterState packet");
3029 return SendIllFormedResponse(packet,
3030 "No thread was is set with the Hg packet");
3033 // Grab the register context for the thread.
3034 NativeRegisterContext ®_context = thread->GetRegisterContext();
3036 // Retrieve register state buffer, then remove from the list.
3037 DataBufferSP register_data_sp;
3039 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3041 // Find the register set buffer for the given save id.
3042 auto it = m_saved_registers_map.find(save_id);
3043 if (it == m_saved_registers_map.end()) {
3045 "pid {0} does not have a register set save buffer for id {1}",
3046 m_debugged_process_up->GetID(), save_id);
3047 return SendErrorResponse(0x77);
3049 register_data_sp = it->second;
3051 // Remove it from the map.
3052 m_saved_registers_map.erase(it);
3055 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3057 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3058 m_debugged_process_up->GetID(), error);
3059 return SendErrorResponse(0x77);
3062 return SendOKResponse();
3065 GDBRemoteCommunication::PacketResult
3066 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3067 StringExtractorGDBRemote &packet) {
3068 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3070 // Consume the ';' after vAttach.
3071 packet.SetFilePos(strlen("vAttach"));
3072 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3073 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3075 // Grab the PID to which we will attach (assume hex encoding).
3076 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3077 if (pid == LLDB_INVALID_PROCESS_ID)
3078 return SendIllFormedResponse(packet,
3079 "vAttach failed to parse the process id");
3081 // Attempt to attach.
3083 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3087 Status error = AttachToProcess(pid);
3091 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3092 "pid %" PRIu64 ": %s\n",
3093 __FUNCTION__, pid, error.AsCString());
3094 return SendErrorResponse(error);
3097 // Notify we attached by sending a stop packet.
3098 return SendStopReasonForState(m_debugged_process_up->GetState());
3101 GDBRemoteCommunication::PacketResult
3102 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3103 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3105 StopSTDIOForwarding();
3107 // Fail if we don't have a current process.
3108 if (!m_debugged_process_up ||
3109 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
3112 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3114 return SendErrorResponse(0x15);
3117 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3119 // Consume the ';' after D.
3120 packet.SetFilePos(1);
3121 if (packet.GetBytesLeft()) {
3122 if (packet.GetChar() != ';')
3123 return SendIllFormedResponse(packet, "D missing expected ';'");
3125 // Grab the PID from which we will detach (assume hex encoding).
3126 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3127 if (pid == LLDB_INVALID_PROCESS_ID)
3128 return SendIllFormedResponse(packet, "D failed to parse the process id");
3131 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
3132 return SendIllFormedResponse(packet, "Invalid pid");
3135 const Status error = m_debugged_process_up->Detach();
3138 "GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3139 "pid %" PRIu64 ": %s\n",
3140 __FUNCTION__, m_debugged_process_up->GetID(), error.AsCString());
3141 return SendErrorResponse(0x01);
3144 return SendOKResponse();
3147 GDBRemoteCommunication::PacketResult
3148 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3149 StringExtractorGDBRemote &packet) {
3150 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3152 packet.SetFilePos(strlen("qThreadStopInfo"));
3153 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3154 if (tid == LLDB_INVALID_THREAD_ID) {
3156 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3157 "parse thread id from request \"%s\"",
3158 __FUNCTION__, packet.GetStringRef().data());
3159 return SendErrorResponse(0x15);
3161 return SendStopReplyPacketForThread(tid);
3164 GDBRemoteCommunication::PacketResult
3165 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3166 StringExtractorGDBRemote &) {
3167 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3169 // Ensure we have a debugged process.
3170 if (!m_debugged_process_up ||
3171 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3172 return SendErrorResponse(50);
3173 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3175 StreamString response;
3176 const bool threads_with_valid_stop_info_only = false;
3177 llvm::Expected<json::Value> threads_info = GetJSONThreadsInfo(
3178 *m_debugged_process_up, threads_with_valid_stop_info_only);
3179 if (!threads_info) {
3180 LLDB_LOG_ERROR(log, threads_info.takeError(),
3181 "failed to prepare a packet for pid {1}: {0}",
3182 m_debugged_process_up->GetID());
3183 return SendErrorResponse(52);
3186 response.AsRawOstream() << *threads_info;
3187 StreamGDBRemote escaped_response;
3188 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3189 return SendPacketNoLock(escaped_response.GetString());
3192 GDBRemoteCommunication::PacketResult
3193 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3194 StringExtractorGDBRemote &packet) {
3195 // Fail if we don't have a current process.
3196 if (!m_debugged_process_up ||
3197 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3198 return SendErrorResponse(68);
3200 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3201 if (packet.GetBytesLeft() == 0)
3202 return SendOKResponse();
3203 if (packet.GetChar() != ':')
3204 return SendErrorResponse(67);
3206 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3208 StreamGDBRemote response;
3209 if (hw_debug_cap == llvm::None)
3210 response.Printf("num:0;");
3212 response.Printf("num:%d;", hw_debug_cap->second);
3214 return SendPacketNoLock(response.GetString());
3217 GDBRemoteCommunication::PacketResult
3218 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3219 StringExtractorGDBRemote &packet) {
3220 // Fail if we don't have a current process.
3221 if (!m_debugged_process_up ||
3222 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3223 return SendErrorResponse(67);
3225 packet.SetFilePos(strlen("qFileLoadAddress:"));
3226 if (packet.GetBytesLeft() == 0)
3227 return SendErrorResponse(68);
3229 std::string file_name;
3230 packet.GetHexByteString(file_name);
3232 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3234 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3236 return SendErrorResponse(69);
3238 if (file_load_address == LLDB_INVALID_ADDRESS)
3239 return SendErrorResponse(1); // File not loaded
3241 StreamGDBRemote response;
3242 response.PutHex64(file_load_address);
3243 return SendPacketNoLock(response.GetString());
3246 GDBRemoteCommunication::PacketResult
3247 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3248 StringExtractorGDBRemote &packet) {
3249 std::vector<int> signals;
3250 packet.SetFilePos(strlen("QPassSignals:"));
3252 // Read sequence of hex signal numbers divided by a semicolon and optionally
3254 while (packet.GetBytesLeft() > 0) {
3255 int signal = packet.GetS32(-1, 16);
3257 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3258 signals.push_back(signal);
3260 packet.SkipSpaces();
3261 char separator = packet.GetChar();
3262 if (separator == '\0')
3263 break; // End of string
3264 if (separator != ';')
3265 return SendIllFormedResponse(packet, "Invalid separator,"
3266 " expected semicolon.");
3269 // Fail if we don't have a current process.
3270 if (!m_debugged_process_up)
3271 return SendErrorResponse(68);
3273 Status error = m_debugged_process_up->IgnoreSignals(signals);
3275 return SendErrorResponse(69);
3277 return SendOKResponse();
3280 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3281 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3283 // Tell the stdio connection to shut down.
3284 if (m_stdio_communication.IsConnected()) {
3285 auto connection = m_stdio_communication.GetConnection();
3288 connection->Disconnect(&error);
3290 if (error.Success()) {
3292 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3293 "terminal stdio - SUCCESS",
3297 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3298 "terminal stdio - FAIL: %s",
3299 __FUNCTION__, error.AsCString());
3305 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3306 StringExtractorGDBRemote &packet) {
3307 // We have no thread if we don't have a process.
3308 if (!m_debugged_process_up ||
3309 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3312 // If the client hasn't asked for thread suffix support, there will not be a
3313 // thread suffix. Use the current thread in that case.
3314 if (!m_thread_suffix_supported) {
3315 const lldb::tid_t current_tid = GetCurrentThreadID();
3316 if (current_tid == LLDB_INVALID_THREAD_ID)
3318 else if (current_tid == 0) {
3320 return m_debugged_process_up->GetThreadAtIndex(0);
3322 return m_debugged_process_up->GetThreadByID(current_tid);
3325 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3327 // Parse out the ';'.
3328 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3330 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3331 "error: expected ';' prior to start of thread suffix: packet "
3333 __FUNCTION__, packet.GetStringRef().data());
3337 if (!packet.GetBytesLeft())
3340 // Parse out thread: portion.
3341 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3343 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3344 "error: expected 'thread:' but not found, packet contents = "
3346 __FUNCTION__, packet.GetStringRef().data());
3349 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3350 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3352 return m_debugged_process_up->GetThreadByID(tid);
3357 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3358 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3359 // Use whatever the debug process says is the current thread id since the
3360 // protocol either didn't specify or specified we want any/all threads
3361 // marked as the current thread.
3362 if (!m_debugged_process_up)
3363 return LLDB_INVALID_THREAD_ID;
3364 return m_debugged_process_up->GetCurrentThreadID();
3366 // Use the specific current thread id set by the gdb remote protocol.
3367 return m_current_tid;
3370 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3371 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3372 return m_next_saved_registers_id++;
3375 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3376 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3378 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
3379 m_xfer_buffer_map.clear();
3383 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3384 const ArchSpec &arch) {
3385 if (m_debugged_process_up) {
3387 if (m_debugged_process_up
3388 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3390 if (FileSystem::Instance().Exists(file_spec))
3395 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
3398 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
3399 llvm::StringRef value) {
3401 for (const char &c : value) {