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/Core/StreamGDBRemote.h"
23 // Other libraries and framework includes
24 #include "lldb/Core/DataBuffer.h"
25 #include "lldb/Core/Log.h"
26 #include "lldb/Core/RegisterValue.h"
27 #include "lldb/Core/State.h"
28 #include "lldb/Core/StreamString.h"
29 #include "lldb/Host/ConnectionFileDescriptor.h"
30 #include "lldb/Host/Debug.h"
31 #include "lldb/Host/Endian.h"
32 #include "lldb/Host/File.h"
33 #include "lldb/Host/FileSystem.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Host/HostInfo.h"
36 #include "lldb/Host/StringConvert.h"
37 #include "lldb/Host/common/NativeProcessProtocol.h"
38 #include "lldb/Host/common/NativeRegisterContext.h"
39 #include "lldb/Host/common/NativeThreadProtocol.h"
40 #include "lldb/Interpreter/Args.h"
41 #include "lldb/Target/FileAction.h"
42 #include "lldb/Target/MemoryRegionInfo.h"
43 #include "lldb/Utility/JSON.h"
44 #include "lldb/Utility/LLDBAssert.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"
52 #include "Utility/UriParser.h"
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
64 enum GDBRemoteServerError {
65 // Set to the first unused error number in literal form below
67 eErrorNoProcess = eErrorFirst,
73 //----------------------------------------------------------------------
74 // GDBRemoteCommunicationServerLLGS constructor
75 //----------------------------------------------------------------------
76 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
78 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
79 "gdb-remote.server.rx_packet"),
80 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
81 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
82 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
83 m_inferior_prev_state(StateType::eStateInvalid),
84 m_active_auxv_buffer_sp(), m_saved_registers_mutex(),
85 m_saved_registers_map(), m_next_saved_registers_id(1),
86 m_handshake_completed(false) {
87 RegisterPacketHandlers();
90 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
92 &GDBRemoteCommunicationServerLLGS::Handle_C);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
94 &GDBRemoteCommunicationServerLLGS::Handle_c);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
96 &GDBRemoteCommunicationServerLLGS::Handle_D);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
98 &GDBRemoteCommunicationServerLLGS::Handle_H);
99 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
100 &GDBRemoteCommunicationServerLLGS::Handle_I);
101 RegisterMemberFunctionHandler(
102 StringExtractorGDBRemote::eServerPacketType_interrupt,
103 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
104 RegisterMemberFunctionHandler(
105 StringExtractorGDBRemote::eServerPacketType_m,
106 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
108 &GDBRemoteCommunicationServerLLGS::Handle_M);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
110 &GDBRemoteCommunicationServerLLGS::Handle_p);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
112 &GDBRemoteCommunicationServerLLGS::Handle_P);
113 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
114 &GDBRemoteCommunicationServerLLGS::Handle_qC);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
117 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
120 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
123 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
129 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
132 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
135 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
138 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
141 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
144 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
147 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
156 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
157 RegisterMemberFunctionHandler(
158 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
159 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
162 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
163 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
164 &GDBRemoteCommunicationServerLLGS::Handle_s);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_stop_reason,
167 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_vAttach,
170 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_vCont,
173 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
174 RegisterMemberFunctionHandler(
175 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
176 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
177 RegisterMemberFunctionHandler(
178 StringExtractorGDBRemote::eServerPacketType_x,
179 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
181 &GDBRemoteCommunicationServerLLGS::Handle_Z);
182 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
183 &GDBRemoteCommunicationServerLLGS::Handle_z);
185 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
186 [this](StringExtractorGDBRemote packet, Error &error,
187 bool &interrupt, bool &quit) {
189 return this->Handle_k(packet);
193 Error GDBRemoteCommunicationServerLLGS::SetLaunchArguments(
194 const char *const args[], int argc) {
195 if ((argc < 1) || !args || !args[0] || !args[0][0])
196 return Error("%s: no process command line specified to launch",
199 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
203 Error GDBRemoteCommunicationServerLLGS::SetLaunchFlags(
204 unsigned int launch_flags) {
205 m_process_launch_info.GetFlags().Set(launch_flags);
209 Error GDBRemoteCommunicationServerLLGS::LaunchProcess() {
210 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
212 if (!m_process_launch_info.GetArguments().GetArgumentCount())
213 return Error("%s: no process command line specified to launch",
216 const bool should_forward_stdio =
217 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
218 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
219 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
220 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
221 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
223 const bool default_to_use_pty = true;
224 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
228 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
229 assert(!m_debugged_process_sp && "lldb-server creating debugged "
230 "process but one already exists");
231 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
232 m_mainloop, m_debugged_process_sp);
235 if (!error.Success()) {
236 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
237 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
241 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
243 // llgs local-process debugging may specify PTY paths, which will make these
244 // file actions non-null
245 // process launch -i/e/o will also make these file actions non-null
246 // nullptr means that the traffic is expected to flow over gdb-remote protocol
247 if (should_forward_stdio) {
248 // nullptr means it's not redirected to file or pty (in case of LLGS local)
249 // at least one of stdio will be transferred pty<->gdb-remote
250 // we need to give the pty master handle to this object to read and/or write
253 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
254 " setting up stdout/stderr redirection via $O gdb-remote commands",
255 __FUNCTION__, m_debugged_process_sp->GetID());
257 // Setup stdout/stderr mapping from inferior to $O
258 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
259 if (terminal_fd >= 0) {
261 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
262 "inferior STDIO fd to %d",
263 __FUNCTION__, terminal_fd);
264 error = SetSTDIOFileDescriptor(terminal_fd);
269 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
270 "inferior STDIO since terminal fd reported as %d",
271 __FUNCTION__, terminal_fd);
275 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
276 " skipping stdout/stderr redirection via $O: inferior will "
277 "communicate over client-provided file descriptors",
278 __FUNCTION__, m_debugged_process_sp->GetID());
281 printf("Launched '%s' as process %" PRIu64 "...\n",
282 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
283 m_process_launch_info.GetProcessID());
288 Error GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
291 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
293 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
296 // Before we try to attach, make sure we aren't already monitoring something
298 if (m_debugged_process_sp &&
299 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
300 return Error("cannot attach to a process %" PRIu64
301 " when another process with pid %" PRIu64
302 " is being debugged.",
303 pid, m_debugged_process_sp->GetID());
306 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
307 m_debugged_process_sp);
308 if (!error.Success()) {
309 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
310 __FUNCTION__, pid, error.AsCString());
314 // Setup stdout/stderr mapping from inferior.
315 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
316 if (terminal_fd >= 0) {
318 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
319 "inferior STDIO fd to %d",
320 __FUNCTION__, terminal_fd);
321 error = SetSTDIOFileDescriptor(terminal_fd);
326 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
327 "inferior STDIO since terminal fd reported as %d",
328 __FUNCTION__, terminal_fd);
331 printf("Attached to process %" PRIu64 "...\n", pid);
336 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
337 NativeProcessProtocol *process) {
338 assert(process && "process cannot be NULL");
339 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
341 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
342 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
343 __FUNCTION__, process->GetID(),
344 StateAsCString(process->GetState()));
348 GDBRemoteCommunication::PacketResult
349 GDBRemoteCommunicationServerLLGS::SendWResponse(
350 NativeProcessProtocol *process) {
351 assert(process && "process cannot be NULL");
352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
354 // send W notification
355 ExitType exit_type = ExitType::eExitTypeInvalid;
357 std::string exit_description;
359 const bool got_exit_info =
360 process->GetExitStatus(&exit_type, &return_code, exit_description);
361 if (!got_exit_info) {
363 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
364 ", failed to retrieve process exit status",
365 __FUNCTION__, process->GetID());
367 StreamGDBRemote response;
368 response.PutChar('E');
369 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
370 return SendPacketNoLock(response.GetString());
373 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
374 ", returning exit type %d, return code %d [%s]",
375 __FUNCTION__, process->GetID(), exit_type, return_code,
376 exit_description.c_str());
378 StreamGDBRemote response;
380 char return_type_code;
382 case ExitType::eExitTypeExit:
383 return_type_code = 'W';
385 case ExitType::eExitTypeSignal:
386 return_type_code = 'X';
388 case ExitType::eExitTypeStop:
389 return_type_code = 'S';
391 case ExitType::eExitTypeInvalid:
392 return_type_code = 'E';
395 response.PutChar(return_type_code);
397 // POSIX exit status limited to unsigned 8 bits.
398 response.PutHex8(return_code);
400 return SendPacketNoLock(response.GetString());
404 static void AppendHexValue(StreamString &response, const uint8_t *buf,
405 uint32_t buf_size, bool swap) {
408 for (i = buf_size - 1; i >= 0; i--)
409 response.PutHex8(buf[i]);
411 for (i = 0; i < buf_size; i++)
412 response.PutHex8(buf[i]);
416 static void WriteRegisterValueInHexFixedWidth(
417 StreamString &response, NativeRegisterContextSP ®_ctx_sp,
418 const RegisterInfo ®_info, const RegisterValue *reg_value_p) {
419 RegisterValue reg_value;
421 Error error = reg_ctx_sp->ReadRegister(®_info, reg_value);
423 reg_value_p = ®_value;
428 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
429 reg_value_p->GetByteSize(), false);
431 // Zero-out any unreadable values.
432 if (reg_info.byte_size > 0) {
433 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
434 AppendHexValue(response, zeros.data(), zeros.size(), false);
439 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread,
441 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
443 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
447 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
449 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
450 // Expedite all registers in the first register set (i.e. should be GPRs) that
451 // are not contained in other registers.
452 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
455 for (const uint32_t *reg_num_p = reg_set_p->registers;
456 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
457 uint32_t reg_num = *reg_num_p;
459 // Expedite only a couple of registers until we figure out why sending
462 static const uint32_t k_expedited_registers[] = {
463 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
464 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
465 static const uint32_t k_abridged_expedited_registers[] = {
466 LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM};
468 for (const uint32_t *generic_reg_p = abridged ? k_abridged_expedited_registers
469 : k_expedited_registers;
470 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
471 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
472 eRegisterKindGeneric, *generic_reg_p);
473 if (reg_num == LLDB_INVALID_REGNUM)
474 continue; // Target does not support the given register.
477 const RegisterInfo *const reg_info_p =
478 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
479 if (reg_info_p == nullptr) {
482 "%s failed to get register info for register index %" PRIu32,
483 __FUNCTION__, reg_num);
487 if (reg_info_p->value_regs != nullptr)
488 continue; // Only expedite registers that are not contained in other
491 RegisterValue reg_value;
492 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
495 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
497 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
498 reg_num, error.AsCString());
503 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
506 register_object_sp->SetObject(
507 llvm::to_string(reg_num),
508 std::make_shared<JSONString>(stream.GetString()));
511 return register_object_sp;
514 static const char *GetStopReasonString(StopReason stop_reason) {
515 switch (stop_reason) {
516 case eStopReasonTrace:
518 case eStopReasonBreakpoint:
520 case eStopReasonWatchpoint:
522 case eStopReasonSignal:
524 case eStopReasonException:
526 case eStopReasonExec:
528 case eStopReasonInstrumentation:
529 case eStopReasonInvalid:
530 case eStopReasonPlanComplete:
531 case eStopReasonThreadExiting:
532 case eStopReasonNone:
538 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
540 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
542 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
544 // Ensure we can get info on the given thread.
545 uint32_t thread_idx = 0;
546 for (NativeThreadProtocolSP thread_sp;
547 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
550 lldb::tid_t tid = thread_sp->GetID();
552 // Grab the reason this thread stopped.
553 struct ThreadStopInfo tid_stop_info;
554 std::string description;
555 if (!thread_sp->GetStopReason(tid_stop_info, description))
558 const int signum = tid_stop_info.details.signal.signo;
560 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
562 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
563 __FUNCTION__, process.GetID(), tid, signum,
564 tid_stop_info.reason, tid_stop_info.details.exception.type);
567 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
568 threads_array_sp->AppendObject(thread_obj_sp);
570 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp, abridged))
571 thread_obj_sp->SetObject("registers", registers_sp);
573 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
575 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
577 const std::string thread_name = thread_sp->GetName();
578 if (!thread_name.empty())
579 thread_obj_sp->SetObject("name",
580 std::make_shared<JSONString>(thread_name));
582 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
583 thread_obj_sp->SetObject("reason",
584 std::make_shared<JSONString>(stop_reason_str));
586 if (!description.empty())
587 thread_obj_sp->SetObject("description",
588 std::make_shared<JSONString>(description));
590 if ((tid_stop_info.reason == eStopReasonException) &&
591 tid_stop_info.details.exception.type) {
592 thread_obj_sp->SetObject(
594 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
596 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
597 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
599 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
600 tid_stop_info.details.exception.data[i]));
602 thread_obj_sp->SetObject("medata", medata_array_sp);
605 // TODO: Expedite interesting regions of inferior memory
608 return threads_array_sp;
611 GDBRemoteCommunication::PacketResult
612 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
614 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
616 // Ensure we have a debugged process.
617 if (!m_debugged_process_sp ||
618 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
619 return SendErrorResponse(50);
623 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
625 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
627 // Ensure we can get info on the given thread.
628 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
630 return SendErrorResponse(51);
632 // Grab the reason this thread stopped.
633 struct ThreadStopInfo tid_stop_info;
634 std::string description;
635 if (!thread_sp->GetStopReason(tid_stop_info, description))
636 return SendErrorResponse(52);
638 // FIXME implement register handling for exec'd inferiors.
639 // if (tid_stop_info.reason == eStopReasonExec)
641 // const bool force = true;
642 // InitializeRegisters(force);
645 StreamString response;
646 // Output the T packet with the thread
647 response.PutChar('T');
648 int signum = tid_stop_info.details.signal.signo;
650 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
652 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
653 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
654 tid_stop_info.reason, tid_stop_info.details.exception.type);
657 // Print the signal number.
658 response.PutHex8(signum & 0xff);
661 response.Printf("thread:%" PRIx64 ";", tid);
663 // Include the thread name if there is one.
664 const std::string thread_name = thread_sp->GetName();
665 if (!thread_name.empty()) {
666 size_t thread_name_len = thread_name.length();
668 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
669 response.PutCString("name:");
670 response.PutCString(thread_name);
672 // The thread name contains special chars, send as hex bytes.
673 response.PutCString("hexname:");
674 response.PutCStringAsRawHex8(thread_name.c_str());
676 response.PutChar(';');
679 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
680 // will send all thread IDs back in the "threads" key whose value is
681 // a list of hex thread IDs separated by commas:
682 // "threads:10a,10b,10c;"
683 // This will save the debugger from having to send a pair of qfThreadInfo
684 // and qsThreadInfo packets, but it also might take a lot of room in the
685 // stop reply packet, so it must be enabled only on systems where there
686 // are no limits on packet lengths.
687 if (m_list_threads_in_stop_reply) {
688 response.PutCString("threads:");
690 uint32_t thread_index = 0;
691 NativeThreadProtocolSP listed_thread_sp;
692 for (listed_thread_sp =
693 m_debugged_process_sp->GetThreadAtIndex(thread_index);
694 listed_thread_sp; ++thread_index,
695 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
697 if (thread_index > 0)
698 response.PutChar(',');
699 response.Printf("%" PRIx64, listed_thread_sp->GetID());
701 response.PutChar(';');
703 // Include JSON info that describes the stop reason for any threads
704 // that actually have stop reasons. We use the new "jstopinfo" key
705 // whose values is hex ascii JSON that contains the thread IDs
706 // thread stop info only for threads that have stop reasons. Only send
707 // this if we have more than one thread otherwise this packet has all
708 // the info it needs.
709 if (thread_index > 0) {
710 const bool threads_with_valid_stop_info_only = true;
711 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
712 *m_debugged_process_sp, threads_with_valid_stop_info_only);
713 if (threads_info_sp) {
714 response.PutCString("jstopinfo:");
715 StreamString unescaped_response;
716 threads_info_sp->Write(unescaped_response);
717 response.PutCStringAsRawHex8(unescaped_response.GetData());
718 response.PutChar(';');
720 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
721 "jstopinfo field for pid %" PRIu64,
722 __FUNCTION__, m_debugged_process_sp->GetID());
727 // Expedite registers.
730 // Grab the register context.
731 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
733 // Expedite all registers in the first register set (i.e. should be GPRs)
734 // that are not contained in other registers.
735 const RegisterSet *reg_set_p;
736 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
737 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
739 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
740 "from set '%s' (registers set count: %zu)",
742 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
743 reg_set_p->num_registers);
745 for (const uint32_t *reg_num_p = reg_set_p->registers;
746 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
747 const RegisterInfo *const reg_info_p =
748 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
749 if (reg_info_p == nullptr) {
751 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
752 "register info for register set '%s', register index "
755 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
757 } else if (reg_info_p->value_regs == nullptr) {
758 // Only expediate registers that are not contained in other registers.
759 RegisterValue reg_value;
760 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
761 if (error.Success()) {
762 response.Printf("%.02x:", *reg_num_p);
763 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
765 response.PutChar(';');
768 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
769 "register '%s' index %" PRIu32 ": %s",
770 __FUNCTION__, reg_info_p->name ? reg_info_p->name
771 : "<unnamed-register>",
772 *reg_num_p, error.AsCString());
779 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
780 if (reason_str != nullptr) {
781 response.Printf("reason:%s;", reason_str);
784 if (!description.empty()) {
785 // Description may contains special chars, send as hex bytes.
786 response.PutCString("description:");
787 response.PutCStringAsRawHex8(description.c_str());
788 response.PutChar(';');
789 } else if ((tid_stop_info.reason == eStopReasonException) &&
790 tid_stop_info.details.exception.type) {
791 response.PutCString("metype:");
792 response.PutHex64(tid_stop_info.details.exception.type);
793 response.PutCString(";mecount:");
794 response.PutHex32(tid_stop_info.details.exception.data_count);
795 response.PutChar(';');
797 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
798 response.PutCString("medata:");
799 response.PutHex64(tid_stop_info.details.exception.data[i]);
800 response.PutChar(';');
804 return SendPacketNoLock(response.GetString());
807 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
808 NativeProcessProtocol *process) {
809 assert(process && "process cannot be NULL");
811 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
813 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
815 PacketResult result = SendStopReasonForState(StateType::eStateExited);
816 if (result != PacketResult::Success) {
818 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
819 "notification for PID %" PRIu64 ", state: eStateExited",
820 __FUNCTION__, process->GetID());
823 // Close the pipe to the inferior terminal i/o if we launched it
825 MaybeCloseInferiorTerminalConnection();
827 // We are ready to exit the debug monitor.
831 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
832 NativeProcessProtocol *process) {
833 assert(process && "process cannot be NULL");
835 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
837 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
839 // Send the stop reason unless this is the stop after the
841 switch (m_inferior_prev_state) {
842 case eStateLaunching:
843 case eStateAttaching:
844 // Don't send anything per debugserver behavior.
847 // In all other cases, send the stop reason.
848 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
849 if (result != PacketResult::Success) {
851 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
852 "notification for PID %" PRIu64 ", state: eStateExited",
853 __FUNCTION__, process->GetID());
859 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
860 NativeProcessProtocol *process, lldb::StateType state) {
861 assert(process && "process cannot be NULL");
862 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
864 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
865 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
866 __FUNCTION__, process->GetID(), StateAsCString(state));
870 case StateType::eStateRunning:
871 StartSTDIOForwarding();
874 case StateType::eStateStopped:
875 // Make sure we get all of the pending stdout/stderr from the inferior
876 // and send it to the lldb host before we send the state change
879 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
881 // interfere with our protocol.
882 StopSTDIOForwarding();
883 HandleInferiorState_Stopped(process);
886 case StateType::eStateExited:
889 StopSTDIOForwarding();
890 HandleInferiorState_Exited(process);
895 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
896 "change for pid %" PRIu64 ", new state: %s",
897 __FUNCTION__, process->GetID(), StateAsCString(state));
902 // Remember the previous state reported to us.
903 m_inferior_prev_state = state;
906 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
907 ClearProcessSpecificData();
910 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
911 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
913 if (!m_handshake_completed) {
914 if (!HandshakeWithClient()) {
916 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
917 "client failed, exiting",
919 m_mainloop.RequestTermination();
922 m_handshake_completed = true;
925 bool interrupt = false;
929 const PacketResult result = GetPacketAndSendResponse(
930 std::chrono::microseconds(0), error, interrupt, done);
931 if (result == PacketResult::ErrorReplyTimeout)
932 break; // No more packets in the queue
934 if ((result != PacketResult::Success)) {
936 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
938 __FUNCTION__, error.AsCString());
939 m_mainloop.RequestTermination();
945 Error GDBRemoteCommunicationServerLLGS::InitializeConnection(
946 std::unique_ptr<Connection> &&connection) {
947 IOObjectSP read_object_sp = connection->GetReadObject();
948 GDBRemoteCommunicationServer::SetConnection(connection.release());
951 m_network_handle_up = m_mainloop.RegisterReadObject(
952 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
957 GDBRemoteCommunication::PacketResult
958 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
960 if ((buffer == nullptr) || (len == 0)) {
962 return PacketResult::Success;
965 StreamString response;
966 response.PutChar('O');
967 response.PutBytesAsRawHex8(buffer, len);
969 return SendPacketNoLock(response.GetString());
972 Error GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
975 // Set up the reading/handling of process I/O
976 std::unique_ptr<ConnectionFileDescriptor> conn_up(
977 new ConnectionFileDescriptor(fd, true));
979 error.SetErrorString("failed to create ConnectionFileDescriptor");
983 m_stdio_communication.SetCloseOnEOF(false);
984 m_stdio_communication.SetConnection(conn_up.release());
985 if (!m_stdio_communication.IsConnected()) {
986 error.SetErrorString(
987 "failed to set connection for inferior I/O communication");
994 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
995 // Don't forward if not connected (e.g. when attaching).
996 if (!m_stdio_communication.IsConnected())
1000 lldbassert(!m_stdio_handle_up);
1001 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1002 m_stdio_communication.GetConnection()->GetReadObject(),
1003 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1005 if (!m_stdio_handle_up) {
1006 // Not much we can do about the failure. Log it and continue without
1008 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1009 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1011 __FUNCTION__, error.AsCString());
1015 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1016 m_stdio_handle_up.reset();
1019 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1021 ConnectionStatus status;
1024 size_t bytes_read = m_stdio_communication.Read(
1025 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1027 case eConnectionStatusSuccess:
1028 SendONotification(buffer, bytes_read);
1030 case eConnectionStatusLostConnection:
1031 case eConnectionStatusEndOfFile:
1032 case eConnectionStatusError:
1033 case eConnectionStatusNoConnection:
1034 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1035 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1036 "forwarding as communication returned status %d (error: "
1038 __FUNCTION__, status, error.AsCString());
1039 m_stdio_handle_up.reset();
1042 case eConnectionStatusInterrupted:
1043 case eConnectionStatusTimedOut:
1049 GDBRemoteCommunication::PacketResult
1050 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1051 StringExtractorGDBRemote &packet) {
1052 // Fail if we don't have a current process.
1053 if (!m_debugged_process_sp ||
1054 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1055 return SendErrorResponse(68);
1057 lldb::pid_t pid = m_debugged_process_sp->GetID();
1059 if (pid == LLDB_INVALID_PROCESS_ID)
1060 return SendErrorResponse(1);
1062 ProcessInstanceInfo proc_info;
1063 if (!Host::GetProcessInfo(pid, proc_info))
1064 return SendErrorResponse(1);
1066 StreamString response;
1067 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1068 return SendPacketNoLock(response.GetString());
1071 GDBRemoteCommunication::PacketResult
1072 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1073 // Fail if we don't have a current process.
1074 if (!m_debugged_process_sp ||
1075 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1076 return SendErrorResponse(68);
1078 // Make sure we set the current thread so g and p packets return
1079 // the data the gdb will expect.
1080 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1081 SetCurrentThreadID(tid);
1083 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1085 return SendErrorResponse(69);
1087 StreamString response;
1088 response.Printf("QC%" PRIx64, thread_sp->GetID());
1090 return SendPacketNoLock(response.GetString());
1093 GDBRemoteCommunication::PacketResult
1094 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1095 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1097 StopSTDIOForwarding();
1099 if (!m_debugged_process_sp) {
1102 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1104 return PacketResult::Success;
1107 Error error = m_debugged_process_sp->Kill();
1108 if (error.Fail() && log)
1109 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1110 "process %" PRIu64 ": %s",
1111 __FUNCTION__, m_debugged_process_sp->GetID(),
1114 // No OK response for kill packet.
1115 // return SendOKResponse ();
1116 return PacketResult::Success;
1119 GDBRemoteCommunication::PacketResult
1120 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1121 StringExtractorGDBRemote &packet) {
1122 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1123 if (packet.GetU32(0))
1124 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1126 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1127 return SendOKResponse();
1130 GDBRemoteCommunication::PacketResult
1131 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1132 StringExtractorGDBRemote &packet) {
1133 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1135 packet.GetHexByteString(path);
1136 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1137 return SendOKResponse();
1140 GDBRemoteCommunication::PacketResult
1141 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1142 StringExtractorGDBRemote &packet) {
1143 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1145 StreamString response;
1146 response.PutCStringAsRawHex8(working_dir.GetCString());
1147 return SendPacketNoLock(response.GetString());
1150 return SendErrorResponse(14);
1153 GDBRemoteCommunication::PacketResult
1154 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1155 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1157 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1159 // Ensure we have a native process.
1160 if (!m_debugged_process_sp) {
1162 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1165 return SendErrorResponse(0x36);
1168 // Pull out the signal number.
1169 packet.SetFilePos(::strlen("C"));
1170 if (packet.GetBytesLeft() < 1) {
1171 // Shouldn't be using a C without a signal.
1172 return SendIllFormedResponse(packet, "C packet specified without signal.");
1174 const uint32_t signo =
1175 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1176 if (signo == std::numeric_limits<uint32_t>::max())
1177 return SendIllFormedResponse(packet, "failed to parse signal number");
1179 // Handle optional continue address.
1180 if (packet.GetBytesLeft() > 0) {
1181 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1182 if (*packet.Peek() == ';')
1183 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1185 return SendIllFormedResponse(
1186 packet, "unexpected content after $C{signal-number}");
1189 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1192 // We have two branches: what to do if a continue thread is specified (in
1193 // which case we target
1194 // sending the signal to that thread), or when we don't have a continue thread
1196 // case we send a signal to the process).
1198 // TODO discuss with Greg Clayton, make sure this makes sense.
1200 lldb::tid_t signal_tid = GetContinueThreadID();
1201 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1202 // The resume action for the continue thread (or all threads if a continue
1203 // thread is not set).
1204 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1205 static_cast<int>(signo)};
1207 // Add the action for the continue thread (or all threads when the continue
1208 // thread isn't present).
1209 resume_actions.Append(action);
1211 // Send the signal to the process since we weren't targeting a specific
1212 // continue thread with the signal.
1213 error = m_debugged_process_sp->Signal(signo);
1216 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1217 "signal for process %" PRIu64 ": %s",
1218 __FUNCTION__, m_debugged_process_sp->GetID(),
1221 return SendErrorResponse(0x52);
1225 // Resume the threads.
1226 error = m_debugged_process_sp->Resume(resume_actions);
1229 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1230 "threads for process %" PRIu64 ": %s",
1231 __FUNCTION__, m_debugged_process_sp->GetID(),
1234 return SendErrorResponse(0x38);
1237 // Don't send an "OK" packet; response is the stopped/exited message.
1238 return PacketResult::Success;
1241 GDBRemoteCommunication::PacketResult
1242 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1243 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1245 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1247 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1249 // For now just support all continue.
1250 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1251 if (has_continue_address) {
1253 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1254 "c{address} variant [%s remains]",
1255 __FUNCTION__, packet.Peek());
1256 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1259 // Ensure we have a native process.
1260 if (!m_debugged_process_sp) {
1262 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1265 return SendErrorResponse(0x36);
1268 // Build the ResumeActionList
1269 ResumeActionList actions(StateType::eStateRunning, 0);
1271 Error error = m_debugged_process_sp->Resume(actions);
1275 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1277 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1279 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1284 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1285 __FUNCTION__, m_debugged_process_sp->GetID());
1287 // No response required from continue.
1288 return PacketResult::Success;
1291 GDBRemoteCommunication::PacketResult
1292 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1293 StringExtractorGDBRemote &packet) {
1294 StreamString response;
1295 response.Printf("vCont;c;C;s;S");
1297 return SendPacketNoLock(response.GetString());
1300 GDBRemoteCommunication::PacketResult
1301 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1302 StringExtractorGDBRemote &packet) {
1303 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1305 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1308 packet.SetFilePos(::strlen("vCont"));
1310 if (packet.GetBytesLeft() == 0) {
1312 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1315 return SendIllFormedResponse(packet, "Missing action from vCont package");
1318 // Check if this is all continue (no options or ";c").
1319 if (::strcmp(packet.Peek(), ";c") == 0) {
1320 // Move past the ';', then do a simple 'c'.
1321 packet.SetFilePos(packet.GetFilePos() + 1);
1322 return Handle_c(packet);
1323 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1324 // Move past the ';', then do a simple 's'.
1325 packet.SetFilePos(packet.GetFilePos() + 1);
1326 return Handle_s(packet);
1329 // Ensure we have a native process.
1330 if (!m_debugged_process_sp) {
1332 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1335 return SendErrorResponse(0x36);
1338 ResumeActionList thread_actions;
1340 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1341 // Skip the semi-colon.
1344 // Build up the thread action.
1345 ResumeAction thread_action;
1346 thread_action.tid = LLDB_INVALID_THREAD_ID;
1347 thread_action.state = eStateInvalid;
1348 thread_action.signal = 0;
1350 const char action = packet.GetChar();
1353 thread_action.signal = packet.GetHexMaxU32(false, 0);
1354 if (thread_action.signal == 0)
1355 return SendIllFormedResponse(
1356 packet, "Could not parse signal in vCont packet C action");
1361 thread_action.state = eStateRunning;
1365 thread_action.signal = packet.GetHexMaxU32(false, 0);
1366 if (thread_action.signal == 0)
1367 return SendIllFormedResponse(
1368 packet, "Could not parse signal in vCont packet S action");
1373 thread_action.state = eStateStepping;
1377 return SendIllFormedResponse(packet, "Unsupported vCont action");
1381 // Parse out optional :{thread-id} value.
1382 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1383 // Consume the separator.
1386 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1387 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1388 return SendIllFormedResponse(
1389 packet, "Could not parse thread number in vCont packet");
1392 thread_actions.Append(thread_action);
1395 Error error = m_debugged_process_sp->Resume(thread_actions);
1398 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1399 "process %" PRIu64 ": %s",
1400 __FUNCTION__, m_debugged_process_sp->GetID(),
1403 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1408 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1409 __FUNCTION__, m_debugged_process_sp->GetID());
1411 // No response required from vCont.
1412 return PacketResult::Success;
1415 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1416 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1418 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1422 m_current_tid = tid;
1423 if (m_debugged_process_sp)
1424 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1427 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1428 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1430 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1434 m_continue_tid = tid;
1437 GDBRemoteCommunication::PacketResult
1438 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1439 StringExtractorGDBRemote &packet) {
1440 // Handle the $? gdbremote command.
1442 // If no process, indicate error
1443 if (!m_debugged_process_sp)
1444 return SendErrorResponse(02);
1446 return SendStopReasonForState(m_debugged_process_sp->GetState());
1449 GDBRemoteCommunication::PacketResult
1450 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1451 lldb::StateType process_state) {
1452 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1454 switch (process_state) {
1455 case eStateAttaching:
1456 case eStateLaunching:
1458 case eStateStepping:
1459 case eStateDetached:
1460 // NOTE: gdb protocol doc looks like it should return $OK
1461 // when everything is running (i.e. no stopped result).
1462 return PacketResult::Success; // Ignore
1464 case eStateSuspended:
1466 case eStateCrashed: {
1467 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1468 // Make sure we set the current thread so g and p packets return
1469 // the data the gdb will expect.
1470 SetCurrentThreadID(tid);
1471 return SendStopReplyPacketForThread(tid);
1475 case eStateUnloaded:
1477 return SendWResponse(m_debugged_process_sp.get());
1481 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1482 ", current state reporting not handled: %s",
1483 __FUNCTION__, m_debugged_process_sp->GetID(),
1484 StateAsCString(process_state));
1489 return SendErrorResponse(0);
1492 GDBRemoteCommunication::PacketResult
1493 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1494 StringExtractorGDBRemote &packet) {
1495 // Fail if we don't have a current process.
1496 if (!m_debugged_process_sp ||
1497 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1498 return SendErrorResponse(68);
1500 // Ensure we have a thread.
1501 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1503 return SendErrorResponse(69);
1505 // Get the register context for the first thread.
1506 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1507 if (!reg_context_sp)
1508 return SendErrorResponse(69);
1510 // Parse out the register number from the request.
1511 packet.SetFilePos(strlen("qRegisterInfo"));
1512 const uint32_t reg_index =
1513 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1514 if (reg_index == std::numeric_limits<uint32_t>::max())
1515 return SendErrorResponse(69);
1517 // Return the end of registers response if we've iterated one past the end of
1518 // the register set.
1519 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1520 return SendErrorResponse(69);
1522 const RegisterInfo *reg_info =
1523 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1525 return SendErrorResponse(69);
1527 // Build the reginfos response.
1528 StreamGDBRemote response;
1530 response.PutCString("name:");
1531 response.PutCString(reg_info->name);
1532 response.PutChar(';');
1534 if (reg_info->alt_name && reg_info->alt_name[0]) {
1535 response.PutCString("alt-name:");
1536 response.PutCString(reg_info->alt_name);
1537 response.PutChar(';');
1540 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1541 reg_info->byte_size * 8, reg_info->byte_offset);
1543 switch (reg_info->encoding) {
1545 response.PutCString("encoding:uint;");
1548 response.PutCString("encoding:sint;");
1550 case eEncodingIEEE754:
1551 response.PutCString("encoding:ieee754;");
1553 case eEncodingVector:
1554 response.PutCString("encoding:vector;");
1560 switch (reg_info->format) {
1562 response.PutCString("format:binary;");
1564 case eFormatDecimal:
1565 response.PutCString("format:decimal;");
1568 response.PutCString("format:hex;");
1571 response.PutCString("format:float;");
1573 case eFormatVectorOfSInt8:
1574 response.PutCString("format:vector-sint8;");
1576 case eFormatVectorOfUInt8:
1577 response.PutCString("format:vector-uint8;");
1579 case eFormatVectorOfSInt16:
1580 response.PutCString("format:vector-sint16;");
1582 case eFormatVectorOfUInt16:
1583 response.PutCString("format:vector-uint16;");
1585 case eFormatVectorOfSInt32:
1586 response.PutCString("format:vector-sint32;");
1588 case eFormatVectorOfUInt32:
1589 response.PutCString("format:vector-uint32;");
1591 case eFormatVectorOfFloat32:
1592 response.PutCString("format:vector-float32;");
1594 case eFormatVectorOfUInt64:
1595 response.PutCString("format:vector-uint64;");
1597 case eFormatVectorOfUInt128:
1598 response.PutCString("format:vector-uint128;");
1604 const char *const register_set_name =
1605 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1606 if (register_set_name) {
1607 response.PutCString("set:");
1608 response.PutCString(register_set_name);
1609 response.PutChar(';');
1612 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1613 LLDB_INVALID_REGNUM)
1614 response.Printf("ehframe:%" PRIu32 ";",
1615 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1617 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1618 response.Printf("dwarf:%" PRIu32 ";",
1619 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1621 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1622 case LLDB_REGNUM_GENERIC_PC:
1623 response.PutCString("generic:pc;");
1625 case LLDB_REGNUM_GENERIC_SP:
1626 response.PutCString("generic:sp;");
1628 case LLDB_REGNUM_GENERIC_FP:
1629 response.PutCString("generic:fp;");
1631 case LLDB_REGNUM_GENERIC_RA:
1632 response.PutCString("generic:ra;");
1634 case LLDB_REGNUM_GENERIC_FLAGS:
1635 response.PutCString("generic:flags;");
1637 case LLDB_REGNUM_GENERIC_ARG1:
1638 response.PutCString("generic:arg1;");
1640 case LLDB_REGNUM_GENERIC_ARG2:
1641 response.PutCString("generic:arg2;");
1643 case LLDB_REGNUM_GENERIC_ARG3:
1644 response.PutCString("generic:arg3;");
1646 case LLDB_REGNUM_GENERIC_ARG4:
1647 response.PutCString("generic:arg4;");
1649 case LLDB_REGNUM_GENERIC_ARG5:
1650 response.PutCString("generic:arg5;");
1652 case LLDB_REGNUM_GENERIC_ARG6:
1653 response.PutCString("generic:arg6;");
1655 case LLDB_REGNUM_GENERIC_ARG7:
1656 response.PutCString("generic:arg7;");
1658 case LLDB_REGNUM_GENERIC_ARG8:
1659 response.PutCString("generic:arg8;");
1665 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1666 response.PutCString("container-regs:");
1668 for (const uint32_t *reg_num = reg_info->value_regs;
1669 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1671 response.PutChar(',');
1672 response.Printf("%" PRIx32, *reg_num);
1674 response.PutChar(';');
1677 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1678 response.PutCString("invalidate-regs:");
1680 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1681 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1683 response.PutChar(',');
1684 response.Printf("%" PRIx32, *reg_num);
1686 response.PutChar(';');
1689 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1690 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1691 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1692 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1693 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1694 response.PutChar(';');
1696 return SendPacketNoLock(response.GetString());
1699 GDBRemoteCommunication::PacketResult
1700 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1701 StringExtractorGDBRemote &packet) {
1702 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1704 // Fail if we don't have a current process.
1705 if (!m_debugged_process_sp ||
1706 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1708 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1711 m_debugged_process_sp ? "invalid process id"
1712 : "null m_debugged_process_sp");
1713 return SendOKResponse();
1716 StreamGDBRemote response;
1717 response.PutChar('m');
1721 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1724 NativeThreadProtocolSP thread_sp;
1725 uint32_t thread_index;
1726 for (thread_index = 0,
1727 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1728 thread_sp; ++thread_index,
1729 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1732 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1733 "(%s, tid=0x%" PRIx64 ")",
1734 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1735 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1736 if (thread_index > 0)
1737 response.PutChar(',');
1738 response.Printf("%" PRIx64, thread_sp->GetID());
1743 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1746 return SendPacketNoLock(response.GetString());
1749 GDBRemoteCommunication::PacketResult
1750 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1751 StringExtractorGDBRemote &packet) {
1752 // FIXME for now we return the full thread list in the initial packet and
1753 // always do nothing here.
1754 return SendPacketNoLock("l");
1757 GDBRemoteCommunication::PacketResult
1758 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1759 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1761 // Parse out the register number from the request.
1762 packet.SetFilePos(strlen("p"));
1763 const uint32_t reg_index =
1764 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1765 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1767 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1768 "parse register number from request \"%s\"",
1769 __FUNCTION__, packet.GetStringRef().c_str());
1770 return SendErrorResponse(0x15);
1773 // Get the thread to use.
1774 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1778 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
1780 return SendErrorResponse(0x15);
1783 // Get the thread's register context.
1784 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1785 if (!reg_context_sp) {
1788 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1789 " failed, no register context available for the thread",
1790 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1791 return SendErrorResponse(0x15);
1794 // Return the end of registers response if we've iterated one past the end of
1795 // the register set.
1796 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1798 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1799 "register %" PRIu32 " beyond register count %" PRIu32,
1800 __FUNCTION__, reg_index,
1801 reg_context_sp->GetUserRegisterCount());
1802 return SendErrorResponse(0x15);
1805 const RegisterInfo *reg_info =
1806 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1809 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1810 "register %" PRIu32 " returned NULL",
1811 __FUNCTION__, reg_index);
1812 return SendErrorResponse(0x15);
1815 // Build the reginfos response.
1816 StreamGDBRemote response;
1818 // Retrieve the value
1819 RegisterValue reg_value;
1820 Error error = reg_context_sp->ReadRegister(reg_info, reg_value);
1823 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1824 "requested register %" PRIu32 " (%s) failed: %s",
1825 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1826 return SendErrorResponse(0x15);
1829 const uint8_t *const data =
1830 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1833 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1834 "bytes from requested register %" PRIu32,
1835 __FUNCTION__, reg_index);
1836 return SendErrorResponse(0x15);
1839 // FIXME flip as needed to get data in big/little endian format for this host.
1840 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1841 response.PutHex8(data[i]);
1843 return SendPacketNoLock(response.GetString());
1846 GDBRemoteCommunication::PacketResult
1847 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1848 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1850 // Ensure there is more content.
1851 if (packet.GetBytesLeft() < 1)
1852 return SendIllFormedResponse(packet, "Empty P packet");
1854 // Parse out the register number from the request.
1855 packet.SetFilePos(strlen("P"));
1856 const uint32_t reg_index =
1857 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1858 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1860 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1861 "parse register number from request \"%s\"",
1862 __FUNCTION__, packet.GetStringRef().c_str());
1863 return SendErrorResponse(0x29);
1866 // Note debugserver would send an E30 here.
1867 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
1868 return SendIllFormedResponse(
1869 packet, "P packet missing '=' char after register number");
1871 // Get process architecture.
1872 ArchSpec process_arch;
1873 if (!m_debugged_process_sp ||
1874 !m_debugged_process_sp->GetArchitecture(process_arch)) {
1876 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
1877 "inferior architecture",
1879 return SendErrorResponse(0x49);
1882 // Parse out the value.
1883 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1884 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
1886 // Get the thread to use.
1887 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1890 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
1891 "available (thread index 0)",
1893 return SendErrorResponse(0x28);
1896 // Get the thread's register context.
1897 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1898 if (!reg_context_sp) {
1901 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1902 " failed, no register context available for the thread",
1903 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1904 return SendErrorResponse(0x15);
1907 const RegisterInfo *reg_info =
1908 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1911 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1912 "register %" PRIu32 " returned NULL",
1913 __FUNCTION__, reg_index);
1914 return SendErrorResponse(0x48);
1917 // Return the end of registers response if we've iterated one past the end of
1918 // the register set.
1919 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1921 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1922 "register %" PRIu32 " beyond register count %" PRIu32,
1923 __FUNCTION__, reg_index,
1924 reg_context_sp->GetUserRegisterCount());
1925 return SendErrorResponse(0x47);
1928 // The dwarf expression are evaluate on host site
1929 // which may cause register size to change
1930 // Hence the reg_size may not be same as reg_info->bytes_size
1931 if ((reg_size != reg_info->byte_size) &&
1932 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
1933 return SendIllFormedResponse(packet, "P packet register size is incorrect");
1936 // Build the reginfos response.
1937 StreamGDBRemote response;
1939 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
1940 Error error = reg_context_sp->WriteRegister(reg_info, reg_value);
1943 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
1944 "requested register %" PRIu32 " (%s) failed: %s",
1945 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1946 return SendErrorResponse(0x32);
1949 return SendOKResponse();
1952 GDBRemoteCommunication::PacketResult
1953 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
1954 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1956 // Fail if we don't have a current process.
1957 if (!m_debugged_process_sp ||
1958 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1961 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
1963 return SendErrorResponse(0x15);
1966 // Parse out which variant of $H is requested.
1967 packet.SetFilePos(strlen("H"));
1968 if (packet.GetBytesLeft() < 1) {
1970 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
1971 "missing {g,c} variant",
1973 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
1976 const char h_variant = packet.GetChar();
1977 switch (h_variant) {
1987 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
1988 __FUNCTION__, h_variant);
1989 return SendIllFormedResponse(packet,
1990 "H variant unsupported, should be c or g");
1993 // Parse out the thread number.
1994 // FIXME return a parse success/fail value. All values are valid here.
1995 const lldb::tid_t tid =
1996 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
1998 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2000 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2001 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2004 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2007 return SendErrorResponse(0x15);
2011 // Now switch the given thread type.
2012 switch (h_variant) {
2014 SetCurrentThreadID(tid);
2018 SetContinueThreadID(tid);
2022 assert(false && "unsupported $H variant - shouldn't get here");
2023 return SendIllFormedResponse(packet,
2024 "H variant unsupported, should be c or g");
2027 return SendOKResponse();
2030 GDBRemoteCommunication::PacketResult
2031 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2032 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2034 // Fail if we don't have a current process.
2035 if (!m_debugged_process_sp ||
2036 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2039 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2041 return SendErrorResponse(0x15);
2044 packet.SetFilePos(::strlen("I"));
2047 size_t read = packet.GetHexBytesAvail(tmp);
2051 // write directly to stdin *this might block if stdin buffer is full*
2052 // TODO: enqueue this block in circular buffer and send window size to
2054 ConnectionStatus status;
2056 m_stdio_communication.Write(tmp, read, status, &error);
2058 return SendErrorResponse(0x15);
2062 return SendOKResponse();
2065 GDBRemoteCommunication::PacketResult
2066 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2067 StringExtractorGDBRemote &packet) {
2068 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 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 // Interrupt the process.
2081 Error error = m_debugged_process_sp->Interrupt();
2085 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2087 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
2089 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2093 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2094 __FUNCTION__, m_debugged_process_sp->GetID());
2096 // No response required from stop all.
2097 return PacketResult::Success;
2100 GDBRemoteCommunication::PacketResult
2101 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2102 StringExtractorGDBRemote &packet) {
2103 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2105 if (!m_debugged_process_sp ||
2106 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2109 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2111 return SendErrorResponse(0x15);
2114 // Parse out the memory address.
2115 packet.SetFilePos(strlen("m"));
2116 if (packet.GetBytesLeft() < 1)
2117 return SendIllFormedResponse(packet, "Too short m packet");
2119 // Read the address. Punting on validation.
2120 // FIXME replace with Hex U64 read with no default value that fails on failed
2122 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2125 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2126 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2128 // Get # bytes to read.
2129 if (packet.GetBytesLeft() < 1)
2130 return SendIllFormedResponse(packet, "Length missing in m packet");
2132 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2133 if (byte_count == 0) {
2135 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2136 "zero-length packet",
2138 return SendOKResponse();
2141 // Allocate the response buffer.
2142 std::string buf(byte_count, '\0');
2144 return SendErrorResponse(0x78);
2146 // Retrieve the process memory.
2147 size_t bytes_read = 0;
2148 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2149 read_addr, &buf[0], byte_count, bytes_read);
2152 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2153 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2154 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2156 return SendErrorResponse(0x08);
2159 if (bytes_read == 0) {
2161 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2162 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2163 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2165 return SendErrorResponse(0x08);
2168 StreamGDBRemote response;
2169 packet.SetFilePos(0);
2170 char kind = packet.GetChar('?');
2172 response.PutEscapedBytes(buf.data(), byte_count);
2174 assert(kind == 'm');
2175 for (size_t i = 0; i < bytes_read; ++i)
2176 response.PutHex8(buf[i]);
2179 return SendPacketNoLock(response.GetString());
2182 GDBRemoteCommunication::PacketResult
2183 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2184 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2186 if (!m_debugged_process_sp ||
2187 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2190 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2192 return SendErrorResponse(0x15);
2195 // Parse out the memory address.
2196 packet.SetFilePos(strlen("M"));
2197 if (packet.GetBytesLeft() < 1)
2198 return SendIllFormedResponse(packet, "Too short M packet");
2200 // Read the address. Punting on validation.
2201 // FIXME replace with Hex U64 read with no default value that fails on failed
2203 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2206 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2207 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2209 // Get # bytes to read.
2210 if (packet.GetBytesLeft() < 1)
2211 return SendIllFormedResponse(packet, "Length missing in M packet");
2213 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2214 if (byte_count == 0) {
2216 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2217 "zero-length packet",
2219 return PacketResult::Success;
2223 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2224 return SendIllFormedResponse(
2225 packet, "Comma sep missing in M packet after byte length");
2227 // Allocate the conversion buffer.
2228 std::vector<uint8_t> buf(byte_count, 0);
2230 return SendErrorResponse(0x78);
2232 // Convert the hex memory write contents to bytes.
2233 StreamGDBRemote response;
2234 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2235 if (convert_count != byte_count) {
2237 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2238 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2239 " bytes, but only found %" PRIu64 " to convert.",
2240 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2241 byte_count, convert_count);
2242 return SendIllFormedResponse(packet, "M content byte length specified did "
2243 "not match hex-encoded content "
2247 // Write the process memory.
2248 size_t bytes_written = 0;
2249 Error error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2250 byte_count, bytes_written);
2253 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2254 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2255 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2257 return SendErrorResponse(0x09);
2260 if (bytes_written == 0) {
2262 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2263 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2264 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2266 return SendErrorResponse(0x09);
2269 return SendOKResponse();
2272 GDBRemoteCommunication::PacketResult
2273 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2274 StringExtractorGDBRemote &packet) {
2275 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2277 // Currently only the NativeProcessProtocol knows if it can handle a
2278 // qMemoryRegionInfoSupported
2279 // request, but we're not guaranteed to be attached to a process. For now
2281 // client only asks this when a process is being debugged.
2283 // Ensure we have a process running; otherwise, we can't figure this out
2284 // since we won't have a NativeProcessProtocol.
2285 if (!m_debugged_process_sp ||
2286 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2289 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2291 return SendErrorResponse(0x15);
2294 // Test if we can get any region back when asking for the region around NULL.
2295 MemoryRegionInfo region_info;
2297 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2299 // We don't support memory region info collection for this
2300 // NativeProcessProtocol.
2301 return SendUnimplementedResponse("");
2304 return SendOKResponse();
2307 GDBRemoteCommunication::PacketResult
2308 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2309 StringExtractorGDBRemote &packet) {
2310 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2312 // Ensure we have a process.
2313 if (!m_debugged_process_sp ||
2314 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2317 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2319 return SendErrorResponse(0x15);
2322 // Parse out the memory address.
2323 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2324 if (packet.GetBytesLeft() < 1)
2325 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2327 // Read the address. Punting on validation.
2328 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2330 StreamGDBRemote response;
2332 // Get the memory region info for the target address.
2333 MemoryRegionInfo region_info;
2335 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2337 // Return the error message.
2339 response.PutCString("error:");
2340 response.PutCStringAsRawHex8(error.AsCString());
2341 response.PutChar(';');
2343 // Range start and size.
2344 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2345 region_info.GetRange().GetRangeBase(),
2346 region_info.GetRange().GetByteSize());
2349 if (region_info.GetReadable() || region_info.GetWritable() ||
2350 region_info.GetExecutable()) {
2351 // Write permissions info.
2352 response.PutCString("permissions:");
2354 if (region_info.GetReadable())
2355 response.PutChar('r');
2356 if (region_info.GetWritable())
2357 response.PutChar('w');
2358 if (region_info.GetExecutable())
2359 response.PutChar('x');
2361 response.PutChar(';');
2365 ConstString name = region_info.GetName();
2367 response.PutCString("name:");
2368 response.PutCStringAsRawHex8(name.AsCString());
2369 response.PutChar(';');
2373 return SendPacketNoLock(response.GetString());
2376 GDBRemoteCommunication::PacketResult
2377 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2378 // Ensure we have a process.
2379 if (!m_debugged_process_sp ||
2380 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2384 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2386 return SendErrorResponse(0x15);
2389 // Parse out software or hardware breakpoint or watchpoint requested.
2390 packet.SetFilePos(strlen("Z"));
2391 if (packet.GetBytesLeft() < 1)
2392 return SendIllFormedResponse(
2393 packet, "Too short Z packet, missing software/hardware specifier");
2395 bool want_breakpoint = true;
2396 bool want_hardware = false;
2397 uint32_t watch_flags = 0;
2399 const GDBStoppointType stoppoint_type =
2400 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2401 switch (stoppoint_type) {
2402 case eBreakpointSoftware:
2403 want_hardware = false;
2404 want_breakpoint = true;
2406 case eBreakpointHardware:
2407 want_hardware = true;
2408 want_breakpoint = true;
2410 case eWatchpointWrite:
2412 want_hardware = true;
2413 want_breakpoint = false;
2415 case eWatchpointRead:
2417 want_hardware = true;
2418 want_breakpoint = false;
2420 case eWatchpointReadWrite:
2422 want_hardware = true;
2423 want_breakpoint = false;
2425 case eStoppointInvalid:
2426 return SendIllFormedResponse(
2427 packet, "Z packet had invalid software/hardware specifier");
2430 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2431 return SendIllFormedResponse(
2432 packet, "Malformed Z packet, expecting comma after stoppoint type");
2434 // Parse out the stoppoint address.
2435 if (packet.GetBytesLeft() < 1)
2436 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2437 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2439 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2440 return SendIllFormedResponse(
2441 packet, "Malformed Z packet, expecting comma after address");
2443 // Parse out the stoppoint size (i.e. size hint for opcode size).
2444 const uint32_t size =
2445 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2446 if (size == std::numeric_limits<uint32_t>::max())
2447 return SendIllFormedResponse(
2448 packet, "Malformed Z packet, failed to parse size argument");
2450 if (want_breakpoint) {
2451 // Try to set the breakpoint.
2453 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2454 if (error.Success())
2455 return SendOKResponse();
2456 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2458 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2459 " failed to set breakpoint: %s",
2460 __FUNCTION__, m_debugged_process_sp->GetID(),
2462 return SendErrorResponse(0x09);
2464 // Try to set the watchpoint.
2465 const Error error = m_debugged_process_sp->SetWatchpoint(
2466 addr, size, watch_flags, want_hardware);
2467 if (error.Success())
2468 return SendOKResponse();
2469 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2471 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2472 " failed to set watchpoint: %s",
2473 __FUNCTION__, m_debugged_process_sp->GetID(),
2475 return SendErrorResponse(0x09);
2479 GDBRemoteCommunication::PacketResult
2480 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2481 // Ensure we have a process.
2482 if (!m_debugged_process_sp ||
2483 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2484 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2487 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2489 return SendErrorResponse(0x15);
2492 // Parse out software or hardware breakpoint or watchpoint requested.
2493 packet.SetFilePos(strlen("z"));
2494 if (packet.GetBytesLeft() < 1)
2495 return SendIllFormedResponse(
2496 packet, "Too short z packet, missing software/hardware specifier");
2498 bool want_breakpoint = true;
2500 const GDBStoppointType stoppoint_type =
2501 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2502 switch (stoppoint_type) {
2503 case eBreakpointHardware:
2504 want_breakpoint = true;
2506 case eBreakpointSoftware:
2507 want_breakpoint = true;
2509 case eWatchpointWrite:
2510 want_breakpoint = false;
2512 case eWatchpointRead:
2513 want_breakpoint = false;
2515 case eWatchpointReadWrite:
2516 want_breakpoint = false;
2519 return SendIllFormedResponse(
2520 packet, "z packet had invalid software/hardware specifier");
2523 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2524 return SendIllFormedResponse(
2525 packet, "Malformed z packet, expecting comma after stoppoint type");
2527 // Parse out the stoppoint address.
2528 if (packet.GetBytesLeft() < 1)
2529 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2530 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2532 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2533 return SendIllFormedResponse(
2534 packet, "Malformed z packet, expecting comma after address");
2537 // Parse out the stoppoint size (i.e. size hint for opcode size).
2538 const uint32_t size = packet.GetHexMaxU32 (false,
2539 std::numeric_limits<uint32_t>::max ());
2540 if (size == std::numeric_limits<uint32_t>::max ())
2541 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2545 if (want_breakpoint) {
2546 // Try to clear the breakpoint.
2547 const Error error = m_debugged_process_sp->RemoveBreakpoint(addr);
2548 if (error.Success())
2549 return SendOKResponse();
2550 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2552 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2553 " failed to remove breakpoint: %s",
2554 __FUNCTION__, m_debugged_process_sp->GetID(),
2556 return SendErrorResponse(0x09);
2558 // Try to clear the watchpoint.
2559 const Error error = m_debugged_process_sp->RemoveWatchpoint(addr);
2560 if (error.Success())
2561 return SendOKResponse();
2562 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2564 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2565 " failed to remove watchpoint: %s",
2566 __FUNCTION__, m_debugged_process_sp->GetID(),
2568 return SendErrorResponse(0x09);
2572 GDBRemoteCommunication::PacketResult
2573 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2574 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2576 // Ensure we have a process.
2577 if (!m_debugged_process_sp ||
2578 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2581 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2583 return SendErrorResponse(0x32);
2586 // We first try to use a continue thread id. If any one or any all set, use
2587 // the current thread.
2588 // Bail out if we don't have a thread id.
2589 lldb::tid_t tid = GetContinueThreadID();
2590 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2591 tid = GetCurrentThreadID();
2592 if (tid == LLDB_INVALID_THREAD_ID)
2593 return SendErrorResponse(0x33);
2595 // Double check that we have such a thread.
2596 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2597 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2598 if (!thread_sp || thread_sp->GetID() != tid)
2599 return SendErrorResponse(0x33);
2601 // Create the step action for the given thread.
2602 ResumeAction action = {tid, eStateStepping, 0};
2604 // Setup the actions list.
2605 ResumeActionList actions;
2606 actions.Append(action);
2608 // All other threads stop while we're single stepping a thread.
2609 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2610 Error error = m_debugged_process_sp->Resume(actions);
2613 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2614 " tid %" PRIu64 " Resume() failed with error: %s",
2615 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2617 return SendErrorResponse(0x49);
2620 // No response here - the stop or exit will come from the resulting action.
2621 return PacketResult::Success;
2624 GDBRemoteCommunication::PacketResult
2625 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2626 StringExtractorGDBRemote &packet) {
2627 // *BSD impls should be able to do this too.
2628 #if defined(__linux__)
2629 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2631 // Parse out the offset.
2632 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2633 if (packet.GetBytesLeft() < 1)
2634 return SendIllFormedResponse(packet,
2635 "qXfer:auxv:read:: packet missing offset");
2637 const uint64_t auxv_offset =
2638 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2639 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2640 return SendIllFormedResponse(packet,
2641 "qXfer:auxv:read:: packet missing offset");
2644 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2645 return SendIllFormedResponse(
2646 packet, "qXfer:auxv:read:: packet missing comma after offset");
2648 // Parse out the length.
2649 const uint64_t auxv_length =
2650 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2651 if (auxv_length == std::numeric_limits<uint64_t>::max())
2652 return SendIllFormedResponse(packet,
2653 "qXfer:auxv:read:: packet missing length");
2655 // Grab the auxv data if we need it.
2656 if (!m_active_auxv_buffer_sp) {
2657 // Make sure we have a valid process.
2658 if (!m_debugged_process_sp ||
2659 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2662 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2664 return SendErrorResponse(0x10);
2667 // Grab the auxv data.
2668 m_active_auxv_buffer_sp = Host::GetAuxvData(m_debugged_process_sp->GetID());
2669 if (!m_active_auxv_buffer_sp ||
2670 m_active_auxv_buffer_sp->GetByteSize() == 0) {
2671 // Hmm, no auxv data, call that an error.
2673 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data "
2676 m_active_auxv_buffer_sp.reset();
2677 return SendErrorResponse(0x11);
2681 // FIXME find out if/how I lock the stream here.
2683 StreamGDBRemote response;
2684 bool done_with_buffer = false;
2686 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize()) {
2687 // We have nothing left to send. Mark the buffer as complete.
2688 response.PutChar('l');
2689 done_with_buffer = true;
2691 // Figure out how many bytes are available starting at the given offset.
2692 const uint64_t bytes_remaining =
2693 m_active_auxv_buffer_sp->GetByteSize() - auxv_offset;
2695 // Figure out how many bytes we're going to read.
2696 const uint64_t bytes_to_read =
2697 (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2699 // Mark the response type according to whether we're reading the remainder
2700 // of the auxv data.
2701 if (bytes_to_read >= bytes_remaining) {
2702 // There will be nothing left to read after this
2703 response.PutChar('l');
2704 done_with_buffer = true;
2706 // There will still be bytes to read after this request.
2707 response.PutChar('m');
2710 // Now write the data in encoded binary form.
2711 response.PutEscapedBytes(m_active_auxv_buffer_sp->GetBytes() + auxv_offset,
2715 if (done_with_buffer)
2716 m_active_auxv_buffer_sp.reset();
2718 return SendPacketNoLock(response.GetString());
2720 return SendUnimplementedResponse("not implemented on this platform");
2724 GDBRemoteCommunication::PacketResult
2725 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2726 StringExtractorGDBRemote &packet) {
2727 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2729 // Move past packet name.
2730 packet.SetFilePos(strlen("QSaveRegisterState"));
2732 // Get the thread to use.
2733 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2735 if (m_thread_suffix_supported)
2736 return SendIllFormedResponse(
2737 packet, "No thread specified in QSaveRegisterState packet");
2739 return SendIllFormedResponse(packet,
2740 "No thread was is set with the Hg packet");
2743 // Grab the register context for the thread.
2744 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2745 if (!reg_context_sp) {
2748 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2749 " failed, no register context available for the thread",
2750 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2751 return SendErrorResponse(0x15);
2754 // Save registers to a buffer.
2755 DataBufferSP register_data_sp;
2756 Error error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
2759 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2760 " failed to save all register values: %s",
2761 __FUNCTION__, m_debugged_process_sp->GetID(),
2763 return SendErrorResponse(0x75);
2766 // Allocate a new save id.
2767 const uint32_t save_id = GetNextSavedRegistersID();
2768 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2769 "GetNextRegisterSaveID() returned an existing register save id");
2771 // Save the register data buffer under the save id.
2773 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2774 m_saved_registers_map[save_id] = register_data_sp;
2777 // Write the response.
2778 StreamGDBRemote response;
2779 response.Printf("%" PRIu32, save_id);
2780 return SendPacketNoLock(response.GetString());
2783 GDBRemoteCommunication::PacketResult
2784 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2785 StringExtractorGDBRemote &packet) {
2786 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2788 // Parse out save id.
2789 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2790 if (packet.GetBytesLeft() < 1)
2791 return SendIllFormedResponse(
2792 packet, "QRestoreRegisterState packet missing register save id");
2794 const uint32_t save_id = packet.GetU32(0);
2797 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
2798 "packet has malformed save id, expecting decimal uint32_t",
2800 return SendErrorResponse(0x76);
2803 // Get the thread to use.
2804 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2806 if (m_thread_suffix_supported)
2807 return SendIllFormedResponse(
2808 packet, "No thread specified in QRestoreRegisterState packet");
2810 return SendIllFormedResponse(packet,
2811 "No thread was is set with the Hg packet");
2814 // Grab the register context for the thread.
2815 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2816 if (!reg_context_sp) {
2819 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2820 " failed, no register context available for the thread",
2821 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2822 return SendErrorResponse(0x15);
2825 // Retrieve register state buffer, then remove from the list.
2826 DataBufferSP register_data_sp;
2828 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2830 // Find the register set buffer for the given save id.
2831 auto it = m_saved_registers_map.find(save_id);
2832 if (it == m_saved_registers_map.end()) {
2834 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2835 " does not have a register set save buffer for id %" PRIu32,
2836 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
2837 return SendErrorResponse(0x77);
2839 register_data_sp = it->second;
2841 // Remove it from the map.
2842 m_saved_registers_map.erase(it);
2845 Error error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
2848 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2849 " failed to restore all register values: %s",
2850 __FUNCTION__, m_debugged_process_sp->GetID(),
2852 return SendErrorResponse(0x77);
2855 return SendOKResponse();
2858 GDBRemoteCommunication::PacketResult
2859 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2860 StringExtractorGDBRemote &packet) {
2861 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2863 // Consume the ';' after vAttach.
2864 packet.SetFilePos(strlen("vAttach"));
2865 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2866 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2868 // Grab the PID to which we will attach (assume hex encoding).
2869 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2870 if (pid == LLDB_INVALID_PROCESS_ID)
2871 return SendIllFormedResponse(packet,
2872 "vAttach failed to parse the process id");
2874 // Attempt to attach.
2876 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2880 Error error = AttachToProcess(pid);
2884 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2885 "pid %" PRIu64 ": %s\n",
2886 __FUNCTION__, pid, error.AsCString());
2887 return SendErrorResponse(0x01);
2890 // Notify we attached by sending a stop packet.
2891 return SendStopReasonForState(m_debugged_process_sp->GetState());
2894 GDBRemoteCommunication::PacketResult
2895 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2896 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2898 StopSTDIOForwarding();
2900 // Fail if we don't have a current process.
2901 if (!m_debugged_process_sp ||
2902 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2905 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2907 return SendErrorResponse(0x15);
2910 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2912 // Consume the ';' after D.
2913 packet.SetFilePos(1);
2914 if (packet.GetBytesLeft()) {
2915 if (packet.GetChar() != ';')
2916 return SendIllFormedResponse(packet, "D missing expected ';'");
2918 // Grab the PID from which we will detach (assume hex encoding).
2919 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2920 if (pid == LLDB_INVALID_PROCESS_ID)
2921 return SendIllFormedResponse(packet, "D failed to parse the process id");
2924 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
2925 return SendIllFormedResponse(packet, "Invalid pid");
2928 const Error error = m_debugged_process_sp->Detach();
2931 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2932 "pid %" PRIu64 ": %s\n",
2933 __FUNCTION__, m_debugged_process_sp->GetID(),
2935 return SendErrorResponse(0x01);
2938 return SendOKResponse();
2941 GDBRemoteCommunication::PacketResult
2942 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2943 StringExtractorGDBRemote &packet) {
2944 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2946 packet.SetFilePos(strlen("qThreadStopInfo"));
2947 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2948 if (tid == LLDB_INVALID_THREAD_ID) {
2950 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2951 "parse thread id from request \"%s\"",
2952 __FUNCTION__, packet.GetStringRef().c_str());
2953 return SendErrorResponse(0x15);
2955 return SendStopReplyPacketForThread(tid);
2958 GDBRemoteCommunication::PacketResult
2959 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
2960 StringExtractorGDBRemote &) {
2961 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2963 // Ensure we have a debugged process.
2964 if (!m_debugged_process_sp ||
2965 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
2966 return SendErrorResponse(50);
2969 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
2971 __FUNCTION__, m_debugged_process_sp->GetID());
2973 StreamString response;
2974 const bool threads_with_valid_stop_info_only = false;
2975 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
2976 *m_debugged_process_sp, threads_with_valid_stop_info_only);
2977 if (!threads_array_sp) {
2979 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
2980 "packet for pid %" PRIu64,
2981 __FUNCTION__, m_debugged_process_sp->GetID());
2982 return SendErrorResponse(52);
2985 threads_array_sp->Write(response);
2986 StreamGDBRemote escaped_response;
2987 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2988 return SendPacketNoLock(escaped_response.GetString());
2991 GDBRemoteCommunication::PacketResult
2992 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
2993 StringExtractorGDBRemote &packet) {
2994 // Fail if we don't have a current process.
2995 if (!m_debugged_process_sp ||
2996 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
2997 return SendErrorResponse(68);
2999 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3000 if (packet.GetBytesLeft() == 0)
3001 return SendOKResponse();
3002 if (packet.GetChar() != ':')
3003 return SendErrorResponse(67);
3005 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
3006 StreamGDBRemote response;
3007 response.Printf("num:%d;", num);
3008 return SendPacketNoLock(response.GetString());
3011 GDBRemoteCommunication::PacketResult
3012 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3013 StringExtractorGDBRemote &packet) {
3014 // Fail if we don't have a current process.
3015 if (!m_debugged_process_sp ||
3016 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3017 return SendErrorResponse(67);
3019 packet.SetFilePos(strlen("qFileLoadAddress:"));
3020 if (packet.GetBytesLeft() == 0)
3021 return SendErrorResponse(68);
3023 std::string file_name;
3024 packet.GetHexByteString(file_name);
3026 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3028 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3030 return SendErrorResponse(69);
3032 if (file_load_address == LLDB_INVALID_ADDRESS)
3033 return SendErrorResponse(1); // File not loaded
3035 StreamGDBRemote response;
3036 response.PutHex64(file_load_address);
3037 return SendPacketNoLock(response.GetString());
3040 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3041 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3043 // Tell the stdio connection to shut down.
3044 if (m_stdio_communication.IsConnected()) {
3045 auto connection = m_stdio_communication.GetConnection();
3048 connection->Disconnect(&error);
3050 if (error.Success()) {
3052 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3053 "terminal stdio - SUCCESS",
3057 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3058 "terminal stdio - FAIL: %s",
3059 __FUNCTION__, error.AsCString());
3065 NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3066 StringExtractorGDBRemote &packet) {
3067 NativeThreadProtocolSP thread_sp;
3069 // We have no thread if we don't have a process.
3070 if (!m_debugged_process_sp ||
3071 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3074 // If the client hasn't asked for thread suffix support, there will not be a
3076 // Use the current thread in that case.
3077 if (!m_thread_suffix_supported) {
3078 const lldb::tid_t current_tid = GetCurrentThreadID();
3079 if (current_tid == LLDB_INVALID_THREAD_ID)
3081 else if (current_tid == 0) {
3083 return m_debugged_process_sp->GetThreadAtIndex(0);
3085 return m_debugged_process_sp->GetThreadByID(current_tid);
3088 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3090 // Parse out the ';'.
3091 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3093 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3094 "error: expected ';' prior to start of thread suffix: packet "
3096 __FUNCTION__, packet.GetStringRef().c_str());
3100 if (!packet.GetBytesLeft())
3103 // Parse out thread: portion.
3104 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3106 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3107 "error: expected 'thread:' but not found, packet contents = "
3109 __FUNCTION__, packet.GetStringRef().c_str());
3112 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3113 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3115 return m_debugged_process_sp->GetThreadByID(tid);
3120 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3121 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3122 // Use whatever the debug process says is the current thread id
3123 // since the protocol either didn't specify or specified we want
3124 // any/all threads marked as the current thread.
3125 if (!m_debugged_process_sp)
3126 return LLDB_INVALID_THREAD_ID;
3127 return m_debugged_process_sp->GetCurrentThreadID();
3129 // Use the specific current thread id set by the gdb remote protocol.
3130 return m_current_tid;
3133 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3134 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3135 return m_next_saved_registers_id++;
3138 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3139 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | GDBR_LOG_PROCESS));
3141 log->Printf("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
3143 // Clear any auxv cached data.
3144 // *BSD impls should be able to do this too.
3145 #if defined(__linux__)
3147 log->Printf("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer "
3150 m_active_auxv_buffer_sp ? "was set" : "was not set");
3151 m_active_auxv_buffer_sp.reset();
3156 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3157 const ArchSpec &arch) {
3158 if (m_debugged_process_sp) {
3160 if (m_debugged_process_sp
3161 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3163 if (file_spec.Exists())
3168 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);