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(
77 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
79 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
80 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
81 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
82 m_inferior_prev_state(StateType::eStateInvalid),
83 m_saved_registers_map(), m_next_saved_registers_id(1),
84 m_handshake_completed(false) {
85 RegisterPacketHandlers();
88 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
90 &GDBRemoteCommunicationServerLLGS::Handle_C);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
92 &GDBRemoteCommunicationServerLLGS::Handle_c);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
94 &GDBRemoteCommunicationServerLLGS::Handle_D);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
96 &GDBRemoteCommunicationServerLLGS::Handle_H);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
98 &GDBRemoteCommunicationServerLLGS::Handle_I);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_interrupt,
101 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
102 RegisterMemberFunctionHandler(
103 StringExtractorGDBRemote::eServerPacketType_m,
104 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
106 &GDBRemoteCommunicationServerLLGS::Handle_M);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
108 &GDBRemoteCommunicationServerLLGS::Handle_p);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
110 &GDBRemoteCommunicationServerLLGS::Handle_P);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
112 &GDBRemoteCommunicationServerLLGS::Handle_qC);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
115 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
118 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
121 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
157 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
158 RegisterMemberFunctionHandler(
159 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
160 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
162 &GDBRemoteCommunicationServerLLGS::Handle_s);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_stop_reason,
165 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vAttach,
168 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
174 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_x,
177 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
178 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
179 &GDBRemoteCommunicationServerLLGS::Handle_Z);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
181 &GDBRemoteCommunicationServerLLGS::Handle_z);
182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
184 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
186 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
187 [this](StringExtractorGDBRemote packet, Error &error,
188 bool &interrupt, bool &quit) {
190 return this->Handle_k(packet);
194 Error GDBRemoteCommunicationServerLLGS::SetLaunchArguments(
195 const char *const args[], int argc) {
196 if ((argc < 1) || !args || !args[0] || !args[0][0])
197 return Error("%s: no process command line specified to launch",
200 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
204 Error GDBRemoteCommunicationServerLLGS::SetLaunchFlags(
205 unsigned int launch_flags) {
206 m_process_launch_info.GetFlags().Set(launch_flags);
210 Error GDBRemoteCommunicationServerLLGS::LaunchProcess() {
211 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
213 if (!m_process_launch_info.GetArguments().GetArgumentCount())
214 return Error("%s: no process command line specified to launch",
217 const bool should_forward_stdio =
218 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
219 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
220 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
221 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
222 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
224 const bool default_to_use_pty = true;
225 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
229 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
230 assert(!m_debugged_process_sp && "lldb-server creating debugged "
231 "process but one already exists");
232 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
233 m_mainloop, m_debugged_process_sp);
236 if (!error.Success()) {
237 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
238 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
242 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
244 // llgs local-process debugging may specify PTY paths, which will make these
245 // file actions non-null
246 // process launch -i/e/o will also make these file actions non-null
247 // nullptr means that the traffic is expected to flow over gdb-remote protocol
248 if (should_forward_stdio) {
249 // nullptr means it's not redirected to file or pty (in case of LLGS local)
250 // at least one of stdio will be transferred pty<->gdb-remote
251 // we need to give the pty master handle to this object to read and/or write
254 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
255 " setting up stdout/stderr redirection via $O gdb-remote commands",
256 __FUNCTION__, m_debugged_process_sp->GetID());
258 // Setup stdout/stderr mapping from inferior to $O
259 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
260 if (terminal_fd >= 0) {
262 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
263 "inferior STDIO fd to %d",
264 __FUNCTION__, terminal_fd);
265 error = SetSTDIOFileDescriptor(terminal_fd);
270 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
271 "inferior STDIO since terminal fd reported as %d",
272 __FUNCTION__, terminal_fd);
276 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
277 " skipping stdout/stderr redirection via $O: inferior will "
278 "communicate over client-provided file descriptors",
279 __FUNCTION__, m_debugged_process_sp->GetID());
282 printf("Launched '%s' as process %" PRIu64 "...\n",
283 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
284 m_process_launch_info.GetProcessID());
289 Error GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
292 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
294 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
297 // Before we try to attach, make sure we aren't already monitoring something
299 if (m_debugged_process_sp &&
300 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
301 return Error("cannot attach to a process %" PRIu64
302 " when another process with pid %" PRIu64
303 " is being debugged.",
304 pid, m_debugged_process_sp->GetID());
307 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
308 m_debugged_process_sp);
309 if (!error.Success()) {
310 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
311 __FUNCTION__, pid, error.AsCString());
315 // Setup stdout/stderr mapping from inferior.
316 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
317 if (terminal_fd >= 0) {
319 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
320 "inferior STDIO fd to %d",
321 __FUNCTION__, terminal_fd);
322 error = SetSTDIOFileDescriptor(terminal_fd);
327 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
328 "inferior STDIO since terminal fd reported as %d",
329 __FUNCTION__, terminal_fd);
332 printf("Attached to process %" PRIu64 "...\n", pid);
337 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
338 NativeProcessProtocol *process) {
339 assert(process && "process cannot be NULL");
340 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
342 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
343 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
344 __FUNCTION__, process->GetID(),
345 StateAsCString(process->GetState()));
349 GDBRemoteCommunication::PacketResult
350 GDBRemoteCommunicationServerLLGS::SendWResponse(
351 NativeProcessProtocol *process) {
352 assert(process && "process cannot be NULL");
353 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
355 // send W notification
356 ExitType exit_type = ExitType::eExitTypeInvalid;
358 std::string exit_description;
360 const bool got_exit_info =
361 process->GetExitStatus(&exit_type, &return_code, exit_description);
362 if (!got_exit_info) {
364 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
365 ", failed to retrieve process exit status",
366 __FUNCTION__, process->GetID());
368 StreamGDBRemote response;
369 response.PutChar('E');
370 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
371 return SendPacketNoLock(response.GetString());
374 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
375 ", returning exit type %d, return code %d [%s]",
376 __FUNCTION__, process->GetID(), exit_type, return_code,
377 exit_description.c_str());
379 StreamGDBRemote response;
381 char return_type_code;
383 case ExitType::eExitTypeExit:
384 return_type_code = 'W';
386 case ExitType::eExitTypeSignal:
387 return_type_code = 'X';
389 case ExitType::eExitTypeStop:
390 return_type_code = 'S';
392 case ExitType::eExitTypeInvalid:
393 return_type_code = 'E';
396 response.PutChar(return_type_code);
398 // POSIX exit status limited to unsigned 8 bits.
399 response.PutHex8(return_code);
401 return SendPacketNoLock(response.GetString());
405 static void AppendHexValue(StreamString &response, const uint8_t *buf,
406 uint32_t buf_size, bool swap) {
409 for (i = buf_size - 1; i >= 0; i--)
410 response.PutHex8(buf[i]);
412 for (i = 0; i < buf_size; i++)
413 response.PutHex8(buf[i]);
417 static void WriteRegisterValueInHexFixedWidth(
418 StreamString &response, NativeRegisterContextSP ®_ctx_sp,
419 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
420 lldb::ByteOrder byte_order) {
421 RegisterValue reg_value;
423 Error error = reg_ctx_sp->ReadRegister(®_info, reg_value);
425 reg_value_p = ®_value;
430 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
431 reg_value_p->GetByteSize(),
432 byte_order == lldb::eByteOrderLittle);
434 // Zero-out any unreadable values.
435 if (reg_info.byte_size > 0) {
436 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
437 AppendHexValue(response, zeros.data(), zeros.size(), false);
442 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
443 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
445 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
449 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
451 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
452 // Expedite all registers in the first register set (i.e. should be GPRs) that
453 // are not contained in other registers.
454 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
457 for (const uint32_t *reg_num_p = reg_set_p->registers;
458 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
459 uint32_t reg_num = *reg_num_p;
461 // Expedite only a couple of registers until we figure out why sending
464 static const uint32_t k_expedited_registers[] = {
465 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
466 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
468 for (const uint32_t *generic_reg_p = k_expedited_registers;
469 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
470 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
471 eRegisterKindGeneric, *generic_reg_p);
472 if (reg_num == LLDB_INVALID_REGNUM)
473 continue; // Target does not support the given register.
476 const RegisterInfo *const reg_info_p =
477 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
478 if (reg_info_p == nullptr) {
481 "%s failed to get register info for register index %" PRIu32,
482 __FUNCTION__, reg_num);
486 if (reg_info_p->value_regs != nullptr)
487 continue; // Only expedite registers that are not contained in other
490 RegisterValue reg_value;
491 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
494 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
496 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
497 reg_num, error.AsCString());
502 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
503 ®_value, lldb::eByteOrderBig);
505 register_object_sp->SetObject(
506 llvm::to_string(reg_num),
507 std::make_shared<JSONString>(stream.GetString()));
510 return register_object_sp;
513 static const char *GetStopReasonString(StopReason stop_reason) {
514 switch (stop_reason) {
515 case eStopReasonTrace:
517 case eStopReasonBreakpoint:
519 case eStopReasonWatchpoint:
521 case eStopReasonSignal:
523 case eStopReasonException:
525 case eStopReasonExec:
527 case eStopReasonInstrumentation:
528 case eStopReasonInvalid:
529 case eStopReasonPlanComplete:
530 case eStopReasonThreadExiting:
531 case eStopReasonNone:
537 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
539 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
541 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
543 // Ensure we can get info on the given thread.
544 uint32_t thread_idx = 0;
545 for (NativeThreadProtocolSP thread_sp;
546 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
549 lldb::tid_t tid = thread_sp->GetID();
551 // Grab the reason this thread stopped.
552 struct ThreadStopInfo tid_stop_info;
553 std::string description;
554 if (!thread_sp->GetStopReason(tid_stop_info, description))
557 const int signum = tid_stop_info.details.signal.signo;
559 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
561 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
562 __FUNCTION__, process.GetID(), tid, signum,
563 tid_stop_info.reason, tid_stop_info.details.exception.type);
566 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
567 threads_array_sp->AppendObject(thread_obj_sp);
570 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
571 thread_obj_sp->SetObject("registers", registers_sp);
574 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
576 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
578 const std::string thread_name = thread_sp->GetName();
579 if (!thread_name.empty())
580 thread_obj_sp->SetObject("name",
581 std::make_shared<JSONString>(thread_name));
583 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
584 thread_obj_sp->SetObject("reason",
585 std::make_shared<JSONString>(stop_reason_str));
587 if (!description.empty())
588 thread_obj_sp->SetObject("description",
589 std::make_shared<JSONString>(description));
591 if ((tid_stop_info.reason == eStopReasonException) &&
592 tid_stop_info.details.exception.type) {
593 thread_obj_sp->SetObject(
595 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
597 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
598 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
600 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
601 tid_stop_info.details.exception.data[i]));
603 thread_obj_sp->SetObject("medata", medata_array_sp);
606 // TODO: Expedite interesting regions of inferior memory
609 return threads_array_sp;
612 GDBRemoteCommunication::PacketResult
613 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
615 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
617 // Ensure we have a debugged process.
618 if (!m_debugged_process_sp ||
619 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
620 return SendErrorResponse(50);
624 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
626 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
628 // Ensure we can get info on the given thread.
629 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
631 return SendErrorResponse(51);
633 // Grab the reason this thread stopped.
634 struct ThreadStopInfo tid_stop_info;
635 std::string description;
636 if (!thread_sp->GetStopReason(tid_stop_info, description))
637 return SendErrorResponse(52);
639 // FIXME implement register handling for exec'd inferiors.
640 // if (tid_stop_info.reason == eStopReasonExec)
642 // const bool force = true;
643 // InitializeRegisters(force);
646 StreamString response;
647 // Output the T packet with the thread
648 response.PutChar('T');
649 int signum = tid_stop_info.details.signal.signo;
651 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
653 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
654 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
655 tid_stop_info.reason, tid_stop_info.details.exception.type);
658 // Print the signal number.
659 response.PutHex8(signum & 0xff);
662 response.Printf("thread:%" PRIx64 ";", tid);
664 // Include the thread name if there is one.
665 const std::string thread_name = thread_sp->GetName();
666 if (!thread_name.empty()) {
667 size_t thread_name_len = thread_name.length();
669 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
670 response.PutCString("name:");
671 response.PutCString(thread_name);
673 // The thread name contains special chars, send as hex bytes.
674 response.PutCString("hexname:");
675 response.PutCStringAsRawHex8(thread_name.c_str());
677 response.PutChar(';');
680 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
681 // will send all thread IDs back in the "threads" key whose value is
682 // a list of hex thread IDs separated by commas:
683 // "threads:10a,10b,10c;"
684 // This will save the debugger from having to send a pair of qfThreadInfo
685 // and qsThreadInfo packets, but it also might take a lot of room in the
686 // stop reply packet, so it must be enabled only on systems where there
687 // are no limits on packet lengths.
688 if (m_list_threads_in_stop_reply) {
689 response.PutCString("threads:");
691 uint32_t thread_index = 0;
692 NativeThreadProtocolSP listed_thread_sp;
693 for (listed_thread_sp =
694 m_debugged_process_sp->GetThreadAtIndex(thread_index);
695 listed_thread_sp; ++thread_index,
696 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
698 if (thread_index > 0)
699 response.PutChar(',');
700 response.Printf("%" PRIx64, listed_thread_sp->GetID());
702 response.PutChar(';');
704 // Include JSON info that describes the stop reason for any threads
705 // that actually have stop reasons. We use the new "jstopinfo" key
706 // whose values is hex ascii JSON that contains the thread IDs
707 // thread stop info only for threads that have stop reasons. Only send
708 // this if we have more than one thread otherwise this packet has all
709 // the info it needs.
710 if (thread_index > 0) {
711 const bool threads_with_valid_stop_info_only = true;
712 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
713 *m_debugged_process_sp, threads_with_valid_stop_info_only);
714 if (threads_info_sp) {
715 response.PutCString("jstopinfo:");
716 StreamString unescaped_response;
717 threads_info_sp->Write(unescaped_response);
718 response.PutCStringAsRawHex8(unescaped_response.GetData());
719 response.PutChar(';');
721 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
722 "jstopinfo field for pid %" PRIu64,
723 __FUNCTION__, m_debugged_process_sp->GetID());
727 response.PutCString("thread-pcs");
728 char delimiter = ':';
729 for (NativeThreadProtocolSP thread_sp;
730 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
732 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
736 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
737 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
738 const RegisterInfo *const reg_info_p =
739 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
741 RegisterValue reg_value;
742 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
745 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
747 reg_info_p->name ? reg_info_p->name
748 : "<unnamed-register>",
749 reg_to_read, error.AsCString());
753 response.PutChar(delimiter);
755 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
756 ®_value, endian::InlHostByteOrder());
759 response.PutChar(';');
763 // Expedite registers.
766 // Grab the register context.
767 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
769 // Expedite all registers in the first register set (i.e. should be GPRs)
770 // that are not contained in other registers.
771 const RegisterSet *reg_set_p;
772 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
773 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
775 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
776 "from set '%s' (registers set count: %zu)",
778 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
779 reg_set_p->num_registers);
781 for (const uint32_t *reg_num_p = reg_set_p->registers;
782 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
783 const RegisterInfo *const reg_info_p =
784 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
785 if (reg_info_p == nullptr) {
787 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
788 "register info for register set '%s', register index "
791 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
793 } else if (reg_info_p->value_regs == nullptr) {
794 // Only expediate registers that are not contained in other registers.
795 RegisterValue reg_value;
796 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
797 if (error.Success()) {
798 response.Printf("%.02x:", *reg_num_p);
799 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
800 ®_value, lldb::eByteOrderBig);
801 response.PutChar(';');
804 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
805 "register '%s' index %" PRIu32 ": %s",
806 __FUNCTION__, reg_info_p->name ? reg_info_p->name
807 : "<unnamed-register>",
808 *reg_num_p, error.AsCString());
815 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
816 if (reason_str != nullptr) {
817 response.Printf("reason:%s;", reason_str);
820 if (!description.empty()) {
821 // Description may contains special chars, send as hex bytes.
822 response.PutCString("description:");
823 response.PutCStringAsRawHex8(description.c_str());
824 response.PutChar(';');
825 } else if ((tid_stop_info.reason == eStopReasonException) &&
826 tid_stop_info.details.exception.type) {
827 response.PutCString("metype:");
828 response.PutHex64(tid_stop_info.details.exception.type);
829 response.PutCString(";mecount:");
830 response.PutHex32(tid_stop_info.details.exception.data_count);
831 response.PutChar(';');
833 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
834 response.PutCString("medata:");
835 response.PutHex64(tid_stop_info.details.exception.data[i]);
836 response.PutChar(';');
840 return SendPacketNoLock(response.GetString());
843 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
844 NativeProcessProtocol *process) {
845 assert(process && "process cannot be NULL");
847 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
849 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
851 PacketResult result = SendStopReasonForState(StateType::eStateExited);
852 if (result != PacketResult::Success) {
854 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
855 "notification for PID %" PRIu64 ", state: eStateExited",
856 __FUNCTION__, process->GetID());
859 // Close the pipe to the inferior terminal i/o if we launched it
861 MaybeCloseInferiorTerminalConnection();
863 // We are ready to exit the debug monitor.
867 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
868 NativeProcessProtocol *process) {
869 assert(process && "process cannot be NULL");
871 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
873 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
875 // Send the stop reason unless this is the stop after the
877 switch (m_inferior_prev_state) {
878 case eStateLaunching:
879 case eStateAttaching:
880 // Don't send anything per debugserver behavior.
883 // In all other cases, send the stop reason.
884 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
885 if (result != PacketResult::Success) {
887 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
888 "notification for PID %" PRIu64 ", state: eStateExited",
889 __FUNCTION__, process->GetID());
895 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
896 NativeProcessProtocol *process, lldb::StateType state) {
897 assert(process && "process cannot be NULL");
898 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
900 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
901 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
902 __FUNCTION__, process->GetID(), StateAsCString(state));
906 case StateType::eStateRunning:
907 StartSTDIOForwarding();
910 case StateType::eStateStopped:
911 // Make sure we get all of the pending stdout/stderr from the inferior
912 // and send it to the lldb host before we send the state change
915 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
917 // interfere with our protocol.
918 StopSTDIOForwarding();
919 HandleInferiorState_Stopped(process);
922 case StateType::eStateExited:
925 StopSTDIOForwarding();
926 HandleInferiorState_Exited(process);
931 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
932 "change for pid %" PRIu64 ", new state: %s",
933 __FUNCTION__, process->GetID(), StateAsCString(state));
938 // Remember the previous state reported to us.
939 m_inferior_prev_state = state;
942 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
943 ClearProcessSpecificData();
946 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
947 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
949 if (!m_handshake_completed) {
950 if (!HandshakeWithClient()) {
952 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
953 "client failed, exiting",
955 m_mainloop.RequestTermination();
958 m_handshake_completed = true;
961 bool interrupt = false;
965 const PacketResult result = GetPacketAndSendResponse(
966 std::chrono::microseconds(0), error, interrupt, done);
967 if (result == PacketResult::ErrorReplyTimeout)
968 break; // No more packets in the queue
970 if ((result != PacketResult::Success)) {
972 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
974 __FUNCTION__, error.AsCString());
975 m_mainloop.RequestTermination();
981 Error GDBRemoteCommunicationServerLLGS::InitializeConnection(
982 std::unique_ptr<Connection> &&connection) {
983 IOObjectSP read_object_sp = connection->GetReadObject();
984 GDBRemoteCommunicationServer::SetConnection(connection.release());
987 m_network_handle_up = m_mainloop.RegisterReadObject(
988 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
993 GDBRemoteCommunication::PacketResult
994 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
996 if ((buffer == nullptr) || (len == 0)) {
998 return PacketResult::Success;
1001 StreamString response;
1002 response.PutChar('O');
1003 response.PutBytesAsRawHex8(buffer, len);
1005 return SendPacketNoLock(response.GetString());
1008 Error GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1011 // Set up the reading/handling of process I/O
1012 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1013 new ConnectionFileDescriptor(fd, true));
1015 error.SetErrorString("failed to create ConnectionFileDescriptor");
1019 m_stdio_communication.SetCloseOnEOF(false);
1020 m_stdio_communication.SetConnection(conn_up.release());
1021 if (!m_stdio_communication.IsConnected()) {
1022 error.SetErrorString(
1023 "failed to set connection for inferior I/O communication");
1030 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1031 // Don't forward if not connected (e.g. when attaching).
1032 if (!m_stdio_communication.IsConnected())
1036 lldbassert(!m_stdio_handle_up);
1037 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1038 m_stdio_communication.GetConnection()->GetReadObject(),
1039 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1041 if (!m_stdio_handle_up) {
1042 // Not much we can do about the failure. Log it and continue without
1044 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1045 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1047 __FUNCTION__, error.AsCString());
1051 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1052 m_stdio_handle_up.reset();
1055 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1057 ConnectionStatus status;
1060 size_t bytes_read = m_stdio_communication.Read(
1061 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1063 case eConnectionStatusSuccess:
1064 SendONotification(buffer, bytes_read);
1066 case eConnectionStatusLostConnection:
1067 case eConnectionStatusEndOfFile:
1068 case eConnectionStatusError:
1069 case eConnectionStatusNoConnection:
1070 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1071 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1072 "forwarding as communication returned status %d (error: "
1074 __FUNCTION__, status, error.AsCString());
1075 m_stdio_handle_up.reset();
1078 case eConnectionStatusInterrupted:
1079 case eConnectionStatusTimedOut:
1085 GDBRemoteCommunication::PacketResult
1086 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1087 StringExtractorGDBRemote &packet) {
1088 // Fail if we don't have a current process.
1089 if (!m_debugged_process_sp ||
1090 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1091 return SendErrorResponse(68);
1093 lldb::pid_t pid = m_debugged_process_sp->GetID();
1095 if (pid == LLDB_INVALID_PROCESS_ID)
1096 return SendErrorResponse(1);
1098 ProcessInstanceInfo proc_info;
1099 if (!Host::GetProcessInfo(pid, proc_info))
1100 return SendErrorResponse(1);
1102 StreamString response;
1103 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1104 return SendPacketNoLock(response.GetString());
1107 GDBRemoteCommunication::PacketResult
1108 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1109 // Fail if we don't have a current process.
1110 if (!m_debugged_process_sp ||
1111 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1112 return SendErrorResponse(68);
1114 // Make sure we set the current thread so g and p packets return
1115 // the data the gdb will expect.
1116 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1117 SetCurrentThreadID(tid);
1119 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1121 return SendErrorResponse(69);
1123 StreamString response;
1124 response.Printf("QC%" PRIx64, thread_sp->GetID());
1126 return SendPacketNoLock(response.GetString());
1129 GDBRemoteCommunication::PacketResult
1130 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1131 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1133 StopSTDIOForwarding();
1135 if (!m_debugged_process_sp) {
1138 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1140 return PacketResult::Success;
1143 Error error = m_debugged_process_sp->Kill();
1144 if (error.Fail() && log)
1145 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1146 "process %" PRIu64 ": %s",
1147 __FUNCTION__, m_debugged_process_sp->GetID(),
1150 // No OK response for kill packet.
1151 // return SendOKResponse ();
1152 return PacketResult::Success;
1155 GDBRemoteCommunication::PacketResult
1156 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1157 StringExtractorGDBRemote &packet) {
1158 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1159 if (packet.GetU32(0))
1160 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1162 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1163 return SendOKResponse();
1166 GDBRemoteCommunication::PacketResult
1167 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1168 StringExtractorGDBRemote &packet) {
1169 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1171 packet.GetHexByteString(path);
1172 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1173 return SendOKResponse();
1176 GDBRemoteCommunication::PacketResult
1177 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1178 StringExtractorGDBRemote &packet) {
1179 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1181 StreamString response;
1182 response.PutCStringAsRawHex8(working_dir.GetCString());
1183 return SendPacketNoLock(response.GetString());
1186 return SendErrorResponse(14);
1189 GDBRemoteCommunication::PacketResult
1190 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1191 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1193 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1195 // Ensure we have a native process.
1196 if (!m_debugged_process_sp) {
1198 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1201 return SendErrorResponse(0x36);
1204 // Pull out the signal number.
1205 packet.SetFilePos(::strlen("C"));
1206 if (packet.GetBytesLeft() < 1) {
1207 // Shouldn't be using a C without a signal.
1208 return SendIllFormedResponse(packet, "C packet specified without signal.");
1210 const uint32_t signo =
1211 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1212 if (signo == std::numeric_limits<uint32_t>::max())
1213 return SendIllFormedResponse(packet, "failed to parse signal number");
1215 // Handle optional continue address.
1216 if (packet.GetBytesLeft() > 0) {
1217 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1218 if (*packet.Peek() == ';')
1219 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1221 return SendIllFormedResponse(
1222 packet, "unexpected content after $C{signal-number}");
1225 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1228 // We have two branches: what to do if a continue thread is specified (in
1229 // which case we target
1230 // sending the signal to that thread), or when we don't have a continue thread
1232 // case we send a signal to the process).
1234 // TODO discuss with Greg Clayton, make sure this makes sense.
1236 lldb::tid_t signal_tid = GetContinueThreadID();
1237 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1238 // The resume action for the continue thread (or all threads if a continue
1239 // thread is not set).
1240 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1241 static_cast<int>(signo)};
1243 // Add the action for the continue thread (or all threads when the continue
1244 // thread isn't present).
1245 resume_actions.Append(action);
1247 // Send the signal to the process since we weren't targeting a specific
1248 // continue thread with the signal.
1249 error = m_debugged_process_sp->Signal(signo);
1252 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1253 "signal for process %" PRIu64 ": %s",
1254 __FUNCTION__, m_debugged_process_sp->GetID(),
1257 return SendErrorResponse(0x52);
1261 // Resume the threads.
1262 error = m_debugged_process_sp->Resume(resume_actions);
1265 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1266 "threads for process %" PRIu64 ": %s",
1267 __FUNCTION__, m_debugged_process_sp->GetID(),
1270 return SendErrorResponse(0x38);
1273 // Don't send an "OK" packet; response is the stopped/exited message.
1274 return PacketResult::Success;
1277 GDBRemoteCommunication::PacketResult
1278 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1279 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1281 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1283 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1285 // For now just support all continue.
1286 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1287 if (has_continue_address) {
1289 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1290 "c{address} variant [%s remains]",
1291 __FUNCTION__, packet.Peek());
1292 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1295 // Ensure we have a native process.
1296 if (!m_debugged_process_sp) {
1298 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1301 return SendErrorResponse(0x36);
1304 // Build the ResumeActionList
1305 ResumeActionList actions(StateType::eStateRunning, 0);
1307 Error error = m_debugged_process_sp->Resume(actions);
1311 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1313 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1315 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1320 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1321 __FUNCTION__, m_debugged_process_sp->GetID());
1323 // No response required from continue.
1324 return PacketResult::Success;
1327 GDBRemoteCommunication::PacketResult
1328 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1329 StringExtractorGDBRemote &packet) {
1330 StreamString response;
1331 response.Printf("vCont;c;C;s;S");
1333 return SendPacketNoLock(response.GetString());
1336 GDBRemoteCommunication::PacketResult
1337 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1338 StringExtractorGDBRemote &packet) {
1339 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1341 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1344 packet.SetFilePos(::strlen("vCont"));
1346 if (packet.GetBytesLeft() == 0) {
1348 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1351 return SendIllFormedResponse(packet, "Missing action from vCont package");
1354 // Check if this is all continue (no options or ";c").
1355 if (::strcmp(packet.Peek(), ";c") == 0) {
1356 // Move past the ';', then do a simple 'c'.
1357 packet.SetFilePos(packet.GetFilePos() + 1);
1358 return Handle_c(packet);
1359 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1360 // Move past the ';', then do a simple 's'.
1361 packet.SetFilePos(packet.GetFilePos() + 1);
1362 return Handle_s(packet);
1365 // Ensure we have a native process.
1366 if (!m_debugged_process_sp) {
1368 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1371 return SendErrorResponse(0x36);
1374 ResumeActionList thread_actions;
1376 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1377 // Skip the semi-colon.
1380 // Build up the thread action.
1381 ResumeAction thread_action;
1382 thread_action.tid = LLDB_INVALID_THREAD_ID;
1383 thread_action.state = eStateInvalid;
1384 thread_action.signal = 0;
1386 const char action = packet.GetChar();
1389 thread_action.signal = packet.GetHexMaxU32(false, 0);
1390 if (thread_action.signal == 0)
1391 return SendIllFormedResponse(
1392 packet, "Could not parse signal in vCont packet C action");
1397 thread_action.state = eStateRunning;
1401 thread_action.signal = packet.GetHexMaxU32(false, 0);
1402 if (thread_action.signal == 0)
1403 return SendIllFormedResponse(
1404 packet, "Could not parse signal in vCont packet S action");
1409 thread_action.state = eStateStepping;
1413 return SendIllFormedResponse(packet, "Unsupported vCont action");
1417 // Parse out optional :{thread-id} value.
1418 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1419 // Consume the separator.
1422 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1423 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1424 return SendIllFormedResponse(
1425 packet, "Could not parse thread number in vCont packet");
1428 thread_actions.Append(thread_action);
1431 Error error = m_debugged_process_sp->Resume(thread_actions);
1434 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1435 "process %" PRIu64 ": %s",
1436 __FUNCTION__, m_debugged_process_sp->GetID(),
1439 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1444 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1445 __FUNCTION__, m_debugged_process_sp->GetID());
1447 // No response required from vCont.
1448 return PacketResult::Success;
1451 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1452 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1454 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1458 m_current_tid = tid;
1459 if (m_debugged_process_sp)
1460 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1463 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1464 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1466 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1470 m_continue_tid = tid;
1473 GDBRemoteCommunication::PacketResult
1474 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1475 StringExtractorGDBRemote &packet) {
1476 // Handle the $? gdbremote command.
1478 // If no process, indicate error
1479 if (!m_debugged_process_sp)
1480 return SendErrorResponse(02);
1482 return SendStopReasonForState(m_debugged_process_sp->GetState());
1485 GDBRemoteCommunication::PacketResult
1486 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1487 lldb::StateType process_state) {
1488 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1490 switch (process_state) {
1491 case eStateAttaching:
1492 case eStateLaunching:
1494 case eStateStepping:
1495 case eStateDetached:
1496 // NOTE: gdb protocol doc looks like it should return $OK
1497 // when everything is running (i.e. no stopped result).
1498 return PacketResult::Success; // Ignore
1500 case eStateSuspended:
1502 case eStateCrashed: {
1503 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1504 // Make sure we set the current thread so g and p packets return
1505 // the data the gdb will expect.
1506 SetCurrentThreadID(tid);
1507 return SendStopReplyPacketForThread(tid);
1511 case eStateUnloaded:
1513 return SendWResponse(m_debugged_process_sp.get());
1517 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1518 ", current state reporting not handled: %s",
1519 __FUNCTION__, m_debugged_process_sp->GetID(),
1520 StateAsCString(process_state));
1525 return SendErrorResponse(0);
1528 GDBRemoteCommunication::PacketResult
1529 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1530 StringExtractorGDBRemote &packet) {
1531 // Fail if we don't have a current process.
1532 if (!m_debugged_process_sp ||
1533 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1534 return SendErrorResponse(68);
1536 // Ensure we have a thread.
1537 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1539 return SendErrorResponse(69);
1541 // Get the register context for the first thread.
1542 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1543 if (!reg_context_sp)
1544 return SendErrorResponse(69);
1546 // Parse out the register number from the request.
1547 packet.SetFilePos(strlen("qRegisterInfo"));
1548 const uint32_t reg_index =
1549 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1550 if (reg_index == std::numeric_limits<uint32_t>::max())
1551 return SendErrorResponse(69);
1553 // Return the end of registers response if we've iterated one past the end of
1554 // the register set.
1555 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1556 return SendErrorResponse(69);
1558 const RegisterInfo *reg_info =
1559 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1561 return SendErrorResponse(69);
1563 // Build the reginfos response.
1564 StreamGDBRemote response;
1566 response.PutCString("name:");
1567 response.PutCString(reg_info->name);
1568 response.PutChar(';');
1570 if (reg_info->alt_name && reg_info->alt_name[0]) {
1571 response.PutCString("alt-name:");
1572 response.PutCString(reg_info->alt_name);
1573 response.PutChar(';');
1576 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1577 reg_info->byte_size * 8, reg_info->byte_offset);
1579 switch (reg_info->encoding) {
1581 response.PutCString("encoding:uint;");
1584 response.PutCString("encoding:sint;");
1586 case eEncodingIEEE754:
1587 response.PutCString("encoding:ieee754;");
1589 case eEncodingVector:
1590 response.PutCString("encoding:vector;");
1596 switch (reg_info->format) {
1598 response.PutCString("format:binary;");
1600 case eFormatDecimal:
1601 response.PutCString("format:decimal;");
1604 response.PutCString("format:hex;");
1607 response.PutCString("format:float;");
1609 case eFormatVectorOfSInt8:
1610 response.PutCString("format:vector-sint8;");
1612 case eFormatVectorOfUInt8:
1613 response.PutCString("format:vector-uint8;");
1615 case eFormatVectorOfSInt16:
1616 response.PutCString("format:vector-sint16;");
1618 case eFormatVectorOfUInt16:
1619 response.PutCString("format:vector-uint16;");
1621 case eFormatVectorOfSInt32:
1622 response.PutCString("format:vector-sint32;");
1624 case eFormatVectorOfUInt32:
1625 response.PutCString("format:vector-uint32;");
1627 case eFormatVectorOfFloat32:
1628 response.PutCString("format:vector-float32;");
1630 case eFormatVectorOfUInt64:
1631 response.PutCString("format:vector-uint64;");
1633 case eFormatVectorOfUInt128:
1634 response.PutCString("format:vector-uint128;");
1640 const char *const register_set_name =
1641 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1642 if (register_set_name) {
1643 response.PutCString("set:");
1644 response.PutCString(register_set_name);
1645 response.PutChar(';');
1648 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1649 LLDB_INVALID_REGNUM)
1650 response.Printf("ehframe:%" PRIu32 ";",
1651 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1653 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1654 response.Printf("dwarf:%" PRIu32 ";",
1655 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1657 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1658 case LLDB_REGNUM_GENERIC_PC:
1659 response.PutCString("generic:pc;");
1661 case LLDB_REGNUM_GENERIC_SP:
1662 response.PutCString("generic:sp;");
1664 case LLDB_REGNUM_GENERIC_FP:
1665 response.PutCString("generic:fp;");
1667 case LLDB_REGNUM_GENERIC_RA:
1668 response.PutCString("generic:ra;");
1670 case LLDB_REGNUM_GENERIC_FLAGS:
1671 response.PutCString("generic:flags;");
1673 case LLDB_REGNUM_GENERIC_ARG1:
1674 response.PutCString("generic:arg1;");
1676 case LLDB_REGNUM_GENERIC_ARG2:
1677 response.PutCString("generic:arg2;");
1679 case LLDB_REGNUM_GENERIC_ARG3:
1680 response.PutCString("generic:arg3;");
1682 case LLDB_REGNUM_GENERIC_ARG4:
1683 response.PutCString("generic:arg4;");
1685 case LLDB_REGNUM_GENERIC_ARG5:
1686 response.PutCString("generic:arg5;");
1688 case LLDB_REGNUM_GENERIC_ARG6:
1689 response.PutCString("generic:arg6;");
1691 case LLDB_REGNUM_GENERIC_ARG7:
1692 response.PutCString("generic:arg7;");
1694 case LLDB_REGNUM_GENERIC_ARG8:
1695 response.PutCString("generic:arg8;");
1701 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1702 response.PutCString("container-regs:");
1704 for (const uint32_t *reg_num = reg_info->value_regs;
1705 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1707 response.PutChar(',');
1708 response.Printf("%" PRIx32, *reg_num);
1710 response.PutChar(';');
1713 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1714 response.PutCString("invalidate-regs:");
1716 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1717 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1719 response.PutChar(',');
1720 response.Printf("%" PRIx32, *reg_num);
1722 response.PutChar(';');
1725 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1726 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1727 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1728 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1729 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1730 response.PutChar(';');
1732 return SendPacketNoLock(response.GetString());
1735 GDBRemoteCommunication::PacketResult
1736 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1737 StringExtractorGDBRemote &packet) {
1738 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1740 // Fail if we don't have a current process.
1741 if (!m_debugged_process_sp ||
1742 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1744 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1747 m_debugged_process_sp ? "invalid process id"
1748 : "null m_debugged_process_sp");
1749 return SendOKResponse();
1752 StreamGDBRemote response;
1753 response.PutChar('m');
1757 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1760 NativeThreadProtocolSP thread_sp;
1761 uint32_t thread_index;
1762 for (thread_index = 0,
1763 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1764 thread_sp; ++thread_index,
1765 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1768 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1769 "(%s, tid=0x%" PRIx64 ")",
1770 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1771 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1772 if (thread_index > 0)
1773 response.PutChar(',');
1774 response.Printf("%" PRIx64, thread_sp->GetID());
1779 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1782 return SendPacketNoLock(response.GetString());
1785 GDBRemoteCommunication::PacketResult
1786 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1787 StringExtractorGDBRemote &packet) {
1788 // FIXME for now we return the full thread list in the initial packet and
1789 // always do nothing here.
1790 return SendPacketNoLock("l");
1793 GDBRemoteCommunication::PacketResult
1794 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1795 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1797 // Parse out the register number from the request.
1798 packet.SetFilePos(strlen("p"));
1799 const uint32_t reg_index =
1800 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1801 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1803 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1804 "parse register number from request \"%s\"",
1805 __FUNCTION__, packet.GetStringRef().c_str());
1806 return SendErrorResponse(0x15);
1809 // Get the thread to use.
1810 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1814 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
1816 return SendErrorResponse(0x15);
1819 // Get the thread's register context.
1820 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1821 if (!reg_context_sp) {
1824 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1825 " failed, no register context available for the thread",
1826 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1827 return SendErrorResponse(0x15);
1830 // Return the end of registers response if we've iterated one past the end of
1831 // the register set.
1832 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1834 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1835 "register %" PRIu32 " beyond register count %" PRIu32,
1836 __FUNCTION__, reg_index,
1837 reg_context_sp->GetUserRegisterCount());
1838 return SendErrorResponse(0x15);
1841 const RegisterInfo *reg_info =
1842 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1845 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1846 "register %" PRIu32 " returned NULL",
1847 __FUNCTION__, reg_index);
1848 return SendErrorResponse(0x15);
1851 // Build the reginfos response.
1852 StreamGDBRemote response;
1854 // Retrieve the value
1855 RegisterValue reg_value;
1856 Error error = reg_context_sp->ReadRegister(reg_info, reg_value);
1859 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1860 "requested register %" PRIu32 " (%s) failed: %s",
1861 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1862 return SendErrorResponse(0x15);
1865 const uint8_t *const data =
1866 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1869 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1870 "bytes from requested register %" PRIu32,
1871 __FUNCTION__, reg_index);
1872 return SendErrorResponse(0x15);
1875 // FIXME flip as needed to get data in big/little endian format for this host.
1876 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1877 response.PutHex8(data[i]);
1879 return SendPacketNoLock(response.GetString());
1882 GDBRemoteCommunication::PacketResult
1883 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1884 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1886 // Ensure there is more content.
1887 if (packet.GetBytesLeft() < 1)
1888 return SendIllFormedResponse(packet, "Empty P packet");
1890 // Parse out the register number from the request.
1891 packet.SetFilePos(strlen("P"));
1892 const uint32_t reg_index =
1893 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1894 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1896 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1897 "parse register number from request \"%s\"",
1898 __FUNCTION__, packet.GetStringRef().c_str());
1899 return SendErrorResponse(0x29);
1902 // Note debugserver would send an E30 here.
1903 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
1904 return SendIllFormedResponse(
1905 packet, "P packet missing '=' char after register number");
1907 // Get process architecture.
1908 ArchSpec process_arch;
1909 if (!m_debugged_process_sp ||
1910 !m_debugged_process_sp->GetArchitecture(process_arch)) {
1912 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
1913 "inferior architecture",
1915 return SendErrorResponse(0x49);
1918 // Parse out the value.
1919 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1920 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
1922 // Get the thread to use.
1923 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1926 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
1927 "available (thread index 0)",
1929 return SendErrorResponse(0x28);
1932 // Get the thread's register context.
1933 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1934 if (!reg_context_sp) {
1937 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1938 " failed, no register context available for the thread",
1939 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1940 return SendErrorResponse(0x15);
1943 const RegisterInfo *reg_info =
1944 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1947 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1948 "register %" PRIu32 " returned NULL",
1949 __FUNCTION__, reg_index);
1950 return SendErrorResponse(0x48);
1953 // Return the end of registers response if we've iterated one past the end of
1954 // the register set.
1955 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1957 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1958 "register %" PRIu32 " beyond register count %" PRIu32,
1959 __FUNCTION__, reg_index,
1960 reg_context_sp->GetUserRegisterCount());
1961 return SendErrorResponse(0x47);
1964 // The dwarf expression are evaluate on host site
1965 // which may cause register size to change
1966 // Hence the reg_size may not be same as reg_info->bytes_size
1967 if ((reg_size != reg_info->byte_size) &&
1968 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
1969 return SendIllFormedResponse(packet, "P packet register size is incorrect");
1972 // Build the reginfos response.
1973 StreamGDBRemote response;
1975 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
1976 Error error = reg_context_sp->WriteRegister(reg_info, reg_value);
1979 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
1980 "requested register %" PRIu32 " (%s) failed: %s",
1981 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1982 return SendErrorResponse(0x32);
1985 return SendOKResponse();
1988 GDBRemoteCommunication::PacketResult
1989 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
1990 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1992 // Fail if we don't have a current process.
1993 if (!m_debugged_process_sp ||
1994 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1997 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
1999 return SendErrorResponse(0x15);
2002 // Parse out which variant of $H is requested.
2003 packet.SetFilePos(strlen("H"));
2004 if (packet.GetBytesLeft() < 1) {
2006 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2007 "missing {g,c} variant",
2009 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2012 const char h_variant = packet.GetChar();
2013 switch (h_variant) {
2023 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2024 __FUNCTION__, h_variant);
2025 return SendIllFormedResponse(packet,
2026 "H variant unsupported, should be c or g");
2029 // Parse out the thread number.
2030 // FIXME return a parse success/fail value. All values are valid here.
2031 const lldb::tid_t tid =
2032 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2034 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2036 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2037 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2040 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2043 return SendErrorResponse(0x15);
2047 // Now switch the given thread type.
2048 switch (h_variant) {
2050 SetCurrentThreadID(tid);
2054 SetContinueThreadID(tid);
2058 assert(false && "unsupported $H variant - shouldn't get here");
2059 return SendIllFormedResponse(packet,
2060 "H variant unsupported, should be c or g");
2063 return SendOKResponse();
2066 GDBRemoteCommunication::PacketResult
2067 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2068 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2070 // Fail if we don't have a current process.
2071 if (!m_debugged_process_sp ||
2072 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2075 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2077 return SendErrorResponse(0x15);
2080 packet.SetFilePos(::strlen("I"));
2083 size_t read = packet.GetHexBytesAvail(tmp);
2087 // write directly to stdin *this might block if stdin buffer is full*
2088 // TODO: enqueue this block in circular buffer and send window size to
2090 ConnectionStatus status;
2092 m_stdio_communication.Write(tmp, read, status, &error);
2094 return SendErrorResponse(0x15);
2098 return SendOKResponse();
2101 GDBRemoteCommunication::PacketResult
2102 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2103 StringExtractorGDBRemote &packet) {
2104 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2106 // Fail if we don't have a current process.
2107 if (!m_debugged_process_sp ||
2108 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2111 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2113 return SendErrorResponse(0x15);
2116 // Interrupt the process.
2117 Error error = m_debugged_process_sp->Interrupt();
2121 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2123 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
2125 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2129 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2130 __FUNCTION__, m_debugged_process_sp->GetID());
2132 // No response required from stop all.
2133 return PacketResult::Success;
2136 GDBRemoteCommunication::PacketResult
2137 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2138 StringExtractorGDBRemote &packet) {
2139 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2141 if (!m_debugged_process_sp ||
2142 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2145 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2147 return SendErrorResponse(0x15);
2150 // Parse out the memory address.
2151 packet.SetFilePos(strlen("m"));
2152 if (packet.GetBytesLeft() < 1)
2153 return SendIllFormedResponse(packet, "Too short m packet");
2155 // Read the address. Punting on validation.
2156 // FIXME replace with Hex U64 read with no default value that fails on failed
2158 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2161 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2162 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2164 // Get # bytes to read.
2165 if (packet.GetBytesLeft() < 1)
2166 return SendIllFormedResponse(packet, "Length missing in m packet");
2168 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2169 if (byte_count == 0) {
2171 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2172 "zero-length packet",
2174 return SendOKResponse();
2177 // Allocate the response buffer.
2178 std::string buf(byte_count, '\0');
2180 return SendErrorResponse(0x78);
2182 // Retrieve the process memory.
2183 size_t bytes_read = 0;
2184 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2185 read_addr, &buf[0], byte_count, bytes_read);
2188 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2189 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2190 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2192 return SendErrorResponse(0x08);
2195 if (bytes_read == 0) {
2197 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2198 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2199 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2201 return SendErrorResponse(0x08);
2204 StreamGDBRemote response;
2205 packet.SetFilePos(0);
2206 char kind = packet.GetChar('?');
2208 response.PutEscapedBytes(buf.data(), byte_count);
2210 assert(kind == 'm');
2211 for (size_t i = 0; i < bytes_read; ++i)
2212 response.PutHex8(buf[i]);
2215 return SendPacketNoLock(response.GetString());
2218 GDBRemoteCommunication::PacketResult
2219 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2220 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2222 if (!m_debugged_process_sp ||
2223 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2226 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2228 return SendErrorResponse(0x15);
2231 // Parse out the memory address.
2232 packet.SetFilePos(strlen("M"));
2233 if (packet.GetBytesLeft() < 1)
2234 return SendIllFormedResponse(packet, "Too short M packet");
2236 // Read the address. Punting on validation.
2237 // FIXME replace with Hex U64 read with no default value that fails on failed
2239 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2242 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2243 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2245 // Get # bytes to read.
2246 if (packet.GetBytesLeft() < 1)
2247 return SendIllFormedResponse(packet, "Length missing in M packet");
2249 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2250 if (byte_count == 0) {
2252 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2253 "zero-length packet",
2255 return PacketResult::Success;
2259 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2260 return SendIllFormedResponse(
2261 packet, "Comma sep missing in M packet after byte length");
2263 // Allocate the conversion buffer.
2264 std::vector<uint8_t> buf(byte_count, 0);
2266 return SendErrorResponse(0x78);
2268 // Convert the hex memory write contents to bytes.
2269 StreamGDBRemote response;
2270 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2271 if (convert_count != byte_count) {
2273 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2274 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2275 " bytes, but only found %" PRIu64 " to convert.",
2276 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2277 byte_count, convert_count);
2278 return SendIllFormedResponse(packet, "M content byte length specified did "
2279 "not match hex-encoded content "
2283 // Write the process memory.
2284 size_t bytes_written = 0;
2285 Error error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2286 byte_count, bytes_written);
2289 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2290 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2291 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2293 return SendErrorResponse(0x09);
2296 if (bytes_written == 0) {
2298 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2299 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2300 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2302 return SendErrorResponse(0x09);
2305 return SendOKResponse();
2308 GDBRemoteCommunication::PacketResult
2309 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2310 StringExtractorGDBRemote &packet) {
2311 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2313 // Currently only the NativeProcessProtocol knows if it can handle a
2314 // qMemoryRegionInfoSupported
2315 // request, but we're not guaranteed to be attached to a process. For now
2317 // client only asks this when a process is being debugged.
2319 // Ensure we have a process running; otherwise, we can't figure this out
2320 // since we won't have a NativeProcessProtocol.
2321 if (!m_debugged_process_sp ||
2322 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2325 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2327 return SendErrorResponse(0x15);
2330 // Test if we can get any region back when asking for the region around NULL.
2331 MemoryRegionInfo region_info;
2333 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2335 // We don't support memory region info collection for this
2336 // NativeProcessProtocol.
2337 return SendUnimplementedResponse("");
2340 return SendOKResponse();
2343 GDBRemoteCommunication::PacketResult
2344 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2345 StringExtractorGDBRemote &packet) {
2346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2348 // Ensure we have a process.
2349 if (!m_debugged_process_sp ||
2350 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2353 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2355 return SendErrorResponse(0x15);
2358 // Parse out the memory address.
2359 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2360 if (packet.GetBytesLeft() < 1)
2361 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2363 // Read the address. Punting on validation.
2364 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2366 StreamGDBRemote response;
2368 // Get the memory region info for the target address.
2369 MemoryRegionInfo region_info;
2371 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2373 // Return the error message.
2375 response.PutCString("error:");
2376 response.PutCStringAsRawHex8(error.AsCString());
2377 response.PutChar(';');
2379 // Range start and size.
2380 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2381 region_info.GetRange().GetRangeBase(),
2382 region_info.GetRange().GetByteSize());
2385 if (region_info.GetReadable() || region_info.GetWritable() ||
2386 region_info.GetExecutable()) {
2387 // Write permissions info.
2388 response.PutCString("permissions:");
2390 if (region_info.GetReadable())
2391 response.PutChar('r');
2392 if (region_info.GetWritable())
2393 response.PutChar('w');
2394 if (region_info.GetExecutable())
2395 response.PutChar('x');
2397 response.PutChar(';');
2401 ConstString name = region_info.GetName();
2403 response.PutCString("name:");
2404 response.PutCStringAsRawHex8(name.AsCString());
2405 response.PutChar(';');
2409 return SendPacketNoLock(response.GetString());
2412 GDBRemoteCommunication::PacketResult
2413 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2414 // Ensure we have a process.
2415 if (!m_debugged_process_sp ||
2416 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2417 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2420 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2422 return SendErrorResponse(0x15);
2425 // Parse out software or hardware breakpoint or watchpoint requested.
2426 packet.SetFilePos(strlen("Z"));
2427 if (packet.GetBytesLeft() < 1)
2428 return SendIllFormedResponse(
2429 packet, "Too short Z packet, missing software/hardware specifier");
2431 bool want_breakpoint = true;
2432 bool want_hardware = false;
2433 uint32_t watch_flags = 0;
2435 const GDBStoppointType stoppoint_type =
2436 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2437 switch (stoppoint_type) {
2438 case eBreakpointSoftware:
2439 want_hardware = false;
2440 want_breakpoint = true;
2442 case eBreakpointHardware:
2443 want_hardware = true;
2444 want_breakpoint = true;
2446 case eWatchpointWrite:
2448 want_hardware = true;
2449 want_breakpoint = false;
2451 case eWatchpointRead:
2453 want_hardware = true;
2454 want_breakpoint = false;
2456 case eWatchpointReadWrite:
2458 want_hardware = true;
2459 want_breakpoint = false;
2461 case eStoppointInvalid:
2462 return SendIllFormedResponse(
2463 packet, "Z packet had invalid software/hardware specifier");
2466 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2467 return SendIllFormedResponse(
2468 packet, "Malformed Z packet, expecting comma after stoppoint type");
2470 // Parse out the stoppoint address.
2471 if (packet.GetBytesLeft() < 1)
2472 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2473 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2475 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2476 return SendIllFormedResponse(
2477 packet, "Malformed Z packet, expecting comma after address");
2479 // Parse out the stoppoint size (i.e. size hint for opcode size).
2480 const uint32_t size =
2481 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2482 if (size == std::numeric_limits<uint32_t>::max())
2483 return SendIllFormedResponse(
2484 packet, "Malformed Z packet, failed to parse size argument");
2486 if (want_breakpoint) {
2487 // Try to set the breakpoint.
2489 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2490 if (error.Success())
2491 return SendOKResponse();
2492 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2494 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2495 " failed to set breakpoint: %s",
2496 __FUNCTION__, m_debugged_process_sp->GetID(),
2498 return SendErrorResponse(0x09);
2500 // Try to set the watchpoint.
2501 const Error error = m_debugged_process_sp->SetWatchpoint(
2502 addr, size, watch_flags, want_hardware);
2503 if (error.Success())
2504 return SendOKResponse();
2505 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2507 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2508 " failed to set watchpoint: %s",
2509 __FUNCTION__, m_debugged_process_sp->GetID(),
2511 return SendErrorResponse(0x09);
2515 GDBRemoteCommunication::PacketResult
2516 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2517 // Ensure we have a process.
2518 if (!m_debugged_process_sp ||
2519 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2520 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2523 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2525 return SendErrorResponse(0x15);
2528 // Parse out software or hardware breakpoint or watchpoint requested.
2529 packet.SetFilePos(strlen("z"));
2530 if (packet.GetBytesLeft() < 1)
2531 return SendIllFormedResponse(
2532 packet, "Too short z packet, missing software/hardware specifier");
2534 bool want_breakpoint = true;
2535 bool want_hardware = false;
2537 const GDBStoppointType stoppoint_type =
2538 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2539 switch (stoppoint_type) {
2540 case eBreakpointHardware:
2541 want_breakpoint = true;
2542 want_hardware = true;
2544 case eBreakpointSoftware:
2545 want_breakpoint = true;
2547 case eWatchpointWrite:
2548 want_breakpoint = false;
2550 case eWatchpointRead:
2551 want_breakpoint = false;
2553 case eWatchpointReadWrite:
2554 want_breakpoint = false;
2557 return SendIllFormedResponse(
2558 packet, "z packet had invalid software/hardware specifier");
2561 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2562 return SendIllFormedResponse(
2563 packet, "Malformed z packet, expecting comma after stoppoint type");
2565 // Parse out the stoppoint address.
2566 if (packet.GetBytesLeft() < 1)
2567 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2568 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2570 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2571 return SendIllFormedResponse(
2572 packet, "Malformed z packet, expecting comma after address");
2575 // Parse out the stoppoint size (i.e. size hint for opcode size).
2576 const uint32_t size = packet.GetHexMaxU32 (false,
2577 std::numeric_limits<uint32_t>::max ());
2578 if (size == std::numeric_limits<uint32_t>::max ())
2579 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2583 if (want_breakpoint) {
2584 // Try to clear the breakpoint.
2586 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
2587 if (error.Success())
2588 return SendOKResponse();
2589 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2591 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2592 " failed to remove breakpoint: %s",
2593 __FUNCTION__, m_debugged_process_sp->GetID(),
2595 return SendErrorResponse(0x09);
2597 // Try to clear the watchpoint.
2598 const Error error = m_debugged_process_sp->RemoveWatchpoint(addr);
2599 if (error.Success())
2600 return SendOKResponse();
2601 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2603 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2604 " failed to remove watchpoint: %s",
2605 __FUNCTION__, m_debugged_process_sp->GetID(),
2607 return SendErrorResponse(0x09);
2611 GDBRemoteCommunication::PacketResult
2612 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2613 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2615 // Ensure we have a process.
2616 if (!m_debugged_process_sp ||
2617 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2620 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2622 return SendErrorResponse(0x32);
2625 // We first try to use a continue thread id. If any one or any all set, use
2626 // the current thread.
2627 // Bail out if we don't have a thread id.
2628 lldb::tid_t tid = GetContinueThreadID();
2629 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2630 tid = GetCurrentThreadID();
2631 if (tid == LLDB_INVALID_THREAD_ID)
2632 return SendErrorResponse(0x33);
2634 // Double check that we have such a thread.
2635 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2636 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2637 if (!thread_sp || thread_sp->GetID() != tid)
2638 return SendErrorResponse(0x33);
2640 // Create the step action for the given thread.
2641 ResumeAction action = {tid, eStateStepping, 0};
2643 // Setup the actions list.
2644 ResumeActionList actions;
2645 actions.Append(action);
2647 // All other threads stop while we're single stepping a thread.
2648 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2649 Error error = m_debugged_process_sp->Resume(actions);
2652 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2653 " tid %" PRIu64 " Resume() failed with error: %s",
2654 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2656 return SendErrorResponse(0x49);
2659 // No response here - the stop or exit will come from the resulting action.
2660 return PacketResult::Success;
2663 GDBRemoteCommunication::PacketResult
2664 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2665 StringExtractorGDBRemote &packet) {
2666 // *BSD impls should be able to do this too.
2667 #if defined(__linux__) || defined(__NetBSD__)
2668 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2670 // Parse out the offset.
2671 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2672 if (packet.GetBytesLeft() < 1)
2673 return SendIllFormedResponse(packet,
2674 "qXfer:auxv:read:: packet missing offset");
2676 const uint64_t auxv_offset =
2677 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2678 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2679 return SendIllFormedResponse(packet,
2680 "qXfer:auxv:read:: packet missing offset");
2683 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2684 return SendIllFormedResponse(
2685 packet, "qXfer:auxv:read:: packet missing comma after offset");
2687 // Parse out the length.
2688 const uint64_t auxv_length =
2689 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2690 if (auxv_length == std::numeric_limits<uint64_t>::max())
2691 return SendIllFormedResponse(packet,
2692 "qXfer:auxv:read:: packet missing length");
2694 // Grab the auxv data if we need it.
2695 if (!m_active_auxv_buffer_up) {
2696 // Make sure we have a valid process.
2697 if (!m_debugged_process_sp ||
2698 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2701 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2703 return SendErrorResponse(0x10);
2706 // Grab the auxv data.
2707 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2708 if (!buffer_or_error) {
2709 std::error_code ec = buffer_or_error.getError();
2710 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2711 return SendErrorResponse(ec.value());
2713 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2716 StreamGDBRemote response;
2717 bool done_with_buffer = false;
2719 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2720 if (auxv_offset >= buffer.size()) {
2721 // We have nothing left to send. Mark the buffer as complete.
2722 response.PutChar('l');
2723 done_with_buffer = true;
2725 // Figure out how many bytes are available starting at the given offset.
2726 buffer = buffer.drop_front(auxv_offset);
2728 // Mark the response type according to whether we're reading the remainder
2729 // of the auxv data.
2730 if (auxv_length >= buffer.size()) {
2731 // There will be nothing left to read after this
2732 response.PutChar('l');
2733 done_with_buffer = true;
2735 // There will still be bytes to read after this request.
2736 response.PutChar('m');
2737 buffer = buffer.take_front(auxv_length);
2740 // Now write the data in encoded binary form.
2741 response.PutEscapedBytes(buffer.data(), buffer.size());
2744 if (done_with_buffer)
2745 m_active_auxv_buffer_up.reset();
2747 return SendPacketNoLock(response.GetString());
2749 return SendUnimplementedResponse("not implemented on this platform");
2753 GDBRemoteCommunication::PacketResult
2754 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2755 StringExtractorGDBRemote &packet) {
2756 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2758 // Move past packet name.
2759 packet.SetFilePos(strlen("QSaveRegisterState"));
2761 // Get the thread to use.
2762 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2764 if (m_thread_suffix_supported)
2765 return SendIllFormedResponse(
2766 packet, "No thread specified in QSaveRegisterState packet");
2768 return SendIllFormedResponse(packet,
2769 "No thread was is set with the Hg packet");
2772 // Grab the register context for the thread.
2773 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2774 if (!reg_context_sp) {
2777 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2778 " failed, no register context available for the thread",
2779 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2780 return SendErrorResponse(0x15);
2783 // Save registers to a buffer.
2784 DataBufferSP register_data_sp;
2785 Error error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
2788 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2789 " failed to save all register values: %s",
2790 __FUNCTION__, m_debugged_process_sp->GetID(),
2792 return SendErrorResponse(0x75);
2795 // Allocate a new save id.
2796 const uint32_t save_id = GetNextSavedRegistersID();
2797 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2798 "GetNextRegisterSaveID() returned an existing register save id");
2800 // Save the register data buffer under the save id.
2802 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2803 m_saved_registers_map[save_id] = register_data_sp;
2806 // Write the response.
2807 StreamGDBRemote response;
2808 response.Printf("%" PRIu32, save_id);
2809 return SendPacketNoLock(response.GetString());
2812 GDBRemoteCommunication::PacketResult
2813 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2814 StringExtractorGDBRemote &packet) {
2815 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2817 // Parse out save id.
2818 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2819 if (packet.GetBytesLeft() < 1)
2820 return SendIllFormedResponse(
2821 packet, "QRestoreRegisterState packet missing register save id");
2823 const uint32_t save_id = packet.GetU32(0);
2826 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
2827 "packet has malformed save id, expecting decimal uint32_t",
2829 return SendErrorResponse(0x76);
2832 // Get the thread to use.
2833 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2835 if (m_thread_suffix_supported)
2836 return SendIllFormedResponse(
2837 packet, "No thread specified in QRestoreRegisterState packet");
2839 return SendIllFormedResponse(packet,
2840 "No thread was is set with the Hg packet");
2843 // Grab the register context for the thread.
2844 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2845 if (!reg_context_sp) {
2848 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2849 " failed, no register context available for the thread",
2850 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2851 return SendErrorResponse(0x15);
2854 // Retrieve register state buffer, then remove from the list.
2855 DataBufferSP register_data_sp;
2857 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2859 // Find the register set buffer for the given save id.
2860 auto it = m_saved_registers_map.find(save_id);
2861 if (it == m_saved_registers_map.end()) {
2863 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2864 " does not have a register set save buffer for id %" PRIu32,
2865 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
2866 return SendErrorResponse(0x77);
2868 register_data_sp = it->second;
2870 // Remove it from the map.
2871 m_saved_registers_map.erase(it);
2874 Error error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
2877 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2878 " failed to restore all register values: %s",
2879 __FUNCTION__, m_debugged_process_sp->GetID(),
2881 return SendErrorResponse(0x77);
2884 return SendOKResponse();
2887 GDBRemoteCommunication::PacketResult
2888 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2889 StringExtractorGDBRemote &packet) {
2890 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2892 // Consume the ';' after vAttach.
2893 packet.SetFilePos(strlen("vAttach"));
2894 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2895 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2897 // Grab the PID to which we will attach (assume hex encoding).
2898 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2899 if (pid == LLDB_INVALID_PROCESS_ID)
2900 return SendIllFormedResponse(packet,
2901 "vAttach failed to parse the process id");
2903 // Attempt to attach.
2905 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2909 Error error = AttachToProcess(pid);
2913 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2914 "pid %" PRIu64 ": %s\n",
2915 __FUNCTION__, pid, error.AsCString());
2916 return SendErrorResponse(0x01);
2919 // Notify we attached by sending a stop packet.
2920 return SendStopReasonForState(m_debugged_process_sp->GetState());
2923 GDBRemoteCommunication::PacketResult
2924 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2925 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2927 StopSTDIOForwarding();
2929 // Fail if we don't have a current process.
2930 if (!m_debugged_process_sp ||
2931 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2934 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2936 return SendErrorResponse(0x15);
2939 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2941 // Consume the ';' after D.
2942 packet.SetFilePos(1);
2943 if (packet.GetBytesLeft()) {
2944 if (packet.GetChar() != ';')
2945 return SendIllFormedResponse(packet, "D missing expected ';'");
2947 // Grab the PID from which we will detach (assume hex encoding).
2948 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2949 if (pid == LLDB_INVALID_PROCESS_ID)
2950 return SendIllFormedResponse(packet, "D failed to parse the process id");
2953 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
2954 return SendIllFormedResponse(packet, "Invalid pid");
2957 const Error error = m_debugged_process_sp->Detach();
2960 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2961 "pid %" PRIu64 ": %s\n",
2962 __FUNCTION__, m_debugged_process_sp->GetID(),
2964 return SendErrorResponse(0x01);
2967 return SendOKResponse();
2970 GDBRemoteCommunication::PacketResult
2971 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2972 StringExtractorGDBRemote &packet) {
2973 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2975 packet.SetFilePos(strlen("qThreadStopInfo"));
2976 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2977 if (tid == LLDB_INVALID_THREAD_ID) {
2979 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2980 "parse thread id from request \"%s\"",
2981 __FUNCTION__, packet.GetStringRef().c_str());
2982 return SendErrorResponse(0x15);
2984 return SendStopReplyPacketForThread(tid);
2987 GDBRemoteCommunication::PacketResult
2988 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
2989 StringExtractorGDBRemote &) {
2990 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2992 // Ensure we have a debugged process.
2993 if (!m_debugged_process_sp ||
2994 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
2995 return SendErrorResponse(50);
2998 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3000 __FUNCTION__, m_debugged_process_sp->GetID());
3002 StreamString response;
3003 const bool threads_with_valid_stop_info_only = false;
3004 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3005 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3006 if (!threads_array_sp) {
3008 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3009 "packet for pid %" PRIu64,
3010 __FUNCTION__, m_debugged_process_sp->GetID());
3011 return SendErrorResponse(52);
3014 threads_array_sp->Write(response);
3015 StreamGDBRemote escaped_response;
3016 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3017 return SendPacketNoLock(escaped_response.GetString());
3020 GDBRemoteCommunication::PacketResult
3021 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3022 StringExtractorGDBRemote &packet) {
3023 // Fail if we don't have a current process.
3024 if (!m_debugged_process_sp ||
3025 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3026 return SendErrorResponse(68);
3028 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3029 if (packet.GetBytesLeft() == 0)
3030 return SendOKResponse();
3031 if (packet.GetChar() != ':')
3032 return SendErrorResponse(67);
3034 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3036 StreamGDBRemote response;
3037 if (hw_debug_cap == llvm::None)
3038 response.Printf("num:0;");
3040 response.Printf("num:%d;", hw_debug_cap->second);
3042 return SendPacketNoLock(response.GetString());
3045 GDBRemoteCommunication::PacketResult
3046 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3047 StringExtractorGDBRemote &packet) {
3048 // Fail if we don't have a current process.
3049 if (!m_debugged_process_sp ||
3050 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3051 return SendErrorResponse(67);
3053 packet.SetFilePos(strlen("qFileLoadAddress:"));
3054 if (packet.GetBytesLeft() == 0)
3055 return SendErrorResponse(68);
3057 std::string file_name;
3058 packet.GetHexByteString(file_name);
3060 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3062 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3064 return SendErrorResponse(69);
3066 if (file_load_address == LLDB_INVALID_ADDRESS)
3067 return SendErrorResponse(1); // File not loaded
3069 StreamGDBRemote response;
3070 response.PutHex64(file_load_address);
3071 return SendPacketNoLock(response.GetString());
3074 GDBRemoteCommunication::PacketResult
3075 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3076 StringExtractorGDBRemote &packet) {
3077 std::vector<int> signals;
3078 packet.SetFilePos(strlen("QPassSignals:"));
3080 // Read sequence of hex signal numbers divided by a semicolon and
3081 // optionally spaces.
3082 while (packet.GetBytesLeft() > 0) {
3083 int signal = packet.GetS32(-1, 16);
3085 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3086 signals.push_back(signal);
3088 packet.SkipSpaces();
3089 char separator = packet.GetChar();
3090 if (separator == '\0')
3091 break; // End of string
3092 if (separator != ';')
3093 return SendIllFormedResponse(packet, "Invalid separator,"
3094 " expected semicolon.");
3097 // Fail if we don't have a current process.
3098 if (!m_debugged_process_sp)
3099 return SendErrorResponse(68);
3101 Error error = m_debugged_process_sp->IgnoreSignals(signals);
3103 return SendErrorResponse(69);
3105 return SendOKResponse();
3108 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3109 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3111 // Tell the stdio connection to shut down.
3112 if (m_stdio_communication.IsConnected()) {
3113 auto connection = m_stdio_communication.GetConnection();
3116 connection->Disconnect(&error);
3118 if (error.Success()) {
3120 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3121 "terminal stdio - SUCCESS",
3125 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3126 "terminal stdio - FAIL: %s",
3127 __FUNCTION__, error.AsCString());
3133 NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3134 StringExtractorGDBRemote &packet) {
3135 NativeThreadProtocolSP thread_sp;
3137 // We have no thread if we don't have a process.
3138 if (!m_debugged_process_sp ||
3139 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3142 // If the client hasn't asked for thread suffix support, there will not be a
3144 // Use the current thread in that case.
3145 if (!m_thread_suffix_supported) {
3146 const lldb::tid_t current_tid = GetCurrentThreadID();
3147 if (current_tid == LLDB_INVALID_THREAD_ID)
3149 else if (current_tid == 0) {
3151 return m_debugged_process_sp->GetThreadAtIndex(0);
3153 return m_debugged_process_sp->GetThreadByID(current_tid);
3156 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3158 // Parse out the ';'.
3159 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3161 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3162 "error: expected ';' prior to start of thread suffix: packet "
3164 __FUNCTION__, packet.GetStringRef().c_str());
3168 if (!packet.GetBytesLeft())
3171 // Parse out thread: portion.
3172 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3174 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3175 "error: expected 'thread:' but not found, packet contents = "
3177 __FUNCTION__, packet.GetStringRef().c_str());
3180 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3181 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3183 return m_debugged_process_sp->GetThreadByID(tid);
3188 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3189 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3190 // Use whatever the debug process says is the current thread id
3191 // since the protocol either didn't specify or specified we want
3192 // any/all threads marked as the current thread.
3193 if (!m_debugged_process_sp)
3194 return LLDB_INVALID_THREAD_ID;
3195 return m_debugged_process_sp->GetCurrentThreadID();
3197 // Use the specific current thread id set by the gdb remote protocol.
3198 return m_current_tid;
3201 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3202 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3203 return m_next_saved_registers_id++;
3206 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3207 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3209 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3210 m_active_auxv_buffer_up.reset();
3214 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3215 const ArchSpec &arch) {
3216 if (m_debugged_process_sp) {
3218 if (m_debugged_process_sp
3219 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3221 if (file_spec.Exists())
3226 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);