1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "lldb/Host/Config.h"
14 #include "GDBRemoteCommunicationServerLLGS.h"
15 #include "lldb/Utility/StreamGDBRemote.h"
23 // Other libraries and framework includes
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Host/ConnectionFileDescriptor.h"
27 #include "lldb/Host/Debug.h"
28 #include "lldb/Host/File.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/common/NativeProcessProtocol.h"
33 #include "lldb/Host/common/NativeRegisterContext.h"
34 #include "lldb/Host/common/NativeThreadProtocol.h"
35 #include "lldb/Interpreter/Args.h"
36 #include "lldb/Target/FileAction.h"
37 #include "lldb/Target/MemoryRegionInfo.h"
38 #include "lldb/Utility/DataBuffer.h"
39 #include "lldb/Utility/Endian.h"
40 #include "lldb/Utility/JSON.h"
41 #include "lldb/Utility/LLDBAssert.h"
42 #include "lldb/Utility/Log.h"
43 #include "lldb/Utility/StreamString.h"
44 #include "lldb/Utility/UriParser.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/Support/ScopedPrinter.h"
49 #include "ProcessGDBRemote.h"
50 #include "ProcessGDBRemoteLog.h"
51 #include "Utility/StringExtractorGDBRemote.h"
54 using namespace lldb_private;
55 using namespace lldb_private::process_gdb_remote;
58 //----------------------------------------------------------------------
60 //----------------------------------------------------------------------
63 enum GDBRemoteServerError {
64 // Set to the first unused error number in literal form below
66 eErrorNoProcess = eErrorFirst,
72 //----------------------------------------------------------------------
73 // GDBRemoteCommunicationServerLLGS constructor
74 //----------------------------------------------------------------------
75 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
76 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
77 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
79 m_mainloop(mainloop), m_process_factory(process_factory),
80 m_stdio_communication("process.stdio") {
81 RegisterPacketHandlers();
84 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
85 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
86 &GDBRemoteCommunicationServerLLGS::Handle_C);
87 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
88 &GDBRemoteCommunicationServerLLGS::Handle_c);
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
90 &GDBRemoteCommunicationServerLLGS::Handle_D);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
92 &GDBRemoteCommunicationServerLLGS::Handle_H);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
94 &GDBRemoteCommunicationServerLLGS::Handle_I);
95 RegisterMemberFunctionHandler(
96 StringExtractorGDBRemote::eServerPacketType_interrupt,
97 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
98 RegisterMemberFunctionHandler(
99 StringExtractorGDBRemote::eServerPacketType_m,
100 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
101 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
102 &GDBRemoteCommunicationServerLLGS::Handle_M);
103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
104 &GDBRemoteCommunicationServerLLGS::Handle_p);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
106 &GDBRemoteCommunicationServerLLGS::Handle_P);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
108 &GDBRemoteCommunicationServerLLGS::Handle_qC);
109 RegisterMemberFunctionHandler(
110 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
111 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
112 RegisterMemberFunctionHandler(
113 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
114 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
117 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
120 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
123 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
129 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
132 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
135 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
138 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
141 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
144 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
147 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158 &GDBRemoteCommunicationServerLLGS::Handle_s);
159 RegisterMemberFunctionHandler(
160 StringExtractorGDBRemote::eServerPacketType_stop_reason,
161 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
162 RegisterMemberFunctionHandler(
163 StringExtractorGDBRemote::eServerPacketType_vAttach,
164 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_vCont,
167 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
170 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_x,
173 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
174 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
175 &GDBRemoteCommunicationServerLLGS::Handle_Z);
176 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
177 &GDBRemoteCommunicationServerLLGS::Handle_z);
178 RegisterMemberFunctionHandler(
179 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
180 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
184 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
185 RegisterMemberFunctionHandler(
186 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
187 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
188 RegisterMemberFunctionHandler(
189 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
190 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
191 RegisterMemberFunctionHandler(
192 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
193 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
194 RegisterMemberFunctionHandler(
195 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
196 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
198 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
199 [this](StringExtractorGDBRemote packet, Status &error,
200 bool &interrupt, bool &quit) {
202 return this->Handle_k(packet);
207 GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
209 if ((argc < 1) || !args || !args[0] || !args[0][0])
210 return Status("%s: no process command line specified to launch",
213 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
218 GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
219 m_process_launch_info.GetFlags().Set(launch_flags);
223 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
224 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
226 if (!m_process_launch_info.GetArguments().GetArgumentCount())
227 return Status("%s: no process command line specified to launch",
230 const bool should_forward_stdio =
231 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
232 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
233 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
234 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
235 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
237 const bool default_to_use_pty = true;
238 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
241 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
242 assert(!m_debugged_process_sp && "lldb-server creating debugged "
243 "process but one already exists");
245 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
247 Status status(process_or.takeError());
248 llvm::errs() << llvm::formatv(
249 "failed to launch executable `{0}`: {1}",
250 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), status);
253 m_debugged_process_sp = *process_or;
256 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
258 // llgs local-process debugging may specify PTY paths, which will make these
259 // file actions non-null
260 // process launch -i/e/o will also make these file actions non-null
261 // nullptr means that the traffic is expected to flow over gdb-remote protocol
262 if (should_forward_stdio) {
263 // nullptr means it's not redirected to file or pty (in case of LLGS local)
264 // at least one of stdio will be transferred pty<->gdb-remote
265 // we need to give the pty master handle to this object to read and/or write
268 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
269 " setting up stdout/stderr redirection via $O gdb-remote commands",
270 __FUNCTION__, m_debugged_process_sp->GetID());
272 // Setup stdout/stderr mapping from inferior to $O
273 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
274 if (terminal_fd >= 0) {
276 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
277 "inferior STDIO fd to %d",
278 __FUNCTION__, terminal_fd);
279 Status status = SetSTDIOFileDescriptor(terminal_fd);
284 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
285 "inferior STDIO since terminal fd reported as %d",
286 __FUNCTION__, terminal_fd);
290 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
291 " skipping stdout/stderr redirection via $O: inferior will "
292 "communicate over client-provided file descriptors",
293 __FUNCTION__, m_debugged_process_sp->GetID());
296 printf("Launched '%s' as process %" PRIu64 "...\n",
297 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
298 m_debugged_process_sp->GetID());
303 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
304 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
306 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
309 // Before we try to attach, make sure we aren't already monitoring something
311 if (m_debugged_process_sp &&
312 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
313 return Status("cannot attach to a process %" PRIu64
314 " when another process with pid %" PRIu64
315 " is being debugged.",
316 pid, m_debugged_process_sp->GetID());
319 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
321 Status status(process_or.takeError());
322 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
326 m_debugged_process_sp = *process_or;
328 // Setup stdout/stderr mapping from inferior.
329 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
330 if (terminal_fd >= 0) {
332 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
333 "inferior STDIO fd to %d",
334 __FUNCTION__, terminal_fd);
335 Status status = SetSTDIOFileDescriptor(terminal_fd);
340 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
341 "inferior STDIO since terminal fd reported as %d",
342 __FUNCTION__, terminal_fd);
345 printf("Attached to process %" PRIu64 "...\n", pid);
349 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
350 NativeProcessProtocol *process) {
351 assert(process && "process cannot be NULL");
352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
354 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
355 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
356 __FUNCTION__, process->GetID(),
357 StateAsCString(process->GetState()));
361 GDBRemoteCommunication::PacketResult
362 GDBRemoteCommunicationServerLLGS::SendWResponse(
363 NativeProcessProtocol *process) {
364 assert(process && "process cannot be NULL");
365 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
367 // send W notification
368 auto wait_status = process->GetExitStatus();
370 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
373 StreamGDBRemote response;
374 response.PutChar('E');
375 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
376 return SendPacketNoLock(response.GetString());
379 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
382 StreamGDBRemote response;
383 response.Format("{0:g}", *wait_status);
384 return SendPacketNoLock(response.GetString());
387 static void AppendHexValue(StreamString &response, const uint8_t *buf,
388 uint32_t buf_size, bool swap) {
391 for (i = buf_size - 1; i >= 0; i--)
392 response.PutHex8(buf[i]);
394 for (i = 0; i < buf_size; i++)
395 response.PutHex8(buf[i]);
399 static void WriteRegisterValueInHexFixedWidth(
400 StreamString &response, NativeRegisterContextSP ®_ctx_sp,
401 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
402 lldb::ByteOrder byte_order) {
403 RegisterValue reg_value;
405 Status error = reg_ctx_sp->ReadRegister(®_info, reg_value);
407 reg_value_p = ®_value;
412 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
413 reg_value_p->GetByteSize(),
414 byte_order == lldb::eByteOrderLittle);
416 // Zero-out any unreadable values.
417 if (reg_info.byte_size > 0) {
418 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
419 AppendHexValue(response, zeros.data(), zeros.size(), false);
424 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
425 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
427 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
431 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
433 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
434 // Expedite all registers in the first register set (i.e. should be GPRs) that
435 // are not contained in other registers.
436 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
439 for (const uint32_t *reg_num_p = reg_set_p->registers;
440 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
441 uint32_t reg_num = *reg_num_p;
443 // Expedite only a couple of registers until we figure out why sending
446 static const uint32_t k_expedited_registers[] = {
447 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
448 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
450 for (const uint32_t *generic_reg_p = k_expedited_registers;
451 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
452 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
453 eRegisterKindGeneric, *generic_reg_p);
454 if (reg_num == LLDB_INVALID_REGNUM)
455 continue; // Target does not support the given register.
458 const RegisterInfo *const reg_info_p =
459 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
460 if (reg_info_p == nullptr) {
463 "%s failed to get register info for register index %" PRIu32,
464 __FUNCTION__, reg_num);
468 if (reg_info_p->value_regs != nullptr)
469 continue; // Only expedite registers that are not contained in other
472 RegisterValue reg_value;
473 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
476 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
478 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
479 reg_num, error.AsCString());
484 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
485 ®_value, lldb::eByteOrderBig);
487 register_object_sp->SetObject(
488 llvm::to_string(reg_num),
489 std::make_shared<JSONString>(stream.GetString()));
492 return register_object_sp;
495 static const char *GetStopReasonString(StopReason stop_reason) {
496 switch (stop_reason) {
497 case eStopReasonTrace:
499 case eStopReasonBreakpoint:
501 case eStopReasonWatchpoint:
503 case eStopReasonSignal:
505 case eStopReasonException:
507 case eStopReasonExec:
509 case eStopReasonInstrumentation:
510 case eStopReasonInvalid:
511 case eStopReasonPlanComplete:
512 case eStopReasonThreadExiting:
513 case eStopReasonNone:
519 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
523 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
525 // Ensure we can get info on the given thread.
526 uint32_t thread_idx = 0;
527 for (NativeThreadProtocolSP thread_sp;
528 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
531 lldb::tid_t tid = thread_sp->GetID();
533 // Grab the reason this thread stopped.
534 struct ThreadStopInfo tid_stop_info;
535 std::string description;
536 if (!thread_sp->GetStopReason(tid_stop_info, description))
539 const int signum = tid_stop_info.details.signal.signo;
541 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
543 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
544 __FUNCTION__, process.GetID(), tid, signum,
545 tid_stop_info.reason, tid_stop_info.details.exception.type);
548 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
549 threads_array_sp->AppendObject(thread_obj_sp);
552 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
553 thread_obj_sp->SetObject("registers", registers_sp);
556 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
558 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
560 const std::string thread_name = thread_sp->GetName();
561 if (!thread_name.empty())
562 thread_obj_sp->SetObject("name",
563 std::make_shared<JSONString>(thread_name));
565 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
566 thread_obj_sp->SetObject("reason",
567 std::make_shared<JSONString>(stop_reason_str));
569 if (!description.empty())
570 thread_obj_sp->SetObject("description",
571 std::make_shared<JSONString>(description));
573 if ((tid_stop_info.reason == eStopReasonException) &&
574 tid_stop_info.details.exception.type) {
575 thread_obj_sp->SetObject(
577 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
579 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
580 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
582 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
583 tid_stop_info.details.exception.data[i]));
585 thread_obj_sp->SetObject("medata", medata_array_sp);
588 // TODO: Expedite interesting regions of inferior memory
591 return threads_array_sp;
594 GDBRemoteCommunication::PacketResult
595 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
597 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
599 // Ensure we have a debugged process.
600 if (!m_debugged_process_sp ||
601 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
602 return SendErrorResponse(50);
606 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
608 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
610 // Ensure we can get info on the given thread.
611 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
613 return SendErrorResponse(51);
615 // Grab the reason this thread stopped.
616 struct ThreadStopInfo tid_stop_info;
617 std::string description;
618 if (!thread_sp->GetStopReason(tid_stop_info, description))
619 return SendErrorResponse(52);
621 // FIXME implement register handling for exec'd inferiors.
622 // if (tid_stop_info.reason == eStopReasonExec)
624 // const bool force = true;
625 // InitializeRegisters(force);
628 StreamString response;
629 // Output the T packet with the thread
630 response.PutChar('T');
631 int signum = tid_stop_info.details.signal.signo;
633 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
635 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
636 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
637 tid_stop_info.reason, tid_stop_info.details.exception.type);
640 // Print the signal number.
641 response.PutHex8(signum & 0xff);
644 response.Printf("thread:%" PRIx64 ";", tid);
646 // Include the thread name if there is one.
647 const std::string thread_name = thread_sp->GetName();
648 if (!thread_name.empty()) {
649 size_t thread_name_len = thread_name.length();
651 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
652 response.PutCString("name:");
653 response.PutCString(thread_name);
655 // The thread name contains special chars, send as hex bytes.
656 response.PutCString("hexname:");
657 response.PutCStringAsRawHex8(thread_name.c_str());
659 response.PutChar(';');
662 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
663 // will send all thread IDs back in the "threads" key whose value is
664 // a list of hex thread IDs separated by commas:
665 // "threads:10a,10b,10c;"
666 // This will save the debugger from having to send a pair of qfThreadInfo
667 // and qsThreadInfo packets, but it also might take a lot of room in the
668 // stop reply packet, so it must be enabled only on systems where there
669 // are no limits on packet lengths.
670 if (m_list_threads_in_stop_reply) {
671 response.PutCString("threads:");
673 uint32_t thread_index = 0;
674 NativeThreadProtocolSP listed_thread_sp;
675 for (listed_thread_sp =
676 m_debugged_process_sp->GetThreadAtIndex(thread_index);
677 listed_thread_sp; ++thread_index,
678 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
680 if (thread_index > 0)
681 response.PutChar(',');
682 response.Printf("%" PRIx64, listed_thread_sp->GetID());
684 response.PutChar(';');
686 // Include JSON info that describes the stop reason for any threads
687 // that actually have stop reasons. We use the new "jstopinfo" key
688 // whose values is hex ascii JSON that contains the thread IDs
689 // thread stop info only for threads that have stop reasons. Only send
690 // this if we have more than one thread otherwise this packet has all
691 // the info it needs.
692 if (thread_index > 0) {
693 const bool threads_with_valid_stop_info_only = true;
694 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
695 *m_debugged_process_sp, threads_with_valid_stop_info_only);
696 if (threads_info_sp) {
697 response.PutCString("jstopinfo:");
698 StreamString unescaped_response;
699 threads_info_sp->Write(unescaped_response);
700 response.PutCStringAsRawHex8(unescaped_response.GetData());
701 response.PutChar(';');
703 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
704 "jstopinfo field for pid %" PRIu64,
705 __FUNCTION__, m_debugged_process_sp->GetID());
709 response.PutCString("thread-pcs");
710 char delimiter = ':';
711 for (NativeThreadProtocolSP thread_sp;
712 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
714 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
718 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
719 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
720 const RegisterInfo *const reg_info_p =
721 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
723 RegisterValue reg_value;
724 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
727 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
729 reg_info_p->name ? reg_info_p->name
730 : "<unnamed-register>",
731 reg_to_read, error.AsCString());
735 response.PutChar(delimiter);
737 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
738 ®_value, endian::InlHostByteOrder());
741 response.PutChar(';');
745 // Expedite registers.
748 // Grab the register context.
749 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
751 // Expedite all registers in the first register set (i.e. should be GPRs)
752 // that are not contained in other registers.
753 const RegisterSet *reg_set_p;
754 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
755 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
757 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
758 "from set '%s' (registers set count: %zu)",
760 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
761 reg_set_p->num_registers);
763 for (const uint32_t *reg_num_p = reg_set_p->registers;
764 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
765 const RegisterInfo *const reg_info_p =
766 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
767 if (reg_info_p == nullptr) {
769 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
770 "register info for register set '%s', register index "
773 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
775 } else if (reg_info_p->value_regs == nullptr) {
776 // Only expediate registers that are not contained in other registers.
777 RegisterValue reg_value;
778 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
779 if (error.Success()) {
780 response.Printf("%.02x:", *reg_num_p);
781 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
782 ®_value, lldb::eByteOrderBig);
783 response.PutChar(';');
786 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
787 "register '%s' index %" PRIu32 ": %s",
788 __FUNCTION__, reg_info_p->name ? reg_info_p->name
789 : "<unnamed-register>",
790 *reg_num_p, error.AsCString());
797 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
798 if (reason_str != nullptr) {
799 response.Printf("reason:%s;", reason_str);
802 if (!description.empty()) {
803 // Description may contains special chars, send as hex bytes.
804 response.PutCString("description:");
805 response.PutCStringAsRawHex8(description.c_str());
806 response.PutChar(';');
807 } else if ((tid_stop_info.reason == eStopReasonException) &&
808 tid_stop_info.details.exception.type) {
809 response.PutCString("metype:");
810 response.PutHex64(tid_stop_info.details.exception.type);
811 response.PutCString(";mecount:");
812 response.PutHex32(tid_stop_info.details.exception.data_count);
813 response.PutChar(';');
815 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
816 response.PutCString("medata:");
817 response.PutHex64(tid_stop_info.details.exception.data[i]);
818 response.PutChar(';');
822 return SendPacketNoLock(response.GetString());
825 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
826 NativeProcessProtocol *process) {
827 assert(process && "process cannot be NULL");
829 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
831 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
833 PacketResult result = SendStopReasonForState(StateType::eStateExited);
834 if (result != PacketResult::Success) {
836 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
837 "notification for PID %" PRIu64 ", state: eStateExited",
838 __FUNCTION__, process->GetID());
841 // Close the pipe to the inferior terminal i/o if we launched it
843 MaybeCloseInferiorTerminalConnection();
845 // We are ready to exit the debug monitor.
849 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
850 NativeProcessProtocol *process) {
851 assert(process && "process cannot be NULL");
853 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
855 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
857 // Send the stop reason unless this is the stop after the
859 switch (m_inferior_prev_state) {
860 case eStateLaunching:
861 case eStateAttaching:
862 // Don't send anything per debugserver behavior.
865 // In all other cases, send the stop reason.
866 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
867 if (result != PacketResult::Success) {
869 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
870 "notification for PID %" PRIu64 ", state: eStateExited",
871 __FUNCTION__, process->GetID());
877 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
878 NativeProcessProtocol *process, lldb::StateType state) {
879 assert(process && "process cannot be NULL");
880 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
882 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
883 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
884 __FUNCTION__, process->GetID(), StateAsCString(state));
888 case StateType::eStateRunning:
889 StartSTDIOForwarding();
892 case StateType::eStateStopped:
893 // Make sure we get all of the pending stdout/stderr from the inferior
894 // and send it to the lldb host before we send the state change
897 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
899 // interfere with our protocol.
900 StopSTDIOForwarding();
901 HandleInferiorState_Stopped(process);
904 case StateType::eStateExited:
907 StopSTDIOForwarding();
908 HandleInferiorState_Exited(process);
913 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
914 "change for pid %" PRIu64 ", new state: %s",
915 __FUNCTION__, process->GetID(), StateAsCString(state));
920 // Remember the previous state reported to us.
921 m_inferior_prev_state = state;
924 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
925 ClearProcessSpecificData();
928 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
929 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
931 if (!m_handshake_completed) {
932 if (!HandshakeWithClient()) {
934 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
935 "client failed, exiting",
937 m_mainloop.RequestTermination();
940 m_handshake_completed = true;
943 bool interrupt = false;
947 const PacketResult result = GetPacketAndSendResponse(
948 std::chrono::microseconds(0), error, interrupt, done);
949 if (result == PacketResult::ErrorReplyTimeout)
950 break; // No more packets in the queue
952 if ((result != PacketResult::Success)) {
954 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
956 __FUNCTION__, error.AsCString());
957 m_mainloop.RequestTermination();
963 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
964 std::unique_ptr<Connection> &&connection) {
965 IOObjectSP read_object_sp = connection->GetReadObject();
966 GDBRemoteCommunicationServer::SetConnection(connection.release());
969 m_network_handle_up = m_mainloop.RegisterReadObject(
970 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
975 GDBRemoteCommunication::PacketResult
976 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
978 if ((buffer == nullptr) || (len == 0)) {
980 return PacketResult::Success;
983 StreamString response;
984 response.PutChar('O');
985 response.PutBytesAsRawHex8(buffer, len);
987 return SendPacketNoLock(response.GetString());
990 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
993 // Set up the reading/handling of process I/O
994 std::unique_ptr<ConnectionFileDescriptor> conn_up(
995 new ConnectionFileDescriptor(fd, true));
997 error.SetErrorString("failed to create ConnectionFileDescriptor");
1001 m_stdio_communication.SetCloseOnEOF(false);
1002 m_stdio_communication.SetConnection(conn_up.release());
1003 if (!m_stdio_communication.IsConnected()) {
1004 error.SetErrorString(
1005 "failed to set connection for inferior I/O communication");
1012 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1013 // Don't forward if not connected (e.g. when attaching).
1014 if (!m_stdio_communication.IsConnected())
1018 lldbassert(!m_stdio_handle_up);
1019 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1020 m_stdio_communication.GetConnection()->GetReadObject(),
1021 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1023 if (!m_stdio_handle_up) {
1024 // Not much we can do about the failure. Log it and continue without
1026 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1027 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1029 __FUNCTION__, error.AsCString());
1033 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1034 m_stdio_handle_up.reset();
1037 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1039 ConnectionStatus status;
1042 size_t bytes_read = m_stdio_communication.Read(
1043 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1045 case eConnectionStatusSuccess:
1046 SendONotification(buffer, bytes_read);
1048 case eConnectionStatusLostConnection:
1049 case eConnectionStatusEndOfFile:
1050 case eConnectionStatusError:
1051 case eConnectionStatusNoConnection:
1052 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1053 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1054 "forwarding as communication returned status %d (error: "
1056 __FUNCTION__, status, error.AsCString());
1057 m_stdio_handle_up.reset();
1060 case eConnectionStatusInterrupted:
1061 case eConnectionStatusTimedOut:
1067 GDBRemoteCommunication::PacketResult
1068 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1069 StringExtractorGDBRemote &packet) {
1070 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1071 // Fail if we don't have a current process.
1072 if (!m_debugged_process_sp ||
1073 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1074 return SendErrorResponse(68);
1076 if (!packet.ConsumeFront("jTraceStart:"))
1077 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1079 TraceOptions options;
1080 uint64_t type = std::numeric_limits<uint64_t>::max();
1081 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1082 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1083 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1085 auto json_object = StructuredData::ParseJSON(packet.Peek());
1088 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1089 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1091 auto json_dict = json_object->GetAsDictionary();
1093 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1094 options.setMetaDataBufferSize(metabuffersize);
1096 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1097 options.setTraceBufferSize(buffersize);
1099 json_dict->GetValueForKeyAsInteger("type", type);
1100 options.setType(static_cast<lldb::TraceType>(type));
1102 json_dict->GetValueForKeyAsInteger("threadid", tid);
1103 options.setThreadID(tid);
1105 StructuredData::ObjectSP custom_params_sp =
1106 json_dict->GetValueForKey("params");
1107 if (custom_params_sp &&
1108 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1109 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1111 options.setTraceParams(
1112 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1114 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1115 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1116 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1118 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1122 lldb::user_id_t uid = LLDB_INVALID_UID;
1123 uid = m_debugged_process_sp->StartTrace(options, error);
1124 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1126 return SendErrorResponse(error);
1128 StreamGDBRemote response;
1129 response.Printf("%" PRIx64, uid);
1130 return SendPacketNoLock(response.GetString());
1133 GDBRemoteCommunication::PacketResult
1134 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1135 StringExtractorGDBRemote &packet) {
1136 // Fail if we don't have a current process.
1137 if (!m_debugged_process_sp ||
1138 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1139 return SendErrorResponse(68);
1141 if (!packet.ConsumeFront("jTraceStop:"))
1142 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1144 lldb::user_id_t uid = LLDB_INVALID_UID;
1145 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1147 auto json_object = StructuredData::ParseJSON(packet.Peek());
1150 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1151 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1153 auto json_dict = json_object->GetAsDictionary();
1155 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1156 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1158 json_dict->GetValueForKeyAsInteger("threadid", tid);
1160 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1163 return SendErrorResponse(error);
1165 return SendOKResponse();
1168 GDBRemoteCommunication::PacketResult
1169 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1170 StringExtractorGDBRemote &packet) {
1172 // Fail if we don't have a current process.
1173 if (!m_debugged_process_sp ||
1174 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1175 return SendErrorResponse(68);
1177 if (!packet.ConsumeFront("jTraceConfigRead:"))
1178 return SendIllFormedResponse(packet,
1179 "jTraceConfigRead: Ill formed packet ");
1181 lldb::user_id_t uid = LLDB_INVALID_UID;
1182 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1184 auto json_object = StructuredData::ParseJSON(packet.Peek());
1187 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1188 return SendIllFormedResponse(packet,
1189 "jTraceConfigRead: Ill formed packet ");
1191 auto json_dict = json_object->GetAsDictionary();
1193 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1194 return SendIllFormedResponse(packet,
1195 "jTraceConfigRead: Ill formed packet ");
1197 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1199 TraceOptions options;
1200 StreamGDBRemote response;
1202 options.setThreadID(threadid);
1203 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1206 return SendErrorResponse(error);
1208 StreamGDBRemote escaped_response;
1209 StructuredData::Dictionary json_packet;
1211 json_packet.AddIntegerItem("type", options.getType());
1212 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1213 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1215 StructuredData::DictionarySP custom_params = options.getTraceParams();
1217 json_packet.AddItem("params", custom_params);
1219 StreamString json_string;
1220 json_packet.Dump(json_string, false);
1221 escaped_response.PutEscapedBytes(json_string.GetData(),
1222 json_string.GetSize());
1223 return SendPacketNoLock(escaped_response.GetString());
1226 GDBRemoteCommunication::PacketResult
1227 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1228 StringExtractorGDBRemote &packet) {
1230 // Fail if we don't have a current process.
1231 if (!m_debugged_process_sp ||
1232 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1233 return SendErrorResponse(68);
1235 enum PacketType { MetaData, BufferData };
1236 PacketType tracetype = MetaData;
1238 if (packet.ConsumeFront("jTraceBufferRead:"))
1239 tracetype = BufferData;
1240 else if (packet.ConsumeFront("jTraceMetaRead:"))
1241 tracetype = MetaData;
1243 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1246 lldb::user_id_t uid = LLDB_INVALID_UID;
1248 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1249 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1250 uint64_t offset = std::numeric_limits<uint64_t>::max();
1252 auto json_object = StructuredData::ParseJSON(packet.Peek());
1255 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1256 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1258 auto json_dict = json_object->GetAsDictionary();
1260 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1261 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1262 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1263 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1265 json_dict->GetValueForKeyAsInteger("threadid", tid);
1267 // Allocate the response buffer.
1268 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1270 return SendErrorResponse(0x78);
1272 StreamGDBRemote response;
1274 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1276 if (tracetype == BufferData)
1277 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1278 else if (tracetype == MetaData)
1279 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1282 return SendErrorResponse(error);
1285 response.PutHex8(i);
1287 StreamGDBRemote escaped_response;
1288 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1289 return SendPacketNoLock(escaped_response.GetString());
1292 GDBRemoteCommunication::PacketResult
1293 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1294 StringExtractorGDBRemote &packet) {
1295 // Fail if we don't have a current process.
1296 if (!m_debugged_process_sp ||
1297 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1298 return SendErrorResponse(68);
1300 lldb::pid_t pid = m_debugged_process_sp->GetID();
1302 if (pid == LLDB_INVALID_PROCESS_ID)
1303 return SendErrorResponse(1);
1305 ProcessInstanceInfo proc_info;
1306 if (!Host::GetProcessInfo(pid, proc_info))
1307 return SendErrorResponse(1);
1309 StreamString response;
1310 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1311 return SendPacketNoLock(response.GetString());
1314 GDBRemoteCommunication::PacketResult
1315 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1316 // Fail if we don't have a current process.
1317 if (!m_debugged_process_sp ||
1318 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1319 return SendErrorResponse(68);
1321 // Make sure we set the current thread so g and p packets return
1322 // the data the gdb will expect.
1323 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1324 SetCurrentThreadID(tid);
1326 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1328 return SendErrorResponse(69);
1330 StreamString response;
1331 response.Printf("QC%" PRIx64, thread_sp->GetID());
1333 return SendPacketNoLock(response.GetString());
1336 GDBRemoteCommunication::PacketResult
1337 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1338 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1340 StopSTDIOForwarding();
1342 if (!m_debugged_process_sp) {
1345 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1347 return PacketResult::Success;
1350 Status error = m_debugged_process_sp->Kill();
1351 if (error.Fail() && log)
1352 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1353 "process %" PRIu64 ": %s",
1354 __FUNCTION__, m_debugged_process_sp->GetID(),
1357 // No OK response for kill packet.
1358 // return SendOKResponse ();
1359 return PacketResult::Success;
1362 GDBRemoteCommunication::PacketResult
1363 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1364 StringExtractorGDBRemote &packet) {
1365 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1366 if (packet.GetU32(0))
1367 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1369 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1370 return SendOKResponse();
1373 GDBRemoteCommunication::PacketResult
1374 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1375 StringExtractorGDBRemote &packet) {
1376 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1378 packet.GetHexByteString(path);
1379 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1380 return SendOKResponse();
1383 GDBRemoteCommunication::PacketResult
1384 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1385 StringExtractorGDBRemote &packet) {
1386 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1388 StreamString response;
1389 response.PutCStringAsRawHex8(working_dir.GetCString());
1390 return SendPacketNoLock(response.GetString());
1393 return SendErrorResponse(14);
1396 GDBRemoteCommunication::PacketResult
1397 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1398 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1400 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1402 // Ensure we have a native process.
1403 if (!m_debugged_process_sp) {
1405 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1408 return SendErrorResponse(0x36);
1411 // Pull out the signal number.
1412 packet.SetFilePos(::strlen("C"));
1413 if (packet.GetBytesLeft() < 1) {
1414 // Shouldn't be using a C without a signal.
1415 return SendIllFormedResponse(packet, "C packet specified without signal.");
1417 const uint32_t signo =
1418 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1419 if (signo == std::numeric_limits<uint32_t>::max())
1420 return SendIllFormedResponse(packet, "failed to parse signal number");
1422 // Handle optional continue address.
1423 if (packet.GetBytesLeft() > 0) {
1424 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1425 if (*packet.Peek() == ';')
1426 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1428 return SendIllFormedResponse(
1429 packet, "unexpected content after $C{signal-number}");
1432 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1435 // We have two branches: what to do if a continue thread is specified (in
1436 // which case we target
1437 // sending the signal to that thread), or when we don't have a continue thread
1439 // case we send a signal to the process).
1441 // TODO discuss with Greg Clayton, make sure this makes sense.
1443 lldb::tid_t signal_tid = GetContinueThreadID();
1444 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1445 // The resume action for the continue thread (or all threads if a continue
1446 // thread is not set).
1447 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1448 static_cast<int>(signo)};
1450 // Add the action for the continue thread (or all threads when the continue
1451 // thread isn't present).
1452 resume_actions.Append(action);
1454 // Send the signal to the process since we weren't targeting a specific
1455 // continue thread with the signal.
1456 error = m_debugged_process_sp->Signal(signo);
1459 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1460 "signal for process %" PRIu64 ": %s",
1461 __FUNCTION__, m_debugged_process_sp->GetID(),
1464 return SendErrorResponse(0x52);
1468 // Resume the threads.
1469 error = m_debugged_process_sp->Resume(resume_actions);
1472 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1473 "threads for process %" PRIu64 ": %s",
1474 __FUNCTION__, m_debugged_process_sp->GetID(),
1477 return SendErrorResponse(0x38);
1480 // Don't send an "OK" packet; response is the stopped/exited message.
1481 return PacketResult::Success;
1484 GDBRemoteCommunication::PacketResult
1485 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1486 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1488 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1490 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1492 // For now just support all continue.
1493 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1494 if (has_continue_address) {
1496 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1497 "c{address} variant [%s remains]",
1498 __FUNCTION__, packet.Peek());
1499 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1502 // Ensure we have a native process.
1503 if (!m_debugged_process_sp) {
1505 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1508 return SendErrorResponse(0x36);
1511 // Build the ResumeActionList
1512 ResumeActionList actions(StateType::eStateRunning, 0);
1514 Status error = m_debugged_process_sp->Resume(actions);
1518 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1520 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1522 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1527 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1528 __FUNCTION__, m_debugged_process_sp->GetID());
1530 // No response required from continue.
1531 return PacketResult::Success;
1534 GDBRemoteCommunication::PacketResult
1535 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1536 StringExtractorGDBRemote &packet) {
1537 StreamString response;
1538 response.Printf("vCont;c;C;s;S");
1540 return SendPacketNoLock(response.GetString());
1543 GDBRemoteCommunication::PacketResult
1544 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1545 StringExtractorGDBRemote &packet) {
1546 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1548 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1551 packet.SetFilePos(::strlen("vCont"));
1553 if (packet.GetBytesLeft() == 0) {
1555 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1558 return SendIllFormedResponse(packet, "Missing action from vCont package");
1561 // Check if this is all continue (no options or ";c").
1562 if (::strcmp(packet.Peek(), ";c") == 0) {
1563 // Move past the ';', then do a simple 'c'.
1564 packet.SetFilePos(packet.GetFilePos() + 1);
1565 return Handle_c(packet);
1566 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1567 // Move past the ';', then do a simple 's'.
1568 packet.SetFilePos(packet.GetFilePos() + 1);
1569 return Handle_s(packet);
1572 // Ensure we have a native process.
1573 if (!m_debugged_process_sp) {
1575 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1578 return SendErrorResponse(0x36);
1581 ResumeActionList thread_actions;
1583 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1584 // Skip the semi-colon.
1587 // Build up the thread action.
1588 ResumeAction thread_action;
1589 thread_action.tid = LLDB_INVALID_THREAD_ID;
1590 thread_action.state = eStateInvalid;
1591 thread_action.signal = 0;
1593 const char action = packet.GetChar();
1596 thread_action.signal = packet.GetHexMaxU32(false, 0);
1597 if (thread_action.signal == 0)
1598 return SendIllFormedResponse(
1599 packet, "Could not parse signal in vCont packet C action");
1604 thread_action.state = eStateRunning;
1608 thread_action.signal = packet.GetHexMaxU32(false, 0);
1609 if (thread_action.signal == 0)
1610 return SendIllFormedResponse(
1611 packet, "Could not parse signal in vCont packet S action");
1616 thread_action.state = eStateStepping;
1620 return SendIllFormedResponse(packet, "Unsupported vCont action");
1624 // Parse out optional :{thread-id} value.
1625 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1626 // Consume the separator.
1629 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1630 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1631 return SendIllFormedResponse(
1632 packet, "Could not parse thread number in vCont packet");
1635 thread_actions.Append(thread_action);
1638 Status error = m_debugged_process_sp->Resume(thread_actions);
1641 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1642 "process %" PRIu64 ": %s",
1643 __FUNCTION__, m_debugged_process_sp->GetID(),
1646 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1651 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1652 __FUNCTION__, m_debugged_process_sp->GetID());
1654 // No response required from vCont.
1655 return PacketResult::Success;
1658 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1659 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1661 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1665 m_current_tid = tid;
1666 if (m_debugged_process_sp)
1667 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1670 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1671 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1673 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1677 m_continue_tid = tid;
1680 GDBRemoteCommunication::PacketResult
1681 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1682 StringExtractorGDBRemote &packet) {
1683 // Handle the $? gdbremote command.
1685 // If no process, indicate error
1686 if (!m_debugged_process_sp)
1687 return SendErrorResponse(02);
1689 return SendStopReasonForState(m_debugged_process_sp->GetState());
1692 GDBRemoteCommunication::PacketResult
1693 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1694 lldb::StateType process_state) {
1695 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1697 switch (process_state) {
1698 case eStateAttaching:
1699 case eStateLaunching:
1701 case eStateStepping:
1702 case eStateDetached:
1703 // NOTE: gdb protocol doc looks like it should return $OK
1704 // when everything is running (i.e. no stopped result).
1705 return PacketResult::Success; // Ignore
1707 case eStateSuspended:
1709 case eStateCrashed: {
1710 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1711 // Make sure we set the current thread so g and p packets return
1712 // the data the gdb will expect.
1713 SetCurrentThreadID(tid);
1714 return SendStopReplyPacketForThread(tid);
1718 case eStateUnloaded:
1720 return SendWResponse(m_debugged_process_sp.get());
1724 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1725 ", current state reporting not handled: %s",
1726 __FUNCTION__, m_debugged_process_sp->GetID(),
1727 StateAsCString(process_state));
1732 return SendErrorResponse(0);
1735 GDBRemoteCommunication::PacketResult
1736 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1737 StringExtractorGDBRemote &packet) {
1738 // Fail if we don't have a current process.
1739 if (!m_debugged_process_sp ||
1740 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1741 return SendErrorResponse(68);
1743 // Ensure we have a thread.
1744 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1746 return SendErrorResponse(69);
1748 // Get the register context for the first thread.
1749 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1750 if (!reg_context_sp)
1751 return SendErrorResponse(69);
1753 // Parse out the register number from the request.
1754 packet.SetFilePos(strlen("qRegisterInfo"));
1755 const uint32_t reg_index =
1756 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1757 if (reg_index == std::numeric_limits<uint32_t>::max())
1758 return SendErrorResponse(69);
1760 // Return the end of registers response if we've iterated one past the end of
1761 // the register set.
1762 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1763 return SendErrorResponse(69);
1765 const RegisterInfo *reg_info =
1766 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1768 return SendErrorResponse(69);
1770 // Build the reginfos response.
1771 StreamGDBRemote response;
1773 response.PutCString("name:");
1774 response.PutCString(reg_info->name);
1775 response.PutChar(';');
1777 if (reg_info->alt_name && reg_info->alt_name[0]) {
1778 response.PutCString("alt-name:");
1779 response.PutCString(reg_info->alt_name);
1780 response.PutChar(';');
1783 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1784 reg_info->byte_size * 8, reg_info->byte_offset);
1786 switch (reg_info->encoding) {
1788 response.PutCString("encoding:uint;");
1791 response.PutCString("encoding:sint;");
1793 case eEncodingIEEE754:
1794 response.PutCString("encoding:ieee754;");
1796 case eEncodingVector:
1797 response.PutCString("encoding:vector;");
1803 switch (reg_info->format) {
1805 response.PutCString("format:binary;");
1807 case eFormatDecimal:
1808 response.PutCString("format:decimal;");
1811 response.PutCString("format:hex;");
1814 response.PutCString("format:float;");
1816 case eFormatVectorOfSInt8:
1817 response.PutCString("format:vector-sint8;");
1819 case eFormatVectorOfUInt8:
1820 response.PutCString("format:vector-uint8;");
1822 case eFormatVectorOfSInt16:
1823 response.PutCString("format:vector-sint16;");
1825 case eFormatVectorOfUInt16:
1826 response.PutCString("format:vector-uint16;");
1828 case eFormatVectorOfSInt32:
1829 response.PutCString("format:vector-sint32;");
1831 case eFormatVectorOfUInt32:
1832 response.PutCString("format:vector-uint32;");
1834 case eFormatVectorOfFloat32:
1835 response.PutCString("format:vector-float32;");
1837 case eFormatVectorOfUInt64:
1838 response.PutCString("format:vector-uint64;");
1840 case eFormatVectorOfUInt128:
1841 response.PutCString("format:vector-uint128;");
1847 const char *const register_set_name =
1848 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1849 if (register_set_name) {
1850 response.PutCString("set:");
1851 response.PutCString(register_set_name);
1852 response.PutChar(';');
1855 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1856 LLDB_INVALID_REGNUM)
1857 response.Printf("ehframe:%" PRIu32 ";",
1858 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1860 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1861 response.Printf("dwarf:%" PRIu32 ";",
1862 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1864 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1865 case LLDB_REGNUM_GENERIC_PC:
1866 response.PutCString("generic:pc;");
1868 case LLDB_REGNUM_GENERIC_SP:
1869 response.PutCString("generic:sp;");
1871 case LLDB_REGNUM_GENERIC_FP:
1872 response.PutCString("generic:fp;");
1874 case LLDB_REGNUM_GENERIC_RA:
1875 response.PutCString("generic:ra;");
1877 case LLDB_REGNUM_GENERIC_FLAGS:
1878 response.PutCString("generic:flags;");
1880 case LLDB_REGNUM_GENERIC_ARG1:
1881 response.PutCString("generic:arg1;");
1883 case LLDB_REGNUM_GENERIC_ARG2:
1884 response.PutCString("generic:arg2;");
1886 case LLDB_REGNUM_GENERIC_ARG3:
1887 response.PutCString("generic:arg3;");
1889 case LLDB_REGNUM_GENERIC_ARG4:
1890 response.PutCString("generic:arg4;");
1892 case LLDB_REGNUM_GENERIC_ARG5:
1893 response.PutCString("generic:arg5;");
1895 case LLDB_REGNUM_GENERIC_ARG6:
1896 response.PutCString("generic:arg6;");
1898 case LLDB_REGNUM_GENERIC_ARG7:
1899 response.PutCString("generic:arg7;");
1901 case LLDB_REGNUM_GENERIC_ARG8:
1902 response.PutCString("generic:arg8;");
1908 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1909 response.PutCString("container-regs:");
1911 for (const uint32_t *reg_num = reg_info->value_regs;
1912 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1914 response.PutChar(',');
1915 response.Printf("%" PRIx32, *reg_num);
1917 response.PutChar(';');
1920 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1921 response.PutCString("invalidate-regs:");
1923 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1924 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1926 response.PutChar(',');
1927 response.Printf("%" PRIx32, *reg_num);
1929 response.PutChar(';');
1932 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1933 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1934 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1935 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1936 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1937 response.PutChar(';');
1939 return SendPacketNoLock(response.GetString());
1942 GDBRemoteCommunication::PacketResult
1943 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1944 StringExtractorGDBRemote &packet) {
1945 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1947 // Fail if we don't have a current process.
1948 if (!m_debugged_process_sp ||
1949 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1951 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1954 m_debugged_process_sp ? "invalid process id"
1955 : "null m_debugged_process_sp");
1956 return SendOKResponse();
1959 StreamGDBRemote response;
1960 response.PutChar('m');
1964 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1967 NativeThreadProtocolSP thread_sp;
1968 uint32_t thread_index;
1969 for (thread_index = 0,
1970 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1971 thread_sp; ++thread_index,
1972 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1975 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1976 "(%s, tid=0x%" PRIx64 ")",
1977 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1978 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1979 if (thread_index > 0)
1980 response.PutChar(',');
1981 response.Printf("%" PRIx64, thread_sp->GetID());
1986 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1989 return SendPacketNoLock(response.GetString());
1992 GDBRemoteCommunication::PacketResult
1993 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1994 StringExtractorGDBRemote &packet) {
1995 // FIXME for now we return the full thread list in the initial packet and
1996 // always do nothing here.
1997 return SendPacketNoLock("l");
2000 GDBRemoteCommunication::PacketResult
2001 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2002 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2004 // Parse out the register number from the request.
2005 packet.SetFilePos(strlen("p"));
2006 const uint32_t reg_index =
2007 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2008 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2010 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2011 "parse register number from request \"%s\"",
2012 __FUNCTION__, packet.GetStringRef().c_str());
2013 return SendErrorResponse(0x15);
2016 // Get the thread to use.
2017 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2021 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2023 return SendErrorResponse(0x15);
2026 // Get the thread's register context.
2027 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2028 if (!reg_context_sp) {
2031 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2032 " failed, no register context available for the thread",
2033 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2034 return SendErrorResponse(0x15);
2037 // Return the end of registers response if we've iterated one past the end of
2038 // the register set.
2039 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2041 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2042 "register %" PRIu32 " beyond register count %" PRIu32,
2043 __FUNCTION__, reg_index,
2044 reg_context_sp->GetUserRegisterCount());
2045 return SendErrorResponse(0x15);
2048 const RegisterInfo *reg_info =
2049 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2052 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2053 "register %" PRIu32 " returned NULL",
2054 __FUNCTION__, reg_index);
2055 return SendErrorResponse(0x15);
2058 // Build the reginfos response.
2059 StreamGDBRemote response;
2061 // Retrieve the value
2062 RegisterValue reg_value;
2063 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
2066 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2067 "requested register %" PRIu32 " (%s) failed: %s",
2068 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2069 return SendErrorResponse(0x15);
2072 const uint8_t *const data =
2073 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2076 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2077 "bytes from requested register %" PRIu32,
2078 __FUNCTION__, reg_index);
2079 return SendErrorResponse(0x15);
2082 // FIXME flip as needed to get data in big/little endian format for this host.
2083 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2084 response.PutHex8(data[i]);
2086 return SendPacketNoLock(response.GetString());
2089 GDBRemoteCommunication::PacketResult
2090 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2091 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2093 // Ensure there is more content.
2094 if (packet.GetBytesLeft() < 1)
2095 return SendIllFormedResponse(packet, "Empty P packet");
2097 // Parse out the register number from the request.
2098 packet.SetFilePos(strlen("P"));
2099 const uint32_t reg_index =
2100 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2101 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2103 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2104 "parse register number from request \"%s\"",
2105 __FUNCTION__, packet.GetStringRef().c_str());
2106 return SendErrorResponse(0x29);
2109 // Note debugserver would send an E30 here.
2110 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2111 return SendIllFormedResponse(
2112 packet, "P packet missing '=' char after register number");
2114 // Get process architecture.
2115 ArchSpec process_arch;
2116 if (!m_debugged_process_sp ||
2117 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2119 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2120 "inferior architecture",
2122 return SendErrorResponse(0x49);
2125 // Parse out the value.
2126 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2127 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2129 // Get the thread to use.
2130 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2133 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2134 "available (thread index 0)",
2136 return SendErrorResponse(0x28);
2139 // Get the thread's register context.
2140 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2141 if (!reg_context_sp) {
2144 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2145 " failed, no register context available for the thread",
2146 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2147 return SendErrorResponse(0x15);
2150 const RegisterInfo *reg_info =
2151 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2154 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2155 "register %" PRIu32 " returned NULL",
2156 __FUNCTION__, reg_index);
2157 return SendErrorResponse(0x48);
2160 // Return the end of registers response if we've iterated one past the end of
2161 // the register set.
2162 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2164 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2165 "register %" PRIu32 " beyond register count %" PRIu32,
2166 __FUNCTION__, reg_index,
2167 reg_context_sp->GetUserRegisterCount());
2168 return SendErrorResponse(0x47);
2171 // The dwarf expression are evaluate on host site
2172 // which may cause register size to change
2173 // Hence the reg_size may not be same as reg_info->bytes_size
2174 if ((reg_size != reg_info->byte_size) &&
2175 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2176 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2179 // Build the reginfos response.
2180 StreamGDBRemote response;
2182 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
2183 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
2186 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2187 "requested register %" PRIu32 " (%s) failed: %s",
2188 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2189 return SendErrorResponse(0x32);
2192 return SendOKResponse();
2195 GDBRemoteCommunication::PacketResult
2196 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2197 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2199 // Fail if we don't have a current process.
2200 if (!m_debugged_process_sp ||
2201 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2204 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2206 return SendErrorResponse(0x15);
2209 // Parse out which variant of $H is requested.
2210 packet.SetFilePos(strlen("H"));
2211 if (packet.GetBytesLeft() < 1) {
2213 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2214 "missing {g,c} variant",
2216 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2219 const char h_variant = packet.GetChar();
2220 switch (h_variant) {
2230 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2231 __FUNCTION__, h_variant);
2232 return SendIllFormedResponse(packet,
2233 "H variant unsupported, should be c or g");
2236 // Parse out the thread number.
2237 // FIXME return a parse success/fail value. All values are valid here.
2238 const lldb::tid_t tid =
2239 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2241 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2243 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2244 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2247 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2250 return SendErrorResponse(0x15);
2254 // Now switch the given thread type.
2255 switch (h_variant) {
2257 SetCurrentThreadID(tid);
2261 SetContinueThreadID(tid);
2265 assert(false && "unsupported $H variant - shouldn't get here");
2266 return SendIllFormedResponse(packet,
2267 "H variant unsupported, should be c or g");
2270 return SendOKResponse();
2273 GDBRemoteCommunication::PacketResult
2274 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2275 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2277 // Fail if we don't have a current process.
2278 if (!m_debugged_process_sp ||
2279 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2282 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2284 return SendErrorResponse(0x15);
2287 packet.SetFilePos(::strlen("I"));
2290 size_t read = packet.GetHexBytesAvail(tmp);
2294 // write directly to stdin *this might block if stdin buffer is full*
2295 // TODO: enqueue this block in circular buffer and send window size to
2297 ConnectionStatus status;
2299 m_stdio_communication.Write(tmp, read, status, &error);
2301 return SendErrorResponse(0x15);
2305 return SendOKResponse();
2308 GDBRemoteCommunication::PacketResult
2309 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2310 StringExtractorGDBRemote &packet) {
2311 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2313 // Fail if we don't have a current process.
2314 if (!m_debugged_process_sp ||
2315 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2318 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2320 return SendErrorResponse(0x15);
2323 // Interrupt the process.
2324 Status error = m_debugged_process_sp->Interrupt();
2328 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2330 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
2332 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2336 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2337 __FUNCTION__, m_debugged_process_sp->GetID());
2339 // No response required from stop all.
2340 return PacketResult::Success;
2343 GDBRemoteCommunication::PacketResult
2344 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2345 StringExtractorGDBRemote &packet) {
2346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2348 if (!m_debugged_process_sp ||
2349 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2352 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2354 return SendErrorResponse(0x15);
2357 // Parse out the memory address.
2358 packet.SetFilePos(strlen("m"));
2359 if (packet.GetBytesLeft() < 1)
2360 return SendIllFormedResponse(packet, "Too short m packet");
2362 // Read the address. Punting on validation.
2363 // FIXME replace with Hex U64 read with no default value that fails on failed
2365 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2368 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2369 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2371 // Get # bytes to read.
2372 if (packet.GetBytesLeft() < 1)
2373 return SendIllFormedResponse(packet, "Length missing in m packet");
2375 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2376 if (byte_count == 0) {
2378 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2379 "zero-length packet",
2381 return SendOKResponse();
2384 // Allocate the response buffer.
2385 std::string buf(byte_count, '\0');
2387 return SendErrorResponse(0x78);
2389 // Retrieve the process memory.
2390 size_t bytes_read = 0;
2391 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2392 read_addr, &buf[0], byte_count, bytes_read);
2395 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2396 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2397 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2399 return SendErrorResponse(0x08);
2402 if (bytes_read == 0) {
2404 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2405 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2406 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2408 return SendErrorResponse(0x08);
2411 StreamGDBRemote response;
2412 packet.SetFilePos(0);
2413 char kind = packet.GetChar('?');
2415 response.PutEscapedBytes(buf.data(), byte_count);
2417 assert(kind == 'm');
2418 for (size_t i = 0; i < bytes_read; ++i)
2419 response.PutHex8(buf[i]);
2422 return SendPacketNoLock(response.GetString());
2425 GDBRemoteCommunication::PacketResult
2426 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2427 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2429 if (!m_debugged_process_sp ||
2430 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2433 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2435 return SendErrorResponse(0x15);
2438 // Parse out the memory address.
2439 packet.SetFilePos(strlen("M"));
2440 if (packet.GetBytesLeft() < 1)
2441 return SendIllFormedResponse(packet, "Too short M packet");
2443 // Read the address. Punting on validation.
2444 // FIXME replace with Hex U64 read with no default value that fails on failed
2446 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2449 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2450 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2452 // Get # bytes to read.
2453 if (packet.GetBytesLeft() < 1)
2454 return SendIllFormedResponse(packet, "Length missing in M packet");
2456 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2457 if (byte_count == 0) {
2459 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2460 "zero-length packet",
2462 return PacketResult::Success;
2466 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2467 return SendIllFormedResponse(
2468 packet, "Comma sep missing in M packet after byte length");
2470 // Allocate the conversion buffer.
2471 std::vector<uint8_t> buf(byte_count, 0);
2473 return SendErrorResponse(0x78);
2475 // Convert the hex memory write contents to bytes.
2476 StreamGDBRemote response;
2477 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2478 if (convert_count != byte_count) {
2480 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2481 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2482 " bytes, but only found %" PRIu64 " to convert.",
2483 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2484 byte_count, convert_count);
2485 return SendIllFormedResponse(packet, "M content byte length specified did "
2486 "not match hex-encoded content "
2490 // Write the process memory.
2491 size_t bytes_written = 0;
2492 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2493 byte_count, bytes_written);
2496 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2497 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2498 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2500 return SendErrorResponse(0x09);
2503 if (bytes_written == 0) {
2505 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2506 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2507 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2509 return SendErrorResponse(0x09);
2512 return SendOKResponse();
2515 GDBRemoteCommunication::PacketResult
2516 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2517 StringExtractorGDBRemote &packet) {
2518 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2520 // Currently only the NativeProcessProtocol knows if it can handle a
2521 // qMemoryRegionInfoSupported
2522 // request, but we're not guaranteed to be attached to a process. For now
2524 // client only asks this when a process is being debugged.
2526 // Ensure we have a process running; otherwise, we can't figure this out
2527 // since we won't have a NativeProcessProtocol.
2528 if (!m_debugged_process_sp ||
2529 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2532 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2534 return SendErrorResponse(0x15);
2537 // Test if we can get any region back when asking for the region around NULL.
2538 MemoryRegionInfo region_info;
2539 const Status error =
2540 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2542 // We don't support memory region info collection for this
2543 // NativeProcessProtocol.
2544 return SendUnimplementedResponse("");
2547 return SendOKResponse();
2550 GDBRemoteCommunication::PacketResult
2551 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2552 StringExtractorGDBRemote &packet) {
2553 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2555 // Ensure we have a process.
2556 if (!m_debugged_process_sp ||
2557 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2560 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2562 return SendErrorResponse(0x15);
2565 // Parse out the memory address.
2566 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2567 if (packet.GetBytesLeft() < 1)
2568 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2570 // Read the address. Punting on validation.
2571 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2573 StreamGDBRemote response;
2575 // Get the memory region info for the target address.
2576 MemoryRegionInfo region_info;
2577 const Status error =
2578 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2580 // Return the error message.
2582 response.PutCString("error:");
2583 response.PutCStringAsRawHex8(error.AsCString());
2584 response.PutChar(';');
2586 // Range start and size.
2587 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2588 region_info.GetRange().GetRangeBase(),
2589 region_info.GetRange().GetByteSize());
2592 if (region_info.GetReadable() || region_info.GetWritable() ||
2593 region_info.GetExecutable()) {
2594 // Write permissions info.
2595 response.PutCString("permissions:");
2597 if (region_info.GetReadable())
2598 response.PutChar('r');
2599 if (region_info.GetWritable())
2600 response.PutChar('w');
2601 if (region_info.GetExecutable())
2602 response.PutChar('x');
2604 response.PutChar(';');
2608 ConstString name = region_info.GetName();
2610 response.PutCString("name:");
2611 response.PutCStringAsRawHex8(name.AsCString());
2612 response.PutChar(';');
2616 return SendPacketNoLock(response.GetString());
2619 GDBRemoteCommunication::PacketResult
2620 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2621 // Ensure we have a process.
2622 if (!m_debugged_process_sp ||
2623 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2624 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2627 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2629 return SendErrorResponse(0x15);
2632 // Parse out software or hardware breakpoint or watchpoint requested.
2633 packet.SetFilePos(strlen("Z"));
2634 if (packet.GetBytesLeft() < 1)
2635 return SendIllFormedResponse(
2636 packet, "Too short Z packet, missing software/hardware specifier");
2638 bool want_breakpoint = true;
2639 bool want_hardware = false;
2640 uint32_t watch_flags = 0;
2642 const GDBStoppointType stoppoint_type =
2643 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2644 switch (stoppoint_type) {
2645 case eBreakpointSoftware:
2646 want_hardware = false;
2647 want_breakpoint = true;
2649 case eBreakpointHardware:
2650 want_hardware = true;
2651 want_breakpoint = true;
2653 case eWatchpointWrite:
2655 want_hardware = true;
2656 want_breakpoint = false;
2658 case eWatchpointRead:
2660 want_hardware = true;
2661 want_breakpoint = false;
2663 case eWatchpointReadWrite:
2665 want_hardware = true;
2666 want_breakpoint = false;
2668 case eStoppointInvalid:
2669 return SendIllFormedResponse(
2670 packet, "Z packet had invalid software/hardware specifier");
2673 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2674 return SendIllFormedResponse(
2675 packet, "Malformed Z packet, expecting comma after stoppoint type");
2677 // Parse out the stoppoint address.
2678 if (packet.GetBytesLeft() < 1)
2679 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2680 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2682 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2683 return SendIllFormedResponse(
2684 packet, "Malformed Z packet, expecting comma after address");
2686 // Parse out the stoppoint size (i.e. size hint for opcode size).
2687 const uint32_t size =
2688 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2689 if (size == std::numeric_limits<uint32_t>::max())
2690 return SendIllFormedResponse(
2691 packet, "Malformed Z packet, failed to parse size argument");
2693 if (want_breakpoint) {
2694 // Try to set the breakpoint.
2695 const Status error =
2696 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2697 if (error.Success())
2698 return SendOKResponse();
2699 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2701 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2702 " failed to set breakpoint: %s",
2703 __FUNCTION__, m_debugged_process_sp->GetID(),
2705 return SendErrorResponse(0x09);
2707 // Try to set the watchpoint.
2708 const Status error = m_debugged_process_sp->SetWatchpoint(
2709 addr, size, watch_flags, want_hardware);
2710 if (error.Success())
2711 return SendOKResponse();
2712 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2714 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2715 " failed to set watchpoint: %s",
2716 __FUNCTION__, m_debugged_process_sp->GetID(),
2718 return SendErrorResponse(0x09);
2722 GDBRemoteCommunication::PacketResult
2723 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2724 // Ensure we have a process.
2725 if (!m_debugged_process_sp ||
2726 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2727 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2730 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2732 return SendErrorResponse(0x15);
2735 // Parse out software or hardware breakpoint or watchpoint requested.
2736 packet.SetFilePos(strlen("z"));
2737 if (packet.GetBytesLeft() < 1)
2738 return SendIllFormedResponse(
2739 packet, "Too short z packet, missing software/hardware specifier");
2741 bool want_breakpoint = true;
2742 bool want_hardware = false;
2744 const GDBStoppointType stoppoint_type =
2745 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2746 switch (stoppoint_type) {
2747 case eBreakpointHardware:
2748 want_breakpoint = true;
2749 want_hardware = true;
2751 case eBreakpointSoftware:
2752 want_breakpoint = true;
2754 case eWatchpointWrite:
2755 want_breakpoint = false;
2757 case eWatchpointRead:
2758 want_breakpoint = false;
2760 case eWatchpointReadWrite:
2761 want_breakpoint = false;
2764 return SendIllFormedResponse(
2765 packet, "z packet had invalid software/hardware specifier");
2768 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2769 return SendIllFormedResponse(
2770 packet, "Malformed z packet, expecting comma after stoppoint type");
2772 // Parse out the stoppoint address.
2773 if (packet.GetBytesLeft() < 1)
2774 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2775 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2777 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2778 return SendIllFormedResponse(
2779 packet, "Malformed z packet, expecting comma after address");
2782 // Parse out the stoppoint size (i.e. size hint for opcode size).
2783 const uint32_t size = packet.GetHexMaxU32 (false,
2784 std::numeric_limits<uint32_t>::max ());
2785 if (size == std::numeric_limits<uint32_t>::max ())
2786 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2790 if (want_breakpoint) {
2791 // Try to clear the breakpoint.
2792 const Status error =
2793 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
2794 if (error.Success())
2795 return SendOKResponse();
2796 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2798 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2799 " failed to remove breakpoint: %s",
2800 __FUNCTION__, m_debugged_process_sp->GetID(),
2802 return SendErrorResponse(0x09);
2804 // Try to clear the watchpoint.
2805 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
2806 if (error.Success())
2807 return SendOKResponse();
2808 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2810 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2811 " failed to remove watchpoint: %s",
2812 __FUNCTION__, m_debugged_process_sp->GetID(),
2814 return SendErrorResponse(0x09);
2818 GDBRemoteCommunication::PacketResult
2819 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2820 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2822 // Ensure we have a process.
2823 if (!m_debugged_process_sp ||
2824 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2827 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2829 return SendErrorResponse(0x32);
2832 // We first try to use a continue thread id. If any one or any all set, use
2833 // the current thread.
2834 // Bail out if we don't have a thread id.
2835 lldb::tid_t tid = GetContinueThreadID();
2836 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2837 tid = GetCurrentThreadID();
2838 if (tid == LLDB_INVALID_THREAD_ID)
2839 return SendErrorResponse(0x33);
2841 // Double check that we have such a thread.
2842 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2843 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2844 if (!thread_sp || thread_sp->GetID() != tid)
2845 return SendErrorResponse(0x33);
2847 // Create the step action for the given thread.
2848 ResumeAction action = {tid, eStateStepping, 0};
2850 // Setup the actions list.
2851 ResumeActionList actions;
2852 actions.Append(action);
2854 // All other threads stop while we're single stepping a thread.
2855 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2856 Status error = m_debugged_process_sp->Resume(actions);
2859 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2860 " tid %" PRIu64 " Resume() failed with error: %s",
2861 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2863 return SendErrorResponse(0x49);
2866 // No response here - the stop or exit will come from the resulting action.
2867 return PacketResult::Success;
2870 GDBRemoteCommunication::PacketResult
2871 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2872 StringExtractorGDBRemote &packet) {
2873 // *BSD impls should be able to do this too.
2874 #if defined(__linux__) || defined(__NetBSD__)
2875 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2877 // Parse out the offset.
2878 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2879 if (packet.GetBytesLeft() < 1)
2880 return SendIllFormedResponse(packet,
2881 "qXfer:auxv:read:: packet missing offset");
2883 const uint64_t auxv_offset =
2884 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2885 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2886 return SendIllFormedResponse(packet,
2887 "qXfer:auxv:read:: packet missing offset");
2890 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2891 return SendIllFormedResponse(
2892 packet, "qXfer:auxv:read:: packet missing comma after offset");
2894 // Parse out the length.
2895 const uint64_t auxv_length =
2896 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2897 if (auxv_length == std::numeric_limits<uint64_t>::max())
2898 return SendIllFormedResponse(packet,
2899 "qXfer:auxv:read:: packet missing length");
2901 // Grab the auxv data if we need it.
2902 if (!m_active_auxv_buffer_up) {
2903 // Make sure we have a valid process.
2904 if (!m_debugged_process_sp ||
2905 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2908 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2910 return SendErrorResponse(0x10);
2913 // Grab the auxv data.
2914 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2915 if (!buffer_or_error) {
2916 std::error_code ec = buffer_or_error.getError();
2917 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2918 return SendErrorResponse(ec.value());
2920 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2923 StreamGDBRemote response;
2924 bool done_with_buffer = false;
2926 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2927 if (auxv_offset >= buffer.size()) {
2928 // We have nothing left to send. Mark the buffer as complete.
2929 response.PutChar('l');
2930 done_with_buffer = true;
2932 // Figure out how many bytes are available starting at the given offset.
2933 buffer = buffer.drop_front(auxv_offset);
2935 // Mark the response type according to whether we're reading the remainder
2936 // of the auxv data.
2937 if (auxv_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(auxv_length);
2947 // Now write the data in encoded binary form.
2948 response.PutEscapedBytes(buffer.data(), buffer.size());
2951 if (done_with_buffer)
2952 m_active_auxv_buffer_up.reset();
2954 return SendPacketNoLock(response.GetString());
2956 return SendUnimplementedResponse("not implemented on this platform");
2960 GDBRemoteCommunication::PacketResult
2961 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2962 StringExtractorGDBRemote &packet) {
2963 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2965 // Move past packet name.
2966 packet.SetFilePos(strlen("QSaveRegisterState"));
2968 // Get the thread to use.
2969 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2971 if (m_thread_suffix_supported)
2972 return SendIllFormedResponse(
2973 packet, "No thread specified in QSaveRegisterState packet");
2975 return SendIllFormedResponse(packet,
2976 "No thread was is set with the Hg packet");
2979 // Grab the register context for the thread.
2980 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2981 if (!reg_context_sp) {
2984 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2985 " failed, no register context available for the thread",
2986 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2987 return SendErrorResponse(0x15);
2990 // Save registers to a buffer.
2991 DataBufferSP register_data_sp;
2992 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
2995 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2996 " failed to save all register values: %s",
2997 __FUNCTION__, m_debugged_process_sp->GetID(),
2999 return SendErrorResponse(0x75);
3002 // Allocate a new save id.
3003 const uint32_t save_id = GetNextSavedRegistersID();
3004 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3005 "GetNextRegisterSaveID() returned an existing register save id");
3007 // Save the register data buffer under the save id.
3009 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3010 m_saved_registers_map[save_id] = register_data_sp;
3013 // Write the response.
3014 StreamGDBRemote response;
3015 response.Printf("%" PRIu32, save_id);
3016 return SendPacketNoLock(response.GetString());
3019 GDBRemoteCommunication::PacketResult
3020 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3021 StringExtractorGDBRemote &packet) {
3022 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3024 // Parse out save id.
3025 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3026 if (packet.GetBytesLeft() < 1)
3027 return SendIllFormedResponse(
3028 packet, "QRestoreRegisterState packet missing register save id");
3030 const uint32_t save_id = packet.GetU32(0);
3033 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3034 "packet has malformed save id, expecting decimal uint32_t",
3036 return SendErrorResponse(0x76);
3039 // Get the thread to use.
3040 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3042 if (m_thread_suffix_supported)
3043 return SendIllFormedResponse(
3044 packet, "No thread specified in QRestoreRegisterState packet");
3046 return SendIllFormedResponse(packet,
3047 "No thread was is set with the Hg packet");
3050 // Grab the register context for the thread.
3051 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3052 if (!reg_context_sp) {
3055 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3056 " failed, no register context available for the thread",
3057 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3058 return SendErrorResponse(0x15);
3061 // Retrieve register state buffer, then remove from the list.
3062 DataBufferSP register_data_sp;
3064 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3066 // Find the register set buffer for the given save id.
3067 auto it = m_saved_registers_map.find(save_id);
3068 if (it == m_saved_registers_map.end()) {
3070 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3071 " does not have a register set save buffer for id %" PRIu32,
3072 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3073 return SendErrorResponse(0x77);
3075 register_data_sp = it->second;
3077 // Remove it from the map.
3078 m_saved_registers_map.erase(it);
3081 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
3084 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3085 " failed to restore all register values: %s",
3086 __FUNCTION__, m_debugged_process_sp->GetID(),
3088 return SendErrorResponse(0x77);
3091 return SendOKResponse();
3094 GDBRemoteCommunication::PacketResult
3095 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3096 StringExtractorGDBRemote &packet) {
3097 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3099 // Consume the ';' after vAttach.
3100 packet.SetFilePos(strlen("vAttach"));
3101 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3102 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3104 // Grab the PID to which we will attach (assume hex encoding).
3105 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3106 if (pid == LLDB_INVALID_PROCESS_ID)
3107 return SendIllFormedResponse(packet,
3108 "vAttach failed to parse the process id");
3110 // Attempt to attach.
3112 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3116 Status error = AttachToProcess(pid);
3120 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3121 "pid %" PRIu64 ": %s\n",
3122 __FUNCTION__, pid, error.AsCString());
3123 return SendErrorResponse(0x01);
3126 // Notify we attached by sending a stop packet.
3127 return SendStopReasonForState(m_debugged_process_sp->GetState());
3130 GDBRemoteCommunication::PacketResult
3131 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3132 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3134 StopSTDIOForwarding();
3136 // Fail if we don't have a current process.
3137 if (!m_debugged_process_sp ||
3138 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3141 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3143 return SendErrorResponse(0x15);
3146 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3148 // Consume the ';' after D.
3149 packet.SetFilePos(1);
3150 if (packet.GetBytesLeft()) {
3151 if (packet.GetChar() != ';')
3152 return SendIllFormedResponse(packet, "D missing expected ';'");
3154 // Grab the PID from which we will detach (assume hex encoding).
3155 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3156 if (pid == LLDB_INVALID_PROCESS_ID)
3157 return SendIllFormedResponse(packet, "D failed to parse the process id");
3160 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3161 return SendIllFormedResponse(packet, "Invalid pid");
3164 const Status error = m_debugged_process_sp->Detach();
3167 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3168 "pid %" PRIu64 ": %s\n",
3169 __FUNCTION__, m_debugged_process_sp->GetID(),
3171 return SendErrorResponse(0x01);
3174 return SendOKResponse();
3177 GDBRemoteCommunication::PacketResult
3178 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3179 StringExtractorGDBRemote &packet) {
3180 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3182 packet.SetFilePos(strlen("qThreadStopInfo"));
3183 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3184 if (tid == LLDB_INVALID_THREAD_ID) {
3186 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3187 "parse thread id from request \"%s\"",
3188 __FUNCTION__, packet.GetStringRef().c_str());
3189 return SendErrorResponse(0x15);
3191 return SendStopReplyPacketForThread(tid);
3194 GDBRemoteCommunication::PacketResult
3195 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3196 StringExtractorGDBRemote &) {
3197 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3199 // Ensure we have a debugged process.
3200 if (!m_debugged_process_sp ||
3201 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3202 return SendErrorResponse(50);
3205 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3207 __FUNCTION__, m_debugged_process_sp->GetID());
3209 StreamString response;
3210 const bool threads_with_valid_stop_info_only = false;
3211 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3212 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3213 if (!threads_array_sp) {
3215 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3216 "packet for pid %" PRIu64,
3217 __FUNCTION__, m_debugged_process_sp->GetID());
3218 return SendErrorResponse(52);
3221 threads_array_sp->Write(response);
3222 StreamGDBRemote escaped_response;
3223 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3224 return SendPacketNoLock(escaped_response.GetString());
3227 GDBRemoteCommunication::PacketResult
3228 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3229 StringExtractorGDBRemote &packet) {
3230 // Fail if we don't have a current process.
3231 if (!m_debugged_process_sp ||
3232 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3233 return SendErrorResponse(68);
3235 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3236 if (packet.GetBytesLeft() == 0)
3237 return SendOKResponse();
3238 if (packet.GetChar() != ':')
3239 return SendErrorResponse(67);
3241 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3243 StreamGDBRemote response;
3244 if (hw_debug_cap == llvm::None)
3245 response.Printf("num:0;");
3247 response.Printf("num:%d;", hw_debug_cap->second);
3249 return SendPacketNoLock(response.GetString());
3252 GDBRemoteCommunication::PacketResult
3253 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3254 StringExtractorGDBRemote &packet) {
3255 // Fail if we don't have a current process.
3256 if (!m_debugged_process_sp ||
3257 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3258 return SendErrorResponse(67);
3260 packet.SetFilePos(strlen("qFileLoadAddress:"));
3261 if (packet.GetBytesLeft() == 0)
3262 return SendErrorResponse(68);
3264 std::string file_name;
3265 packet.GetHexByteString(file_name);
3267 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3269 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3271 return SendErrorResponse(69);
3273 if (file_load_address == LLDB_INVALID_ADDRESS)
3274 return SendErrorResponse(1); // File not loaded
3276 StreamGDBRemote response;
3277 response.PutHex64(file_load_address);
3278 return SendPacketNoLock(response.GetString());
3281 GDBRemoteCommunication::PacketResult
3282 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3283 StringExtractorGDBRemote &packet) {
3284 std::vector<int> signals;
3285 packet.SetFilePos(strlen("QPassSignals:"));
3287 // Read sequence of hex signal numbers divided by a semicolon and
3288 // optionally spaces.
3289 while (packet.GetBytesLeft() > 0) {
3290 int signal = packet.GetS32(-1, 16);
3292 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3293 signals.push_back(signal);
3295 packet.SkipSpaces();
3296 char separator = packet.GetChar();
3297 if (separator == '\0')
3298 break; // End of string
3299 if (separator != ';')
3300 return SendIllFormedResponse(packet, "Invalid separator,"
3301 " expected semicolon.");
3304 // Fail if we don't have a current process.
3305 if (!m_debugged_process_sp)
3306 return SendErrorResponse(68);
3308 Status error = m_debugged_process_sp->IgnoreSignals(signals);
3310 return SendErrorResponse(69);
3312 return SendOKResponse();
3315 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3316 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3318 // Tell the stdio connection to shut down.
3319 if (m_stdio_communication.IsConnected()) {
3320 auto connection = m_stdio_communication.GetConnection();
3323 connection->Disconnect(&error);
3325 if (error.Success()) {
3327 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3328 "terminal stdio - SUCCESS",
3332 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3333 "terminal stdio - FAIL: %s",
3334 __FUNCTION__, error.AsCString());
3340 NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3341 StringExtractorGDBRemote &packet) {
3342 NativeThreadProtocolSP thread_sp;
3344 // We have no thread if we don't have a process.
3345 if (!m_debugged_process_sp ||
3346 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3349 // If the client hasn't asked for thread suffix support, there will not be a
3351 // Use the current thread in that case.
3352 if (!m_thread_suffix_supported) {
3353 const lldb::tid_t current_tid = GetCurrentThreadID();
3354 if (current_tid == LLDB_INVALID_THREAD_ID)
3356 else if (current_tid == 0) {
3358 return m_debugged_process_sp->GetThreadAtIndex(0);
3360 return m_debugged_process_sp->GetThreadByID(current_tid);
3363 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3365 // Parse out the ';'.
3366 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3368 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3369 "error: expected ';' prior to start of thread suffix: packet "
3371 __FUNCTION__, packet.GetStringRef().c_str());
3375 if (!packet.GetBytesLeft())
3378 // Parse out thread: portion.
3379 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3381 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3382 "error: expected 'thread:' but not found, packet contents = "
3384 __FUNCTION__, packet.GetStringRef().c_str());
3387 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3388 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3390 return m_debugged_process_sp->GetThreadByID(tid);
3395 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3396 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3397 // Use whatever the debug process says is the current thread id
3398 // since the protocol either didn't specify or specified we want
3399 // any/all threads marked as the current thread.
3400 if (!m_debugged_process_sp)
3401 return LLDB_INVALID_THREAD_ID;
3402 return m_debugged_process_sp->GetCurrentThreadID();
3404 // Use the specific current thread id set by the gdb remote protocol.
3405 return m_current_tid;
3408 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3409 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3410 return m_next_saved_registers_id++;
3413 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3414 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3416 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3417 m_active_auxv_buffer_up.reset();
3421 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3422 const ArchSpec &arch) {
3423 if (m_debugged_process_sp) {
3425 if (m_debugged_process_sp
3426 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3428 if (file_spec.Exists())
3433 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);