1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "lldb/Host/Config.h"
14 #include "GDBRemoteCommunicationServerLLGS.h"
15 #include "lldb/Utility/StreamGDBRemote.h"
23 // Other libraries and framework includes
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Host/ConnectionFileDescriptor.h"
27 #include "lldb/Host/Debug.h"
28 #include "lldb/Host/File.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/common/NativeProcessProtocol.h"
33 #include "lldb/Host/common/NativeRegisterContext.h"
34 #include "lldb/Host/common/NativeThreadProtocol.h"
35 #include "lldb/Interpreter/Args.h"
36 #include "lldb/Target/FileAction.h"
37 #include "lldb/Target/MemoryRegionInfo.h"
38 #include "lldb/Utility/DataBuffer.h"
39 #include "lldb/Utility/Endian.h"
40 #include "lldb/Utility/JSON.h"
41 #include "lldb/Utility/LLDBAssert.h"
42 #include "lldb/Utility/Log.h"
43 #include "lldb/Utility/StreamString.h"
44 #include "lldb/Utility/UriParser.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/Support/ScopedPrinter.h"
49 #include "ProcessGDBRemote.h"
50 #include "ProcessGDBRemoteLog.h"
51 #include "Utility/StringExtractorGDBRemote.h"
54 using namespace lldb_private;
55 using namespace lldb_private::process_gdb_remote;
58 //----------------------------------------------------------------------
60 //----------------------------------------------------------------------
63 enum GDBRemoteServerError {
64 // Set to the first unused error number in literal form below
66 eErrorNoProcess = eErrorFirst,
72 //----------------------------------------------------------------------
73 // GDBRemoteCommunicationServerLLGS constructor
74 //----------------------------------------------------------------------
75 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
77 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
79 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
80 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
81 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
82 m_inferior_prev_state(StateType::eStateInvalid),
83 m_saved_registers_map(), m_next_saved_registers_id(1),
84 m_handshake_completed(false) {
85 RegisterPacketHandlers();
88 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
90 &GDBRemoteCommunicationServerLLGS::Handle_C);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
92 &GDBRemoteCommunicationServerLLGS::Handle_c);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
94 &GDBRemoteCommunicationServerLLGS::Handle_D);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
96 &GDBRemoteCommunicationServerLLGS::Handle_H);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
98 &GDBRemoteCommunicationServerLLGS::Handle_I);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_interrupt,
101 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
102 RegisterMemberFunctionHandler(
103 StringExtractorGDBRemote::eServerPacketType_m,
104 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
106 &GDBRemoteCommunicationServerLLGS::Handle_M);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
108 &GDBRemoteCommunicationServerLLGS::Handle_p);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
110 &GDBRemoteCommunicationServerLLGS::Handle_P);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
112 &GDBRemoteCommunicationServerLLGS::Handle_qC);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
115 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
118 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
121 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
157 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
158 RegisterMemberFunctionHandler(
159 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
160 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
162 &GDBRemoteCommunicationServerLLGS::Handle_s);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_stop_reason,
165 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vAttach,
168 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
174 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_x,
177 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
178 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
179 &GDBRemoteCommunicationServerLLGS::Handle_Z);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
181 &GDBRemoteCommunicationServerLLGS::Handle_z);
182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
184 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
191 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
194 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
195 RegisterMemberFunctionHandler(
196 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
197 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
198 RegisterMemberFunctionHandler(
199 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
200 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
202 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
203 [this](StringExtractorGDBRemote packet, Status &error,
204 bool &interrupt, bool &quit) {
206 return this->Handle_k(packet);
211 GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
213 if ((argc < 1) || !args || !args[0] || !args[0][0])
214 return Status("%s: no process command line specified to launch",
217 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
222 GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
223 m_process_launch_info.GetFlags().Set(launch_flags);
227 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
228 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
230 if (!m_process_launch_info.GetArguments().GetArgumentCount())
231 return Status("%s: no process command line specified to launch",
234 const bool should_forward_stdio =
235 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
236 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
237 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
238 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
239 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
241 const bool default_to_use_pty = true;
242 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
246 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
247 assert(!m_debugged_process_sp && "lldb-server creating debugged "
248 "process but one already exists");
249 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
250 m_mainloop, m_debugged_process_sp);
253 if (!error.Success()) {
254 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
255 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
259 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
261 // llgs local-process debugging may specify PTY paths, which will make these
262 // file actions non-null
263 // process launch -i/e/o will also make these file actions non-null
264 // nullptr means that the traffic is expected to flow over gdb-remote protocol
265 if (should_forward_stdio) {
266 // nullptr means it's not redirected to file or pty (in case of LLGS local)
267 // at least one of stdio will be transferred pty<->gdb-remote
268 // we need to give the pty master handle to this object to read and/or write
271 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
272 " setting up stdout/stderr redirection via $O gdb-remote commands",
273 __FUNCTION__, m_debugged_process_sp->GetID());
275 // Setup stdout/stderr mapping from inferior to $O
276 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
277 if (terminal_fd >= 0) {
279 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
280 "inferior STDIO fd to %d",
281 __FUNCTION__, terminal_fd);
282 error = SetSTDIOFileDescriptor(terminal_fd);
287 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
288 "inferior STDIO since terminal fd reported as %d",
289 __FUNCTION__, terminal_fd);
293 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
294 " skipping stdout/stderr redirection via $O: inferior will "
295 "communicate over client-provided file descriptors",
296 __FUNCTION__, m_debugged_process_sp->GetID());
299 printf("Launched '%s' as process %" PRIu64 "...\n",
300 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
301 m_process_launch_info.GetProcessID());
306 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
309 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
311 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
314 // Before we try to attach, make sure we aren't already monitoring something
316 if (m_debugged_process_sp &&
317 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
318 return Status("cannot attach to a process %" PRIu64
319 " when another process with pid %" PRIu64
320 " is being debugged.",
321 pid, m_debugged_process_sp->GetID());
324 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
325 m_debugged_process_sp);
326 if (!error.Success()) {
327 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
328 __FUNCTION__, pid, error.AsCString());
332 // Setup stdout/stderr mapping from inferior.
333 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
334 if (terminal_fd >= 0) {
336 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
337 "inferior STDIO fd to %d",
338 __FUNCTION__, terminal_fd);
339 error = SetSTDIOFileDescriptor(terminal_fd);
344 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
345 "inferior STDIO since terminal fd reported as %d",
346 __FUNCTION__, terminal_fd);
349 printf("Attached to process %" PRIu64 "...\n", pid);
354 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
355 NativeProcessProtocol *process) {
356 assert(process && "process cannot be NULL");
357 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
359 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
360 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
361 __FUNCTION__, process->GetID(),
362 StateAsCString(process->GetState()));
366 GDBRemoteCommunication::PacketResult
367 GDBRemoteCommunicationServerLLGS::SendWResponse(
368 NativeProcessProtocol *process) {
369 assert(process && "process cannot be NULL");
370 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
372 // send W notification
373 auto wait_status = process->GetExitStatus();
375 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
378 StreamGDBRemote response;
379 response.PutChar('E');
380 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
381 return SendPacketNoLock(response.GetString());
384 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
387 StreamGDBRemote response;
388 response.Format("{0:g}", *wait_status);
389 return SendPacketNoLock(response.GetString());
392 static void AppendHexValue(StreamString &response, const uint8_t *buf,
393 uint32_t buf_size, bool swap) {
396 for (i = buf_size - 1; i >= 0; i--)
397 response.PutHex8(buf[i]);
399 for (i = 0; i < buf_size; i++)
400 response.PutHex8(buf[i]);
404 static void WriteRegisterValueInHexFixedWidth(
405 StreamString &response, NativeRegisterContextSP ®_ctx_sp,
406 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
407 lldb::ByteOrder byte_order) {
408 RegisterValue reg_value;
410 Status error = reg_ctx_sp->ReadRegister(®_info, reg_value);
412 reg_value_p = ®_value;
417 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
418 reg_value_p->GetByteSize(),
419 byte_order == lldb::eByteOrderLittle);
421 // Zero-out any unreadable values.
422 if (reg_info.byte_size > 0) {
423 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
424 AppendHexValue(response, zeros.data(), zeros.size(), false);
429 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
430 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
432 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
436 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
438 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
439 // Expedite all registers in the first register set (i.e. should be GPRs) that
440 // are not contained in other registers.
441 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
444 for (const uint32_t *reg_num_p = reg_set_p->registers;
445 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
446 uint32_t reg_num = *reg_num_p;
448 // Expedite only a couple of registers until we figure out why sending
451 static const uint32_t k_expedited_registers[] = {
452 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
453 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
455 for (const uint32_t *generic_reg_p = k_expedited_registers;
456 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
457 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
458 eRegisterKindGeneric, *generic_reg_p);
459 if (reg_num == LLDB_INVALID_REGNUM)
460 continue; // Target does not support the given register.
463 const RegisterInfo *const reg_info_p =
464 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
465 if (reg_info_p == nullptr) {
468 "%s failed to get register info for register index %" PRIu32,
469 __FUNCTION__, reg_num);
473 if (reg_info_p->value_regs != nullptr)
474 continue; // Only expedite registers that are not contained in other
477 RegisterValue reg_value;
478 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
481 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
483 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
484 reg_num, error.AsCString());
489 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
490 ®_value, lldb::eByteOrderBig);
492 register_object_sp->SetObject(
493 llvm::to_string(reg_num),
494 std::make_shared<JSONString>(stream.GetString()));
497 return register_object_sp;
500 static const char *GetStopReasonString(StopReason stop_reason) {
501 switch (stop_reason) {
502 case eStopReasonTrace:
504 case eStopReasonBreakpoint:
506 case eStopReasonWatchpoint:
508 case eStopReasonSignal:
510 case eStopReasonException:
512 case eStopReasonExec:
514 case eStopReasonInstrumentation:
515 case eStopReasonInvalid:
516 case eStopReasonPlanComplete:
517 case eStopReasonThreadExiting:
518 case eStopReasonNone:
524 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
526 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
528 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
530 // Ensure we can get info on the given thread.
531 uint32_t thread_idx = 0;
532 for (NativeThreadProtocolSP thread_sp;
533 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
536 lldb::tid_t tid = thread_sp->GetID();
538 // Grab the reason this thread stopped.
539 struct ThreadStopInfo tid_stop_info;
540 std::string description;
541 if (!thread_sp->GetStopReason(tid_stop_info, description))
544 const int signum = tid_stop_info.details.signal.signo;
546 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
548 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
549 __FUNCTION__, process.GetID(), tid, signum,
550 tid_stop_info.reason, tid_stop_info.details.exception.type);
553 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
554 threads_array_sp->AppendObject(thread_obj_sp);
557 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
558 thread_obj_sp->SetObject("registers", registers_sp);
561 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
563 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
565 const std::string thread_name = thread_sp->GetName();
566 if (!thread_name.empty())
567 thread_obj_sp->SetObject("name",
568 std::make_shared<JSONString>(thread_name));
570 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
571 thread_obj_sp->SetObject("reason",
572 std::make_shared<JSONString>(stop_reason_str));
574 if (!description.empty())
575 thread_obj_sp->SetObject("description",
576 std::make_shared<JSONString>(description));
578 if ((tid_stop_info.reason == eStopReasonException) &&
579 tid_stop_info.details.exception.type) {
580 thread_obj_sp->SetObject(
582 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
584 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
585 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
587 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
588 tid_stop_info.details.exception.data[i]));
590 thread_obj_sp->SetObject("medata", medata_array_sp);
593 // TODO: Expedite interesting regions of inferior memory
596 return threads_array_sp;
599 GDBRemoteCommunication::PacketResult
600 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
602 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
604 // Ensure we have a debugged process.
605 if (!m_debugged_process_sp ||
606 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
607 return SendErrorResponse(50);
611 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
613 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
615 // Ensure we can get info on the given thread.
616 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
618 return SendErrorResponse(51);
620 // Grab the reason this thread stopped.
621 struct ThreadStopInfo tid_stop_info;
622 std::string description;
623 if (!thread_sp->GetStopReason(tid_stop_info, description))
624 return SendErrorResponse(52);
626 // FIXME implement register handling for exec'd inferiors.
627 // if (tid_stop_info.reason == eStopReasonExec)
629 // const bool force = true;
630 // InitializeRegisters(force);
633 StreamString response;
634 // Output the T packet with the thread
635 response.PutChar('T');
636 int signum = tid_stop_info.details.signal.signo;
638 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
640 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
641 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
642 tid_stop_info.reason, tid_stop_info.details.exception.type);
645 // Print the signal number.
646 response.PutHex8(signum & 0xff);
649 response.Printf("thread:%" PRIx64 ";", tid);
651 // Include the thread name if there is one.
652 const std::string thread_name = thread_sp->GetName();
653 if (!thread_name.empty()) {
654 size_t thread_name_len = thread_name.length();
656 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
657 response.PutCString("name:");
658 response.PutCString(thread_name);
660 // The thread name contains special chars, send as hex bytes.
661 response.PutCString("hexname:");
662 response.PutCStringAsRawHex8(thread_name.c_str());
664 response.PutChar(';');
667 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
668 // will send all thread IDs back in the "threads" key whose value is
669 // a list of hex thread IDs separated by commas:
670 // "threads:10a,10b,10c;"
671 // This will save the debugger from having to send a pair of qfThreadInfo
672 // and qsThreadInfo packets, but it also might take a lot of room in the
673 // stop reply packet, so it must be enabled only on systems where there
674 // are no limits on packet lengths.
675 if (m_list_threads_in_stop_reply) {
676 response.PutCString("threads:");
678 uint32_t thread_index = 0;
679 NativeThreadProtocolSP listed_thread_sp;
680 for (listed_thread_sp =
681 m_debugged_process_sp->GetThreadAtIndex(thread_index);
682 listed_thread_sp; ++thread_index,
683 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
685 if (thread_index > 0)
686 response.PutChar(',');
687 response.Printf("%" PRIx64, listed_thread_sp->GetID());
689 response.PutChar(';');
691 // Include JSON info that describes the stop reason for any threads
692 // that actually have stop reasons. We use the new "jstopinfo" key
693 // whose values is hex ascii JSON that contains the thread IDs
694 // thread stop info only for threads that have stop reasons. Only send
695 // this if we have more than one thread otherwise this packet has all
696 // the info it needs.
697 if (thread_index > 0) {
698 const bool threads_with_valid_stop_info_only = true;
699 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
700 *m_debugged_process_sp, threads_with_valid_stop_info_only);
701 if (threads_info_sp) {
702 response.PutCString("jstopinfo:");
703 StreamString unescaped_response;
704 threads_info_sp->Write(unescaped_response);
705 response.PutCStringAsRawHex8(unescaped_response.GetData());
706 response.PutChar(';');
708 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
709 "jstopinfo field for pid %" PRIu64,
710 __FUNCTION__, m_debugged_process_sp->GetID());
714 response.PutCString("thread-pcs");
715 char delimiter = ':';
716 for (NativeThreadProtocolSP thread_sp;
717 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
719 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
723 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
724 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
725 const RegisterInfo *const reg_info_p =
726 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
728 RegisterValue reg_value;
729 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
732 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
734 reg_info_p->name ? reg_info_p->name
735 : "<unnamed-register>",
736 reg_to_read, error.AsCString());
740 response.PutChar(delimiter);
742 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
743 ®_value, endian::InlHostByteOrder());
746 response.PutChar(';');
750 // Expedite registers.
753 // Grab the register context.
754 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
756 // Expedite all registers in the first register set (i.e. should be GPRs)
757 // that are not contained in other registers.
758 const RegisterSet *reg_set_p;
759 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
760 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
762 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
763 "from set '%s' (registers set count: %zu)",
765 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
766 reg_set_p->num_registers);
768 for (const uint32_t *reg_num_p = reg_set_p->registers;
769 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
770 const RegisterInfo *const reg_info_p =
771 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
772 if (reg_info_p == nullptr) {
774 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
775 "register info for register set '%s', register index "
778 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
780 } else if (reg_info_p->value_regs == nullptr) {
781 // Only expediate registers that are not contained in other registers.
782 RegisterValue reg_value;
783 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
784 if (error.Success()) {
785 response.Printf("%.02x:", *reg_num_p);
786 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
787 ®_value, lldb::eByteOrderBig);
788 response.PutChar(';');
791 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
792 "register '%s' index %" PRIu32 ": %s",
793 __FUNCTION__, reg_info_p->name ? reg_info_p->name
794 : "<unnamed-register>",
795 *reg_num_p, error.AsCString());
802 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
803 if (reason_str != nullptr) {
804 response.Printf("reason:%s;", reason_str);
807 if (!description.empty()) {
808 // Description may contains special chars, send as hex bytes.
809 response.PutCString("description:");
810 response.PutCStringAsRawHex8(description.c_str());
811 response.PutChar(';');
812 } else if ((tid_stop_info.reason == eStopReasonException) &&
813 tid_stop_info.details.exception.type) {
814 response.PutCString("metype:");
815 response.PutHex64(tid_stop_info.details.exception.type);
816 response.PutCString(";mecount:");
817 response.PutHex32(tid_stop_info.details.exception.data_count);
818 response.PutChar(';');
820 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
821 response.PutCString("medata:");
822 response.PutHex64(tid_stop_info.details.exception.data[i]);
823 response.PutChar(';');
827 return SendPacketNoLock(response.GetString());
830 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
831 NativeProcessProtocol *process) {
832 assert(process && "process cannot be NULL");
834 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
836 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
838 PacketResult result = SendStopReasonForState(StateType::eStateExited);
839 if (result != PacketResult::Success) {
841 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
842 "notification for PID %" PRIu64 ", state: eStateExited",
843 __FUNCTION__, process->GetID());
846 // Close the pipe to the inferior terminal i/o if we launched it
848 MaybeCloseInferiorTerminalConnection();
850 // We are ready to exit the debug monitor.
854 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
855 NativeProcessProtocol *process) {
856 assert(process && "process cannot be NULL");
858 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
860 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
862 // Send the stop reason unless this is the stop after the
864 switch (m_inferior_prev_state) {
865 case eStateLaunching:
866 case eStateAttaching:
867 // Don't send anything per debugserver behavior.
870 // In all other cases, send the stop reason.
871 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
872 if (result != PacketResult::Success) {
874 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
875 "notification for PID %" PRIu64 ", state: eStateExited",
876 __FUNCTION__, process->GetID());
882 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
883 NativeProcessProtocol *process, lldb::StateType state) {
884 assert(process && "process cannot be NULL");
885 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
887 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
888 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
889 __FUNCTION__, process->GetID(), StateAsCString(state));
893 case StateType::eStateRunning:
894 StartSTDIOForwarding();
897 case StateType::eStateStopped:
898 // Make sure we get all of the pending stdout/stderr from the inferior
899 // and send it to the lldb host before we send the state change
902 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
904 // interfere with our protocol.
905 StopSTDIOForwarding();
906 HandleInferiorState_Stopped(process);
909 case StateType::eStateExited:
912 StopSTDIOForwarding();
913 HandleInferiorState_Exited(process);
918 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
919 "change for pid %" PRIu64 ", new state: %s",
920 __FUNCTION__, process->GetID(), StateAsCString(state));
925 // Remember the previous state reported to us.
926 m_inferior_prev_state = state;
929 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
930 ClearProcessSpecificData();
933 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
934 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
936 if (!m_handshake_completed) {
937 if (!HandshakeWithClient()) {
939 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
940 "client failed, exiting",
942 m_mainloop.RequestTermination();
945 m_handshake_completed = true;
948 bool interrupt = false;
952 const PacketResult result = GetPacketAndSendResponse(
953 std::chrono::microseconds(0), error, interrupt, done);
954 if (result == PacketResult::ErrorReplyTimeout)
955 break; // No more packets in the queue
957 if ((result != PacketResult::Success)) {
959 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
961 __FUNCTION__, error.AsCString());
962 m_mainloop.RequestTermination();
968 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
969 std::unique_ptr<Connection> &&connection) {
970 IOObjectSP read_object_sp = connection->GetReadObject();
971 GDBRemoteCommunicationServer::SetConnection(connection.release());
974 m_network_handle_up = m_mainloop.RegisterReadObject(
975 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
980 GDBRemoteCommunication::PacketResult
981 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
983 if ((buffer == nullptr) || (len == 0)) {
985 return PacketResult::Success;
988 StreamString response;
989 response.PutChar('O');
990 response.PutBytesAsRawHex8(buffer, len);
992 return SendPacketNoLock(response.GetString());
995 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
998 // Set up the reading/handling of process I/O
999 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1000 new ConnectionFileDescriptor(fd, true));
1002 error.SetErrorString("failed to create ConnectionFileDescriptor");
1006 m_stdio_communication.SetCloseOnEOF(false);
1007 m_stdio_communication.SetConnection(conn_up.release());
1008 if (!m_stdio_communication.IsConnected()) {
1009 error.SetErrorString(
1010 "failed to set connection for inferior I/O communication");
1017 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1018 // Don't forward if not connected (e.g. when attaching).
1019 if (!m_stdio_communication.IsConnected())
1023 lldbassert(!m_stdio_handle_up);
1024 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1025 m_stdio_communication.GetConnection()->GetReadObject(),
1026 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1028 if (!m_stdio_handle_up) {
1029 // Not much we can do about the failure. Log it and continue without
1031 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1032 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1034 __FUNCTION__, error.AsCString());
1038 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1039 m_stdio_handle_up.reset();
1042 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1044 ConnectionStatus status;
1047 size_t bytes_read = m_stdio_communication.Read(
1048 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1050 case eConnectionStatusSuccess:
1051 SendONotification(buffer, bytes_read);
1053 case eConnectionStatusLostConnection:
1054 case eConnectionStatusEndOfFile:
1055 case eConnectionStatusError:
1056 case eConnectionStatusNoConnection:
1057 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1058 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1059 "forwarding as communication returned status %d (error: "
1061 __FUNCTION__, status, error.AsCString());
1062 m_stdio_handle_up.reset();
1065 case eConnectionStatusInterrupted:
1066 case eConnectionStatusTimedOut:
1072 GDBRemoteCommunication::PacketResult
1073 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1074 StringExtractorGDBRemote &packet) {
1075 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1076 // Fail if we don't have a current process.
1077 if (!m_debugged_process_sp ||
1078 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1079 return SendErrorResponse(68);
1081 if (!packet.ConsumeFront("jTraceStart:"))
1082 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1084 TraceOptions options;
1085 uint64_t type = std::numeric_limits<uint64_t>::max();
1086 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1087 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1088 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1090 auto json_object = StructuredData::ParseJSON(packet.Peek());
1093 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1094 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1096 auto json_dict = json_object->GetAsDictionary();
1098 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1099 options.setMetaDataBufferSize(metabuffersize);
1101 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1102 options.setTraceBufferSize(buffersize);
1104 json_dict->GetValueForKeyAsInteger("type", type);
1105 options.setType(static_cast<lldb::TraceType>(type));
1107 json_dict->GetValueForKeyAsInteger("threadid", tid);
1108 options.setThreadID(tid);
1110 StructuredData::ObjectSP custom_params_sp =
1111 json_dict->GetValueForKey("params");
1112 if (custom_params_sp &&
1113 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1114 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1116 options.setTraceParams(
1117 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1119 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1120 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1121 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1123 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1127 lldb::user_id_t uid = LLDB_INVALID_UID;
1128 uid = m_debugged_process_sp->StartTrace(options, error);
1129 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1131 return SendErrorResponse(error.GetError());
1133 StreamGDBRemote response;
1134 response.Printf("%" PRIx64, uid);
1135 return SendPacketNoLock(response.GetString());
1138 GDBRemoteCommunication::PacketResult
1139 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1140 StringExtractorGDBRemote &packet) {
1141 // Fail if we don't have a current process.
1142 if (!m_debugged_process_sp ||
1143 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1144 return SendErrorResponse(68);
1146 if (!packet.ConsumeFront("jTraceStop:"))
1147 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1149 lldb::user_id_t uid = LLDB_INVALID_UID;
1150 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1152 auto json_object = StructuredData::ParseJSON(packet.Peek());
1155 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1156 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1158 auto json_dict = json_object->GetAsDictionary();
1160 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1161 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1163 json_dict->GetValueForKeyAsInteger("threadid", tid);
1165 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1168 return SendErrorResponse(error.GetError());
1170 return SendOKResponse();
1173 GDBRemoteCommunication::PacketResult
1174 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1175 StringExtractorGDBRemote &packet) {
1177 // Fail if we don't have a current process.
1178 if (!m_debugged_process_sp ||
1179 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1180 return SendErrorResponse(68);
1182 if (!packet.ConsumeFront("jTraceConfigRead:"))
1183 return SendIllFormedResponse(packet,
1184 "jTraceConfigRead: Ill formed packet ");
1186 lldb::user_id_t uid = LLDB_INVALID_UID;
1187 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1189 auto json_object = StructuredData::ParseJSON(packet.Peek());
1192 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1193 return SendIllFormedResponse(packet,
1194 "jTraceConfigRead: Ill formed packet ");
1196 auto json_dict = json_object->GetAsDictionary();
1198 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1199 return SendIllFormedResponse(packet,
1200 "jTraceConfigRead: Ill formed packet ");
1202 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1204 TraceOptions options;
1205 StreamGDBRemote response;
1207 options.setThreadID(threadid);
1208 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1211 return SendErrorResponse(error.GetError());
1213 StreamGDBRemote escaped_response;
1214 StructuredData::Dictionary json_packet;
1216 json_packet.AddIntegerItem("type", options.getType());
1217 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1218 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1220 StructuredData::DictionarySP custom_params = options.getTraceParams();
1222 json_packet.AddItem("params", custom_params);
1224 StreamString json_string;
1225 json_packet.Dump(json_string, false);
1226 escaped_response.PutEscapedBytes(json_string.GetData(),
1227 json_string.GetSize());
1228 return SendPacketNoLock(escaped_response.GetString());
1231 GDBRemoteCommunication::PacketResult
1232 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1233 StringExtractorGDBRemote &packet) {
1235 // Fail if we don't have a current process.
1236 if (!m_debugged_process_sp ||
1237 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1238 return SendErrorResponse(68);
1240 enum PacketType { MetaData, BufferData };
1241 PacketType tracetype = MetaData;
1243 if (packet.ConsumeFront("jTraceBufferRead:"))
1244 tracetype = BufferData;
1245 else if (packet.ConsumeFront("jTraceMetaRead:"))
1246 tracetype = MetaData;
1248 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1251 lldb::user_id_t uid = LLDB_INVALID_UID;
1253 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1254 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1255 uint64_t offset = std::numeric_limits<uint64_t>::max();
1257 auto json_object = StructuredData::ParseJSON(packet.Peek());
1260 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1261 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1263 auto json_dict = json_object->GetAsDictionary();
1265 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1266 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1267 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1268 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1270 json_dict->GetValueForKeyAsInteger("threadid", tid);
1272 // Allocate the response buffer.
1273 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1275 return SendErrorResponse(0x78);
1277 StreamGDBRemote response;
1279 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1281 if (tracetype == BufferData)
1282 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1283 else if (tracetype == MetaData)
1284 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1287 return SendErrorResponse(error.GetError());
1290 response.PutHex8(i);
1292 StreamGDBRemote escaped_response;
1293 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1294 return SendPacketNoLock(escaped_response.GetString());
1297 GDBRemoteCommunication::PacketResult
1298 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1299 StringExtractorGDBRemote &packet) {
1300 // Fail if we don't have a current process.
1301 if (!m_debugged_process_sp ||
1302 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1303 return SendErrorResponse(68);
1305 lldb::pid_t pid = m_debugged_process_sp->GetID();
1307 if (pid == LLDB_INVALID_PROCESS_ID)
1308 return SendErrorResponse(1);
1310 ProcessInstanceInfo proc_info;
1311 if (!Host::GetProcessInfo(pid, proc_info))
1312 return SendErrorResponse(1);
1314 StreamString response;
1315 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1316 return SendPacketNoLock(response.GetString());
1319 GDBRemoteCommunication::PacketResult
1320 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1321 // Fail if we don't have a current process.
1322 if (!m_debugged_process_sp ||
1323 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1324 return SendErrorResponse(68);
1326 // Make sure we set the current thread so g and p packets return
1327 // the data the gdb will expect.
1328 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1329 SetCurrentThreadID(tid);
1331 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1333 return SendErrorResponse(69);
1335 StreamString response;
1336 response.Printf("QC%" PRIx64, thread_sp->GetID());
1338 return SendPacketNoLock(response.GetString());
1341 GDBRemoteCommunication::PacketResult
1342 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1343 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1345 StopSTDIOForwarding();
1347 if (!m_debugged_process_sp) {
1350 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1352 return PacketResult::Success;
1355 Status error = m_debugged_process_sp->Kill();
1356 if (error.Fail() && log)
1357 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1358 "process %" PRIu64 ": %s",
1359 __FUNCTION__, m_debugged_process_sp->GetID(),
1362 // No OK response for kill packet.
1363 // return SendOKResponse ();
1364 return PacketResult::Success;
1367 GDBRemoteCommunication::PacketResult
1368 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1369 StringExtractorGDBRemote &packet) {
1370 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1371 if (packet.GetU32(0))
1372 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1374 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1375 return SendOKResponse();
1378 GDBRemoteCommunication::PacketResult
1379 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1380 StringExtractorGDBRemote &packet) {
1381 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1383 packet.GetHexByteString(path);
1384 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1385 return SendOKResponse();
1388 GDBRemoteCommunication::PacketResult
1389 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1390 StringExtractorGDBRemote &packet) {
1391 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1393 StreamString response;
1394 response.PutCStringAsRawHex8(working_dir.GetCString());
1395 return SendPacketNoLock(response.GetString());
1398 return SendErrorResponse(14);
1401 GDBRemoteCommunication::PacketResult
1402 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1403 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1405 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1407 // Ensure we have a native process.
1408 if (!m_debugged_process_sp) {
1410 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1413 return SendErrorResponse(0x36);
1416 // Pull out the signal number.
1417 packet.SetFilePos(::strlen("C"));
1418 if (packet.GetBytesLeft() < 1) {
1419 // Shouldn't be using a C without a signal.
1420 return SendIllFormedResponse(packet, "C packet specified without signal.");
1422 const uint32_t signo =
1423 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1424 if (signo == std::numeric_limits<uint32_t>::max())
1425 return SendIllFormedResponse(packet, "failed to parse signal number");
1427 // Handle optional continue address.
1428 if (packet.GetBytesLeft() > 0) {
1429 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1430 if (*packet.Peek() == ';')
1431 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1433 return SendIllFormedResponse(
1434 packet, "unexpected content after $C{signal-number}");
1437 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1440 // We have two branches: what to do if a continue thread is specified (in
1441 // which case we target
1442 // sending the signal to that thread), or when we don't have a continue thread
1444 // case we send a signal to the process).
1446 // TODO discuss with Greg Clayton, make sure this makes sense.
1448 lldb::tid_t signal_tid = GetContinueThreadID();
1449 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1450 // The resume action for the continue thread (or all threads if a continue
1451 // thread is not set).
1452 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1453 static_cast<int>(signo)};
1455 // Add the action for the continue thread (or all threads when the continue
1456 // thread isn't present).
1457 resume_actions.Append(action);
1459 // Send the signal to the process since we weren't targeting a specific
1460 // continue thread with the signal.
1461 error = m_debugged_process_sp->Signal(signo);
1464 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1465 "signal for process %" PRIu64 ": %s",
1466 __FUNCTION__, m_debugged_process_sp->GetID(),
1469 return SendErrorResponse(0x52);
1473 // Resume the threads.
1474 error = m_debugged_process_sp->Resume(resume_actions);
1477 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1478 "threads for process %" PRIu64 ": %s",
1479 __FUNCTION__, m_debugged_process_sp->GetID(),
1482 return SendErrorResponse(0x38);
1485 // Don't send an "OK" packet; response is the stopped/exited message.
1486 return PacketResult::Success;
1489 GDBRemoteCommunication::PacketResult
1490 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1491 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1493 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1495 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1497 // For now just support all continue.
1498 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1499 if (has_continue_address) {
1501 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1502 "c{address} variant [%s remains]",
1503 __FUNCTION__, packet.Peek());
1504 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1507 // Ensure we have a native process.
1508 if (!m_debugged_process_sp) {
1510 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1513 return SendErrorResponse(0x36);
1516 // Build the ResumeActionList
1517 ResumeActionList actions(StateType::eStateRunning, 0);
1519 Status error = m_debugged_process_sp->Resume(actions);
1523 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1525 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1527 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1532 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1533 __FUNCTION__, m_debugged_process_sp->GetID());
1535 // No response required from continue.
1536 return PacketResult::Success;
1539 GDBRemoteCommunication::PacketResult
1540 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1541 StringExtractorGDBRemote &packet) {
1542 StreamString response;
1543 response.Printf("vCont;c;C;s;S");
1545 return SendPacketNoLock(response.GetString());
1548 GDBRemoteCommunication::PacketResult
1549 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1550 StringExtractorGDBRemote &packet) {
1551 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1553 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1556 packet.SetFilePos(::strlen("vCont"));
1558 if (packet.GetBytesLeft() == 0) {
1560 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1563 return SendIllFormedResponse(packet, "Missing action from vCont package");
1566 // Check if this is all continue (no options or ";c").
1567 if (::strcmp(packet.Peek(), ";c") == 0) {
1568 // Move past the ';', then do a simple 'c'.
1569 packet.SetFilePos(packet.GetFilePos() + 1);
1570 return Handle_c(packet);
1571 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1572 // Move past the ';', then do a simple 's'.
1573 packet.SetFilePos(packet.GetFilePos() + 1);
1574 return Handle_s(packet);
1577 // Ensure we have a native process.
1578 if (!m_debugged_process_sp) {
1580 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1583 return SendErrorResponse(0x36);
1586 ResumeActionList thread_actions;
1588 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1589 // Skip the semi-colon.
1592 // Build up the thread action.
1593 ResumeAction thread_action;
1594 thread_action.tid = LLDB_INVALID_THREAD_ID;
1595 thread_action.state = eStateInvalid;
1596 thread_action.signal = 0;
1598 const char action = packet.GetChar();
1601 thread_action.signal = packet.GetHexMaxU32(false, 0);
1602 if (thread_action.signal == 0)
1603 return SendIllFormedResponse(
1604 packet, "Could not parse signal in vCont packet C action");
1609 thread_action.state = eStateRunning;
1613 thread_action.signal = packet.GetHexMaxU32(false, 0);
1614 if (thread_action.signal == 0)
1615 return SendIllFormedResponse(
1616 packet, "Could not parse signal in vCont packet S action");
1621 thread_action.state = eStateStepping;
1625 return SendIllFormedResponse(packet, "Unsupported vCont action");
1629 // Parse out optional :{thread-id} value.
1630 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1631 // Consume the separator.
1634 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1635 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1636 return SendIllFormedResponse(
1637 packet, "Could not parse thread number in vCont packet");
1640 thread_actions.Append(thread_action);
1643 Status error = m_debugged_process_sp->Resume(thread_actions);
1646 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1647 "process %" PRIu64 ": %s",
1648 __FUNCTION__, m_debugged_process_sp->GetID(),
1651 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1656 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1657 __FUNCTION__, m_debugged_process_sp->GetID());
1659 // No response required from vCont.
1660 return PacketResult::Success;
1663 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1664 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1666 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1670 m_current_tid = tid;
1671 if (m_debugged_process_sp)
1672 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1675 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1676 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1678 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1682 m_continue_tid = tid;
1685 GDBRemoteCommunication::PacketResult
1686 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1687 StringExtractorGDBRemote &packet) {
1688 // Handle the $? gdbremote command.
1690 // If no process, indicate error
1691 if (!m_debugged_process_sp)
1692 return SendErrorResponse(02);
1694 return SendStopReasonForState(m_debugged_process_sp->GetState());
1697 GDBRemoteCommunication::PacketResult
1698 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1699 lldb::StateType process_state) {
1700 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1702 switch (process_state) {
1703 case eStateAttaching:
1704 case eStateLaunching:
1706 case eStateStepping:
1707 case eStateDetached:
1708 // NOTE: gdb protocol doc looks like it should return $OK
1709 // when everything is running (i.e. no stopped result).
1710 return PacketResult::Success; // Ignore
1712 case eStateSuspended:
1714 case eStateCrashed: {
1715 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1716 // Make sure we set the current thread so g and p packets return
1717 // the data the gdb will expect.
1718 SetCurrentThreadID(tid);
1719 return SendStopReplyPacketForThread(tid);
1723 case eStateUnloaded:
1725 return SendWResponse(m_debugged_process_sp.get());
1729 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1730 ", current state reporting not handled: %s",
1731 __FUNCTION__, m_debugged_process_sp->GetID(),
1732 StateAsCString(process_state));
1737 return SendErrorResponse(0);
1740 GDBRemoteCommunication::PacketResult
1741 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1742 StringExtractorGDBRemote &packet) {
1743 // Fail if we don't have a current process.
1744 if (!m_debugged_process_sp ||
1745 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1746 return SendErrorResponse(68);
1748 // Ensure we have a thread.
1749 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1751 return SendErrorResponse(69);
1753 // Get the register context for the first thread.
1754 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1755 if (!reg_context_sp)
1756 return SendErrorResponse(69);
1758 // Parse out the register number from the request.
1759 packet.SetFilePos(strlen("qRegisterInfo"));
1760 const uint32_t reg_index =
1761 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1762 if (reg_index == std::numeric_limits<uint32_t>::max())
1763 return SendErrorResponse(69);
1765 // Return the end of registers response if we've iterated one past the end of
1766 // the register set.
1767 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1768 return SendErrorResponse(69);
1770 const RegisterInfo *reg_info =
1771 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1773 return SendErrorResponse(69);
1775 // Build the reginfos response.
1776 StreamGDBRemote response;
1778 response.PutCString("name:");
1779 response.PutCString(reg_info->name);
1780 response.PutChar(';');
1782 if (reg_info->alt_name && reg_info->alt_name[0]) {
1783 response.PutCString("alt-name:");
1784 response.PutCString(reg_info->alt_name);
1785 response.PutChar(';');
1788 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1789 reg_info->byte_size * 8, reg_info->byte_offset);
1791 switch (reg_info->encoding) {
1793 response.PutCString("encoding:uint;");
1796 response.PutCString("encoding:sint;");
1798 case eEncodingIEEE754:
1799 response.PutCString("encoding:ieee754;");
1801 case eEncodingVector:
1802 response.PutCString("encoding:vector;");
1808 switch (reg_info->format) {
1810 response.PutCString("format:binary;");
1812 case eFormatDecimal:
1813 response.PutCString("format:decimal;");
1816 response.PutCString("format:hex;");
1819 response.PutCString("format:float;");
1821 case eFormatVectorOfSInt8:
1822 response.PutCString("format:vector-sint8;");
1824 case eFormatVectorOfUInt8:
1825 response.PutCString("format:vector-uint8;");
1827 case eFormatVectorOfSInt16:
1828 response.PutCString("format:vector-sint16;");
1830 case eFormatVectorOfUInt16:
1831 response.PutCString("format:vector-uint16;");
1833 case eFormatVectorOfSInt32:
1834 response.PutCString("format:vector-sint32;");
1836 case eFormatVectorOfUInt32:
1837 response.PutCString("format:vector-uint32;");
1839 case eFormatVectorOfFloat32:
1840 response.PutCString("format:vector-float32;");
1842 case eFormatVectorOfUInt64:
1843 response.PutCString("format:vector-uint64;");
1845 case eFormatVectorOfUInt128:
1846 response.PutCString("format:vector-uint128;");
1852 const char *const register_set_name =
1853 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1854 if (register_set_name) {
1855 response.PutCString("set:");
1856 response.PutCString(register_set_name);
1857 response.PutChar(';');
1860 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1861 LLDB_INVALID_REGNUM)
1862 response.Printf("ehframe:%" PRIu32 ";",
1863 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1865 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1866 response.Printf("dwarf:%" PRIu32 ";",
1867 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1869 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1870 case LLDB_REGNUM_GENERIC_PC:
1871 response.PutCString("generic:pc;");
1873 case LLDB_REGNUM_GENERIC_SP:
1874 response.PutCString("generic:sp;");
1876 case LLDB_REGNUM_GENERIC_FP:
1877 response.PutCString("generic:fp;");
1879 case LLDB_REGNUM_GENERIC_RA:
1880 response.PutCString("generic:ra;");
1882 case LLDB_REGNUM_GENERIC_FLAGS:
1883 response.PutCString("generic:flags;");
1885 case LLDB_REGNUM_GENERIC_ARG1:
1886 response.PutCString("generic:arg1;");
1888 case LLDB_REGNUM_GENERIC_ARG2:
1889 response.PutCString("generic:arg2;");
1891 case LLDB_REGNUM_GENERIC_ARG3:
1892 response.PutCString("generic:arg3;");
1894 case LLDB_REGNUM_GENERIC_ARG4:
1895 response.PutCString("generic:arg4;");
1897 case LLDB_REGNUM_GENERIC_ARG5:
1898 response.PutCString("generic:arg5;");
1900 case LLDB_REGNUM_GENERIC_ARG6:
1901 response.PutCString("generic:arg6;");
1903 case LLDB_REGNUM_GENERIC_ARG7:
1904 response.PutCString("generic:arg7;");
1906 case LLDB_REGNUM_GENERIC_ARG8:
1907 response.PutCString("generic:arg8;");
1913 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1914 response.PutCString("container-regs:");
1916 for (const uint32_t *reg_num = reg_info->value_regs;
1917 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1919 response.PutChar(',');
1920 response.Printf("%" PRIx32, *reg_num);
1922 response.PutChar(';');
1925 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1926 response.PutCString("invalidate-regs:");
1928 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1929 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1931 response.PutChar(',');
1932 response.Printf("%" PRIx32, *reg_num);
1934 response.PutChar(';');
1937 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1938 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1939 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1940 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1941 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1942 response.PutChar(';');
1944 return SendPacketNoLock(response.GetString());
1947 GDBRemoteCommunication::PacketResult
1948 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1949 StringExtractorGDBRemote &packet) {
1950 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1952 // Fail if we don't have a current process.
1953 if (!m_debugged_process_sp ||
1954 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1956 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1959 m_debugged_process_sp ? "invalid process id"
1960 : "null m_debugged_process_sp");
1961 return SendOKResponse();
1964 StreamGDBRemote response;
1965 response.PutChar('m');
1969 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1972 NativeThreadProtocolSP thread_sp;
1973 uint32_t thread_index;
1974 for (thread_index = 0,
1975 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1976 thread_sp; ++thread_index,
1977 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1980 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1981 "(%s, tid=0x%" PRIx64 ")",
1982 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1983 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1984 if (thread_index > 0)
1985 response.PutChar(',');
1986 response.Printf("%" PRIx64, thread_sp->GetID());
1991 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1994 return SendPacketNoLock(response.GetString());
1997 GDBRemoteCommunication::PacketResult
1998 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1999 StringExtractorGDBRemote &packet) {
2000 // FIXME for now we return the full thread list in the initial packet and
2001 // always do nothing here.
2002 return SendPacketNoLock("l");
2005 GDBRemoteCommunication::PacketResult
2006 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2007 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2009 // Parse out the register number from the request.
2010 packet.SetFilePos(strlen("p"));
2011 const uint32_t reg_index =
2012 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2013 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2015 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2016 "parse register number from request \"%s\"",
2017 __FUNCTION__, packet.GetStringRef().c_str());
2018 return SendErrorResponse(0x15);
2021 // Get the thread to use.
2022 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2026 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2028 return SendErrorResponse(0x15);
2031 // Get the thread's register context.
2032 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2033 if (!reg_context_sp) {
2036 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2037 " failed, no register context available for the thread",
2038 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2039 return SendErrorResponse(0x15);
2042 // Return the end of registers response if we've iterated one past the end of
2043 // the register set.
2044 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2046 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2047 "register %" PRIu32 " beyond register count %" PRIu32,
2048 __FUNCTION__, reg_index,
2049 reg_context_sp->GetUserRegisterCount());
2050 return SendErrorResponse(0x15);
2053 const RegisterInfo *reg_info =
2054 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2057 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2058 "register %" PRIu32 " returned NULL",
2059 __FUNCTION__, reg_index);
2060 return SendErrorResponse(0x15);
2063 // Build the reginfos response.
2064 StreamGDBRemote response;
2066 // Retrieve the value
2067 RegisterValue reg_value;
2068 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
2071 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2072 "requested register %" PRIu32 " (%s) failed: %s",
2073 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2074 return SendErrorResponse(0x15);
2077 const uint8_t *const data =
2078 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2081 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2082 "bytes from requested register %" PRIu32,
2083 __FUNCTION__, reg_index);
2084 return SendErrorResponse(0x15);
2087 // FIXME flip as needed to get data in big/little endian format for this host.
2088 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2089 response.PutHex8(data[i]);
2091 return SendPacketNoLock(response.GetString());
2094 GDBRemoteCommunication::PacketResult
2095 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2096 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2098 // Ensure there is more content.
2099 if (packet.GetBytesLeft() < 1)
2100 return SendIllFormedResponse(packet, "Empty P packet");
2102 // Parse out the register number from the request.
2103 packet.SetFilePos(strlen("P"));
2104 const uint32_t reg_index =
2105 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2106 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2108 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2109 "parse register number from request \"%s\"",
2110 __FUNCTION__, packet.GetStringRef().c_str());
2111 return SendErrorResponse(0x29);
2114 // Note debugserver would send an E30 here.
2115 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2116 return SendIllFormedResponse(
2117 packet, "P packet missing '=' char after register number");
2119 // Get process architecture.
2120 ArchSpec process_arch;
2121 if (!m_debugged_process_sp ||
2122 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2124 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2125 "inferior architecture",
2127 return SendErrorResponse(0x49);
2130 // Parse out the value.
2131 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2132 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2134 // Get the thread to use.
2135 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2138 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2139 "available (thread index 0)",
2141 return SendErrorResponse(0x28);
2144 // Get the thread's register context.
2145 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2146 if (!reg_context_sp) {
2149 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2150 " failed, no register context available for the thread",
2151 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2152 return SendErrorResponse(0x15);
2155 const RegisterInfo *reg_info =
2156 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2159 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2160 "register %" PRIu32 " returned NULL",
2161 __FUNCTION__, reg_index);
2162 return SendErrorResponse(0x48);
2165 // Return the end of registers response if we've iterated one past the end of
2166 // the register set.
2167 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2169 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2170 "register %" PRIu32 " beyond register count %" PRIu32,
2171 __FUNCTION__, reg_index,
2172 reg_context_sp->GetUserRegisterCount());
2173 return SendErrorResponse(0x47);
2176 // The dwarf expression are evaluate on host site
2177 // which may cause register size to change
2178 // Hence the reg_size may not be same as reg_info->bytes_size
2179 if ((reg_size != reg_info->byte_size) &&
2180 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2181 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2184 // Build the reginfos response.
2185 StreamGDBRemote response;
2187 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
2188 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
2191 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2192 "requested register %" PRIu32 " (%s) failed: %s",
2193 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2194 return SendErrorResponse(0x32);
2197 return SendOKResponse();
2200 GDBRemoteCommunication::PacketResult
2201 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2202 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2204 // Fail if we don't have a current process.
2205 if (!m_debugged_process_sp ||
2206 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2209 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2211 return SendErrorResponse(0x15);
2214 // Parse out which variant of $H is requested.
2215 packet.SetFilePos(strlen("H"));
2216 if (packet.GetBytesLeft() < 1) {
2218 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2219 "missing {g,c} variant",
2221 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2224 const char h_variant = packet.GetChar();
2225 switch (h_variant) {
2235 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2236 __FUNCTION__, h_variant);
2237 return SendIllFormedResponse(packet,
2238 "H variant unsupported, should be c or g");
2241 // Parse out the thread number.
2242 // FIXME return a parse success/fail value. All values are valid here.
2243 const lldb::tid_t tid =
2244 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2246 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2248 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2249 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2252 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2255 return SendErrorResponse(0x15);
2259 // Now switch the given thread type.
2260 switch (h_variant) {
2262 SetCurrentThreadID(tid);
2266 SetContinueThreadID(tid);
2270 assert(false && "unsupported $H variant - shouldn't get here");
2271 return SendIllFormedResponse(packet,
2272 "H variant unsupported, should be c or g");
2275 return SendOKResponse();
2278 GDBRemoteCommunication::PacketResult
2279 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2280 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2282 // Fail if we don't have a current process.
2283 if (!m_debugged_process_sp ||
2284 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2287 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2289 return SendErrorResponse(0x15);
2292 packet.SetFilePos(::strlen("I"));
2295 size_t read = packet.GetHexBytesAvail(tmp);
2299 // write directly to stdin *this might block if stdin buffer is full*
2300 // TODO: enqueue this block in circular buffer and send window size to
2302 ConnectionStatus status;
2304 m_stdio_communication.Write(tmp, read, status, &error);
2306 return SendErrorResponse(0x15);
2310 return SendOKResponse();
2313 GDBRemoteCommunication::PacketResult
2314 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2315 StringExtractorGDBRemote &packet) {
2316 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2318 // Fail if we don't have a current process.
2319 if (!m_debugged_process_sp ||
2320 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2323 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2325 return SendErrorResponse(0x15);
2328 // Interrupt the process.
2329 Status error = m_debugged_process_sp->Interrupt();
2333 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2335 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
2337 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2341 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2342 __FUNCTION__, m_debugged_process_sp->GetID());
2344 // No response required from stop all.
2345 return PacketResult::Success;
2348 GDBRemoteCommunication::PacketResult
2349 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2350 StringExtractorGDBRemote &packet) {
2351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2353 if (!m_debugged_process_sp ||
2354 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2357 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2359 return SendErrorResponse(0x15);
2362 // Parse out the memory address.
2363 packet.SetFilePos(strlen("m"));
2364 if (packet.GetBytesLeft() < 1)
2365 return SendIllFormedResponse(packet, "Too short m packet");
2367 // Read the address. Punting on validation.
2368 // FIXME replace with Hex U64 read with no default value that fails on failed
2370 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2373 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2374 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2376 // Get # bytes to read.
2377 if (packet.GetBytesLeft() < 1)
2378 return SendIllFormedResponse(packet, "Length missing in m packet");
2380 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2381 if (byte_count == 0) {
2383 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2384 "zero-length packet",
2386 return SendOKResponse();
2389 // Allocate the response buffer.
2390 std::string buf(byte_count, '\0');
2392 return SendErrorResponse(0x78);
2394 // Retrieve the process memory.
2395 size_t bytes_read = 0;
2396 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2397 read_addr, &buf[0], byte_count, bytes_read);
2400 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2401 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2402 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2404 return SendErrorResponse(0x08);
2407 if (bytes_read == 0) {
2409 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2410 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2411 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2413 return SendErrorResponse(0x08);
2416 StreamGDBRemote response;
2417 packet.SetFilePos(0);
2418 char kind = packet.GetChar('?');
2420 response.PutEscapedBytes(buf.data(), byte_count);
2422 assert(kind == 'm');
2423 for (size_t i = 0; i < bytes_read; ++i)
2424 response.PutHex8(buf[i]);
2427 return SendPacketNoLock(response.GetString());
2430 GDBRemoteCommunication::PacketResult
2431 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2432 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2434 if (!m_debugged_process_sp ||
2435 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2438 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2440 return SendErrorResponse(0x15);
2443 // Parse out the memory address.
2444 packet.SetFilePos(strlen("M"));
2445 if (packet.GetBytesLeft() < 1)
2446 return SendIllFormedResponse(packet, "Too short M packet");
2448 // Read the address. Punting on validation.
2449 // FIXME replace with Hex U64 read with no default value that fails on failed
2451 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2454 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2455 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2457 // Get # bytes to read.
2458 if (packet.GetBytesLeft() < 1)
2459 return SendIllFormedResponse(packet, "Length missing in M packet");
2461 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2462 if (byte_count == 0) {
2464 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2465 "zero-length packet",
2467 return PacketResult::Success;
2471 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2472 return SendIllFormedResponse(
2473 packet, "Comma sep missing in M packet after byte length");
2475 // Allocate the conversion buffer.
2476 std::vector<uint8_t> buf(byte_count, 0);
2478 return SendErrorResponse(0x78);
2480 // Convert the hex memory write contents to bytes.
2481 StreamGDBRemote response;
2482 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2483 if (convert_count != byte_count) {
2485 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2486 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2487 " bytes, but only found %" PRIu64 " to convert.",
2488 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2489 byte_count, convert_count);
2490 return SendIllFormedResponse(packet, "M content byte length specified did "
2491 "not match hex-encoded content "
2495 // Write the process memory.
2496 size_t bytes_written = 0;
2497 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2498 byte_count, bytes_written);
2501 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2502 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2503 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2505 return SendErrorResponse(0x09);
2508 if (bytes_written == 0) {
2510 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2511 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2512 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2514 return SendErrorResponse(0x09);
2517 return SendOKResponse();
2520 GDBRemoteCommunication::PacketResult
2521 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2522 StringExtractorGDBRemote &packet) {
2523 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2525 // Currently only the NativeProcessProtocol knows if it can handle a
2526 // qMemoryRegionInfoSupported
2527 // request, but we're not guaranteed to be attached to a process. For now
2529 // client only asks this when a process is being debugged.
2531 // Ensure we have a process running; otherwise, we can't figure this out
2532 // since we won't have a NativeProcessProtocol.
2533 if (!m_debugged_process_sp ||
2534 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2537 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2539 return SendErrorResponse(0x15);
2542 // Test if we can get any region back when asking for the region around NULL.
2543 MemoryRegionInfo region_info;
2544 const Status error =
2545 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2547 // We don't support memory region info collection for this
2548 // NativeProcessProtocol.
2549 return SendUnimplementedResponse("");
2552 return SendOKResponse();
2555 GDBRemoteCommunication::PacketResult
2556 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2557 StringExtractorGDBRemote &packet) {
2558 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2560 // Ensure we have a process.
2561 if (!m_debugged_process_sp ||
2562 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2565 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2567 return SendErrorResponse(0x15);
2570 // Parse out the memory address.
2571 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2572 if (packet.GetBytesLeft() < 1)
2573 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2575 // Read the address. Punting on validation.
2576 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2578 StreamGDBRemote response;
2580 // Get the memory region info for the target address.
2581 MemoryRegionInfo region_info;
2582 const Status error =
2583 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2585 // Return the error message.
2587 response.PutCString("error:");
2588 response.PutCStringAsRawHex8(error.AsCString());
2589 response.PutChar(';');
2591 // Range start and size.
2592 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2593 region_info.GetRange().GetRangeBase(),
2594 region_info.GetRange().GetByteSize());
2597 if (region_info.GetReadable() || region_info.GetWritable() ||
2598 region_info.GetExecutable()) {
2599 // Write permissions info.
2600 response.PutCString("permissions:");
2602 if (region_info.GetReadable())
2603 response.PutChar('r');
2604 if (region_info.GetWritable())
2605 response.PutChar('w');
2606 if (region_info.GetExecutable())
2607 response.PutChar('x');
2609 response.PutChar(';');
2613 ConstString name = region_info.GetName();
2615 response.PutCString("name:");
2616 response.PutCStringAsRawHex8(name.AsCString());
2617 response.PutChar(';');
2621 return SendPacketNoLock(response.GetString());
2624 GDBRemoteCommunication::PacketResult
2625 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2626 // Ensure we have a process.
2627 if (!m_debugged_process_sp ||
2628 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2629 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2632 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2634 return SendErrorResponse(0x15);
2637 // Parse out software or hardware breakpoint or watchpoint requested.
2638 packet.SetFilePos(strlen("Z"));
2639 if (packet.GetBytesLeft() < 1)
2640 return SendIllFormedResponse(
2641 packet, "Too short Z packet, missing software/hardware specifier");
2643 bool want_breakpoint = true;
2644 bool want_hardware = false;
2645 uint32_t watch_flags = 0;
2647 const GDBStoppointType stoppoint_type =
2648 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2649 switch (stoppoint_type) {
2650 case eBreakpointSoftware:
2651 want_hardware = false;
2652 want_breakpoint = true;
2654 case eBreakpointHardware:
2655 want_hardware = true;
2656 want_breakpoint = true;
2658 case eWatchpointWrite:
2660 want_hardware = true;
2661 want_breakpoint = false;
2663 case eWatchpointRead:
2665 want_hardware = true;
2666 want_breakpoint = false;
2668 case eWatchpointReadWrite:
2670 want_hardware = true;
2671 want_breakpoint = false;
2673 case eStoppointInvalid:
2674 return SendIllFormedResponse(
2675 packet, "Z packet had invalid software/hardware specifier");
2678 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2679 return SendIllFormedResponse(
2680 packet, "Malformed Z packet, expecting comma after stoppoint type");
2682 // Parse out the stoppoint address.
2683 if (packet.GetBytesLeft() < 1)
2684 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2685 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2687 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2688 return SendIllFormedResponse(
2689 packet, "Malformed Z packet, expecting comma after address");
2691 // Parse out the stoppoint size (i.e. size hint for opcode size).
2692 const uint32_t size =
2693 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2694 if (size == std::numeric_limits<uint32_t>::max())
2695 return SendIllFormedResponse(
2696 packet, "Malformed Z packet, failed to parse size argument");
2698 if (want_breakpoint) {
2699 // Try to set the breakpoint.
2700 const Status error =
2701 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2702 if (error.Success())
2703 return SendOKResponse();
2704 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2706 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2707 " failed to set breakpoint: %s",
2708 __FUNCTION__, m_debugged_process_sp->GetID(),
2710 return SendErrorResponse(0x09);
2712 // Try to set the watchpoint.
2713 const Status error = m_debugged_process_sp->SetWatchpoint(
2714 addr, size, watch_flags, want_hardware);
2715 if (error.Success())
2716 return SendOKResponse();
2717 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2719 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2720 " failed to set watchpoint: %s",
2721 __FUNCTION__, m_debugged_process_sp->GetID(),
2723 return SendErrorResponse(0x09);
2727 GDBRemoteCommunication::PacketResult
2728 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2729 // Ensure we have a process.
2730 if (!m_debugged_process_sp ||
2731 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2732 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2735 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2737 return SendErrorResponse(0x15);
2740 // Parse out software or hardware breakpoint or watchpoint requested.
2741 packet.SetFilePos(strlen("z"));
2742 if (packet.GetBytesLeft() < 1)
2743 return SendIllFormedResponse(
2744 packet, "Too short z packet, missing software/hardware specifier");
2746 bool want_breakpoint = true;
2747 bool want_hardware = false;
2749 const GDBStoppointType stoppoint_type =
2750 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2751 switch (stoppoint_type) {
2752 case eBreakpointHardware:
2753 want_breakpoint = true;
2754 want_hardware = true;
2756 case eBreakpointSoftware:
2757 want_breakpoint = true;
2759 case eWatchpointWrite:
2760 want_breakpoint = false;
2762 case eWatchpointRead:
2763 want_breakpoint = false;
2765 case eWatchpointReadWrite:
2766 want_breakpoint = false;
2769 return SendIllFormedResponse(
2770 packet, "z packet had invalid software/hardware specifier");
2773 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2774 return SendIllFormedResponse(
2775 packet, "Malformed z packet, expecting comma after stoppoint type");
2777 // Parse out the stoppoint address.
2778 if (packet.GetBytesLeft() < 1)
2779 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2780 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2782 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2783 return SendIllFormedResponse(
2784 packet, "Malformed z packet, expecting comma after address");
2787 // Parse out the stoppoint size (i.e. size hint for opcode size).
2788 const uint32_t size = packet.GetHexMaxU32 (false,
2789 std::numeric_limits<uint32_t>::max ());
2790 if (size == std::numeric_limits<uint32_t>::max ())
2791 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2795 if (want_breakpoint) {
2796 // Try to clear the breakpoint.
2797 const Status error =
2798 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
2799 if (error.Success())
2800 return SendOKResponse();
2801 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2803 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2804 " failed to remove breakpoint: %s",
2805 __FUNCTION__, m_debugged_process_sp->GetID(),
2807 return SendErrorResponse(0x09);
2809 // Try to clear the watchpoint.
2810 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
2811 if (error.Success())
2812 return SendOKResponse();
2813 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2815 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2816 " failed to remove watchpoint: %s",
2817 __FUNCTION__, m_debugged_process_sp->GetID(),
2819 return SendErrorResponse(0x09);
2823 GDBRemoteCommunication::PacketResult
2824 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2825 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2827 // Ensure we have a process.
2828 if (!m_debugged_process_sp ||
2829 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2832 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2834 return SendErrorResponse(0x32);
2837 // We first try to use a continue thread id. If any one or any all set, use
2838 // the current thread.
2839 // Bail out if we don't have a thread id.
2840 lldb::tid_t tid = GetContinueThreadID();
2841 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2842 tid = GetCurrentThreadID();
2843 if (tid == LLDB_INVALID_THREAD_ID)
2844 return SendErrorResponse(0x33);
2846 // Double check that we have such a thread.
2847 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2848 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2849 if (!thread_sp || thread_sp->GetID() != tid)
2850 return SendErrorResponse(0x33);
2852 // Create the step action for the given thread.
2853 ResumeAction action = {tid, eStateStepping, 0};
2855 // Setup the actions list.
2856 ResumeActionList actions;
2857 actions.Append(action);
2859 // All other threads stop while we're single stepping a thread.
2860 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2861 Status error = m_debugged_process_sp->Resume(actions);
2864 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2865 " tid %" PRIu64 " Resume() failed with error: %s",
2866 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2868 return SendErrorResponse(0x49);
2871 // No response here - the stop or exit will come from the resulting action.
2872 return PacketResult::Success;
2875 GDBRemoteCommunication::PacketResult
2876 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2877 StringExtractorGDBRemote &packet) {
2878 // *BSD impls should be able to do this too.
2879 #if defined(__linux__) || defined(__NetBSD__)
2880 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2882 // Parse out the offset.
2883 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2884 if (packet.GetBytesLeft() < 1)
2885 return SendIllFormedResponse(packet,
2886 "qXfer:auxv:read:: packet missing offset");
2888 const uint64_t auxv_offset =
2889 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2890 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2891 return SendIllFormedResponse(packet,
2892 "qXfer:auxv:read:: packet missing offset");
2895 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2896 return SendIllFormedResponse(
2897 packet, "qXfer:auxv:read:: packet missing comma after offset");
2899 // Parse out the length.
2900 const uint64_t auxv_length =
2901 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2902 if (auxv_length == std::numeric_limits<uint64_t>::max())
2903 return SendIllFormedResponse(packet,
2904 "qXfer:auxv:read:: packet missing length");
2906 // Grab the auxv data if we need it.
2907 if (!m_active_auxv_buffer_up) {
2908 // Make sure we have a valid process.
2909 if (!m_debugged_process_sp ||
2910 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2913 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2915 return SendErrorResponse(0x10);
2918 // Grab the auxv data.
2919 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2920 if (!buffer_or_error) {
2921 std::error_code ec = buffer_or_error.getError();
2922 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2923 return SendErrorResponse(ec.value());
2925 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2928 StreamGDBRemote response;
2929 bool done_with_buffer = false;
2931 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2932 if (auxv_offset >= buffer.size()) {
2933 // We have nothing left to send. Mark the buffer as complete.
2934 response.PutChar('l');
2935 done_with_buffer = true;
2937 // Figure out how many bytes are available starting at the given offset.
2938 buffer = buffer.drop_front(auxv_offset);
2940 // Mark the response type according to whether we're reading the remainder
2941 // of the auxv data.
2942 if (auxv_length >= buffer.size()) {
2943 // There will be nothing left to read after this
2944 response.PutChar('l');
2945 done_with_buffer = true;
2947 // There will still be bytes to read after this request.
2948 response.PutChar('m');
2949 buffer = buffer.take_front(auxv_length);
2952 // Now write the data in encoded binary form.
2953 response.PutEscapedBytes(buffer.data(), buffer.size());
2956 if (done_with_buffer)
2957 m_active_auxv_buffer_up.reset();
2959 return SendPacketNoLock(response.GetString());
2961 return SendUnimplementedResponse("not implemented on this platform");
2965 GDBRemoteCommunication::PacketResult
2966 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2967 StringExtractorGDBRemote &packet) {
2968 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2970 // Move past packet name.
2971 packet.SetFilePos(strlen("QSaveRegisterState"));
2973 // Get the thread to use.
2974 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2976 if (m_thread_suffix_supported)
2977 return SendIllFormedResponse(
2978 packet, "No thread specified in QSaveRegisterState packet");
2980 return SendIllFormedResponse(packet,
2981 "No thread was is set with the Hg packet");
2984 // Grab the register context for the thread.
2985 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2986 if (!reg_context_sp) {
2989 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2990 " failed, no register context available for the thread",
2991 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2992 return SendErrorResponse(0x15);
2995 // Save registers to a buffer.
2996 DataBufferSP register_data_sp;
2997 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
3000 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3001 " failed to save all register values: %s",
3002 __FUNCTION__, m_debugged_process_sp->GetID(),
3004 return SendErrorResponse(0x75);
3007 // Allocate a new save id.
3008 const uint32_t save_id = GetNextSavedRegistersID();
3009 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3010 "GetNextRegisterSaveID() returned an existing register save id");
3012 // Save the register data buffer under the save id.
3014 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3015 m_saved_registers_map[save_id] = register_data_sp;
3018 // Write the response.
3019 StreamGDBRemote response;
3020 response.Printf("%" PRIu32, save_id);
3021 return SendPacketNoLock(response.GetString());
3024 GDBRemoteCommunication::PacketResult
3025 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3026 StringExtractorGDBRemote &packet) {
3027 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3029 // Parse out save id.
3030 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3031 if (packet.GetBytesLeft() < 1)
3032 return SendIllFormedResponse(
3033 packet, "QRestoreRegisterState packet missing register save id");
3035 const uint32_t save_id = packet.GetU32(0);
3038 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3039 "packet has malformed save id, expecting decimal uint32_t",
3041 return SendErrorResponse(0x76);
3044 // Get the thread to use.
3045 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3047 if (m_thread_suffix_supported)
3048 return SendIllFormedResponse(
3049 packet, "No thread specified in QRestoreRegisterState packet");
3051 return SendIllFormedResponse(packet,
3052 "No thread was is set with the Hg packet");
3055 // Grab the register context for the thread.
3056 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3057 if (!reg_context_sp) {
3060 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3061 " failed, no register context available for the thread",
3062 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3063 return SendErrorResponse(0x15);
3066 // Retrieve register state buffer, then remove from the list.
3067 DataBufferSP register_data_sp;
3069 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3071 // Find the register set buffer for the given save id.
3072 auto it = m_saved_registers_map.find(save_id);
3073 if (it == m_saved_registers_map.end()) {
3075 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3076 " does not have a register set save buffer for id %" PRIu32,
3077 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3078 return SendErrorResponse(0x77);
3080 register_data_sp = it->second;
3082 // Remove it from the map.
3083 m_saved_registers_map.erase(it);
3086 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
3089 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3090 " failed to restore all register values: %s",
3091 __FUNCTION__, m_debugged_process_sp->GetID(),
3093 return SendErrorResponse(0x77);
3096 return SendOKResponse();
3099 GDBRemoteCommunication::PacketResult
3100 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3101 StringExtractorGDBRemote &packet) {
3102 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3104 // Consume the ';' after vAttach.
3105 packet.SetFilePos(strlen("vAttach"));
3106 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3107 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3109 // Grab the PID to which we will attach (assume hex encoding).
3110 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3111 if (pid == LLDB_INVALID_PROCESS_ID)
3112 return SendIllFormedResponse(packet,
3113 "vAttach failed to parse the process id");
3115 // Attempt to attach.
3117 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3121 Status error = AttachToProcess(pid);
3125 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3126 "pid %" PRIu64 ": %s\n",
3127 __FUNCTION__, pid, error.AsCString());
3128 return SendErrorResponse(0x01);
3131 // Notify we attached by sending a stop packet.
3132 return SendStopReasonForState(m_debugged_process_sp->GetState());
3135 GDBRemoteCommunication::PacketResult
3136 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3137 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3139 StopSTDIOForwarding();
3141 // Fail if we don't have a current process.
3142 if (!m_debugged_process_sp ||
3143 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3146 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3148 return SendErrorResponse(0x15);
3151 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3153 // Consume the ';' after D.
3154 packet.SetFilePos(1);
3155 if (packet.GetBytesLeft()) {
3156 if (packet.GetChar() != ';')
3157 return SendIllFormedResponse(packet, "D missing expected ';'");
3159 // Grab the PID from which we will detach (assume hex encoding).
3160 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3161 if (pid == LLDB_INVALID_PROCESS_ID)
3162 return SendIllFormedResponse(packet, "D failed to parse the process id");
3165 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3166 return SendIllFormedResponse(packet, "Invalid pid");
3169 const Status error = m_debugged_process_sp->Detach();
3172 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3173 "pid %" PRIu64 ": %s\n",
3174 __FUNCTION__, m_debugged_process_sp->GetID(),
3176 return SendErrorResponse(0x01);
3179 return SendOKResponse();
3182 GDBRemoteCommunication::PacketResult
3183 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3184 StringExtractorGDBRemote &packet) {
3185 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3187 packet.SetFilePos(strlen("qThreadStopInfo"));
3188 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3189 if (tid == LLDB_INVALID_THREAD_ID) {
3191 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3192 "parse thread id from request \"%s\"",
3193 __FUNCTION__, packet.GetStringRef().c_str());
3194 return SendErrorResponse(0x15);
3196 return SendStopReplyPacketForThread(tid);
3199 GDBRemoteCommunication::PacketResult
3200 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3201 StringExtractorGDBRemote &) {
3202 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3204 // Ensure we have a debugged process.
3205 if (!m_debugged_process_sp ||
3206 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3207 return SendErrorResponse(50);
3210 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3212 __FUNCTION__, m_debugged_process_sp->GetID());
3214 StreamString response;
3215 const bool threads_with_valid_stop_info_only = false;
3216 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3217 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3218 if (!threads_array_sp) {
3220 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3221 "packet for pid %" PRIu64,
3222 __FUNCTION__, m_debugged_process_sp->GetID());
3223 return SendErrorResponse(52);
3226 threads_array_sp->Write(response);
3227 StreamGDBRemote escaped_response;
3228 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3229 return SendPacketNoLock(escaped_response.GetString());
3232 GDBRemoteCommunication::PacketResult
3233 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3234 StringExtractorGDBRemote &packet) {
3235 // Fail if we don't have a current process.
3236 if (!m_debugged_process_sp ||
3237 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3238 return SendErrorResponse(68);
3240 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3241 if (packet.GetBytesLeft() == 0)
3242 return SendOKResponse();
3243 if (packet.GetChar() != ':')
3244 return SendErrorResponse(67);
3246 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3248 StreamGDBRemote response;
3249 if (hw_debug_cap == llvm::None)
3250 response.Printf("num:0;");
3252 response.Printf("num:%d;", hw_debug_cap->second);
3254 return SendPacketNoLock(response.GetString());
3257 GDBRemoteCommunication::PacketResult
3258 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3259 StringExtractorGDBRemote &packet) {
3260 // Fail if we don't have a current process.
3261 if (!m_debugged_process_sp ||
3262 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3263 return SendErrorResponse(67);
3265 packet.SetFilePos(strlen("qFileLoadAddress:"));
3266 if (packet.GetBytesLeft() == 0)
3267 return SendErrorResponse(68);
3269 std::string file_name;
3270 packet.GetHexByteString(file_name);
3272 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3274 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3276 return SendErrorResponse(69);
3278 if (file_load_address == LLDB_INVALID_ADDRESS)
3279 return SendErrorResponse(1); // File not loaded
3281 StreamGDBRemote response;
3282 response.PutHex64(file_load_address);
3283 return SendPacketNoLock(response.GetString());
3286 GDBRemoteCommunication::PacketResult
3287 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3288 StringExtractorGDBRemote &packet) {
3289 std::vector<int> signals;
3290 packet.SetFilePos(strlen("QPassSignals:"));
3292 // Read sequence of hex signal numbers divided by a semicolon and
3293 // optionally spaces.
3294 while (packet.GetBytesLeft() > 0) {
3295 int signal = packet.GetS32(-1, 16);
3297 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3298 signals.push_back(signal);
3300 packet.SkipSpaces();
3301 char separator = packet.GetChar();
3302 if (separator == '\0')
3303 break; // End of string
3304 if (separator != ';')
3305 return SendIllFormedResponse(packet, "Invalid separator,"
3306 " expected semicolon.");
3309 // Fail if we don't have a current process.
3310 if (!m_debugged_process_sp)
3311 return SendErrorResponse(68);
3313 Status error = m_debugged_process_sp->IgnoreSignals(signals);
3315 return SendErrorResponse(69);
3317 return SendOKResponse();
3320 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3321 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3323 // Tell the stdio connection to shut down.
3324 if (m_stdio_communication.IsConnected()) {
3325 auto connection = m_stdio_communication.GetConnection();
3328 connection->Disconnect(&error);
3330 if (error.Success()) {
3332 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3333 "terminal stdio - SUCCESS",
3337 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3338 "terminal stdio - FAIL: %s",
3339 __FUNCTION__, error.AsCString());
3345 NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3346 StringExtractorGDBRemote &packet) {
3347 NativeThreadProtocolSP thread_sp;
3349 // We have no thread if we don't have a process.
3350 if (!m_debugged_process_sp ||
3351 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3354 // If the client hasn't asked for thread suffix support, there will not be a
3356 // Use the current thread in that case.
3357 if (!m_thread_suffix_supported) {
3358 const lldb::tid_t current_tid = GetCurrentThreadID();
3359 if (current_tid == LLDB_INVALID_THREAD_ID)
3361 else if (current_tid == 0) {
3363 return m_debugged_process_sp->GetThreadAtIndex(0);
3365 return m_debugged_process_sp->GetThreadByID(current_tid);
3368 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3370 // Parse out the ';'.
3371 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3373 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3374 "error: expected ';' prior to start of thread suffix: packet "
3376 __FUNCTION__, packet.GetStringRef().c_str());
3380 if (!packet.GetBytesLeft())
3383 // Parse out thread: portion.
3384 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3386 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3387 "error: expected 'thread:' but not found, packet contents = "
3389 __FUNCTION__, packet.GetStringRef().c_str());
3392 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3393 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3395 return m_debugged_process_sp->GetThreadByID(tid);
3400 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3401 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3402 // Use whatever the debug process says is the current thread id
3403 // since the protocol either didn't specify or specified we want
3404 // any/all threads marked as the current thread.
3405 if (!m_debugged_process_sp)
3406 return LLDB_INVALID_THREAD_ID;
3407 return m_debugged_process_sp->GetCurrentThreadID();
3409 // Use the specific current thread id set by the gdb remote protocol.
3410 return m_current_tid;
3413 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3414 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3415 return m_next_saved_registers_id++;
3418 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3419 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3421 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3422 m_active_auxv_buffer_up.reset();
3426 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3427 const ArchSpec &arch) {
3428 if (m_debugged_process_sp) {
3430 if (m_debugged_process_sp
3431 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3433 if (file_spec.Exists())
3438 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);