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 ExitType exit_type = ExitType::eExitTypeInvalid;
375 std::string exit_description;
377 const bool got_exit_info =
378 process->GetExitStatus(&exit_type, &return_code, exit_description);
379 if (!got_exit_info) {
381 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
382 ", failed to retrieve process exit status",
383 __FUNCTION__, process->GetID());
385 StreamGDBRemote response;
386 response.PutChar('E');
387 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
388 return SendPacketNoLock(response.GetString());
391 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
392 ", returning exit type %d, return code %d [%s]",
393 __FUNCTION__, process->GetID(), exit_type, return_code,
394 exit_description.c_str());
396 StreamGDBRemote response;
398 char return_type_code;
400 case ExitType::eExitTypeExit:
401 return_type_code = 'W';
403 case ExitType::eExitTypeSignal:
404 return_type_code = 'X';
406 case ExitType::eExitTypeStop:
407 return_type_code = 'S';
409 case ExitType::eExitTypeInvalid:
410 return_type_code = 'E';
413 response.PutChar(return_type_code);
415 // POSIX exit status limited to unsigned 8 bits.
416 response.PutHex8(return_code);
418 return SendPacketNoLock(response.GetString());
422 static void AppendHexValue(StreamString &response, const uint8_t *buf,
423 uint32_t buf_size, bool swap) {
426 for (i = buf_size - 1; i >= 0; i--)
427 response.PutHex8(buf[i]);
429 for (i = 0; i < buf_size; i++)
430 response.PutHex8(buf[i]);
434 static void WriteRegisterValueInHexFixedWidth(
435 StreamString &response, NativeRegisterContextSP ®_ctx_sp,
436 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
437 lldb::ByteOrder byte_order) {
438 RegisterValue reg_value;
440 Status error = reg_ctx_sp->ReadRegister(®_info, reg_value);
442 reg_value_p = ®_value;
447 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
448 reg_value_p->GetByteSize(),
449 byte_order == lldb::eByteOrderLittle);
451 // Zero-out any unreadable values.
452 if (reg_info.byte_size > 0) {
453 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
454 AppendHexValue(response, zeros.data(), zeros.size(), false);
459 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
460 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
462 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
466 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
468 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
469 // Expedite all registers in the first register set (i.e. should be GPRs) that
470 // are not contained in other registers.
471 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
474 for (const uint32_t *reg_num_p = reg_set_p->registers;
475 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
476 uint32_t reg_num = *reg_num_p;
478 // Expedite only a couple of registers until we figure out why sending
481 static const uint32_t k_expedited_registers[] = {
482 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
483 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
485 for (const uint32_t *generic_reg_p = k_expedited_registers;
486 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
487 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
488 eRegisterKindGeneric, *generic_reg_p);
489 if (reg_num == LLDB_INVALID_REGNUM)
490 continue; // Target does not support the given register.
493 const RegisterInfo *const reg_info_p =
494 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
495 if (reg_info_p == nullptr) {
498 "%s failed to get register info for register index %" PRIu32,
499 __FUNCTION__, reg_num);
503 if (reg_info_p->value_regs != nullptr)
504 continue; // Only expedite registers that are not contained in other
507 RegisterValue reg_value;
508 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
511 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
513 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
514 reg_num, error.AsCString());
519 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
520 ®_value, lldb::eByteOrderBig);
522 register_object_sp->SetObject(
523 llvm::to_string(reg_num),
524 std::make_shared<JSONString>(stream.GetString()));
527 return register_object_sp;
530 static const char *GetStopReasonString(StopReason stop_reason) {
531 switch (stop_reason) {
532 case eStopReasonTrace:
534 case eStopReasonBreakpoint:
536 case eStopReasonWatchpoint:
538 case eStopReasonSignal:
540 case eStopReasonException:
542 case eStopReasonExec:
544 case eStopReasonInstrumentation:
545 case eStopReasonInvalid:
546 case eStopReasonPlanComplete:
547 case eStopReasonThreadExiting:
548 case eStopReasonNone:
554 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
556 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
558 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
560 // Ensure we can get info on the given thread.
561 uint32_t thread_idx = 0;
562 for (NativeThreadProtocolSP thread_sp;
563 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
566 lldb::tid_t tid = thread_sp->GetID();
568 // Grab the reason this thread stopped.
569 struct ThreadStopInfo tid_stop_info;
570 std::string description;
571 if (!thread_sp->GetStopReason(tid_stop_info, description))
574 const int signum = tid_stop_info.details.signal.signo;
576 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
578 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
579 __FUNCTION__, process.GetID(), tid, signum,
580 tid_stop_info.reason, tid_stop_info.details.exception.type);
583 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
584 threads_array_sp->AppendObject(thread_obj_sp);
587 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
588 thread_obj_sp->SetObject("registers", registers_sp);
591 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
593 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
595 const std::string thread_name = thread_sp->GetName();
596 if (!thread_name.empty())
597 thread_obj_sp->SetObject("name",
598 std::make_shared<JSONString>(thread_name));
600 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
601 thread_obj_sp->SetObject("reason",
602 std::make_shared<JSONString>(stop_reason_str));
604 if (!description.empty())
605 thread_obj_sp->SetObject("description",
606 std::make_shared<JSONString>(description));
608 if ((tid_stop_info.reason == eStopReasonException) &&
609 tid_stop_info.details.exception.type) {
610 thread_obj_sp->SetObject(
612 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
614 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
615 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
617 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
618 tid_stop_info.details.exception.data[i]));
620 thread_obj_sp->SetObject("medata", medata_array_sp);
623 // TODO: Expedite interesting regions of inferior memory
626 return threads_array_sp;
629 GDBRemoteCommunication::PacketResult
630 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
632 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
634 // Ensure we have a debugged process.
635 if (!m_debugged_process_sp ||
636 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
637 return SendErrorResponse(50);
641 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
643 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
645 // Ensure we can get info on the given thread.
646 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
648 return SendErrorResponse(51);
650 // Grab the reason this thread stopped.
651 struct ThreadStopInfo tid_stop_info;
652 std::string description;
653 if (!thread_sp->GetStopReason(tid_stop_info, description))
654 return SendErrorResponse(52);
656 // FIXME implement register handling for exec'd inferiors.
657 // if (tid_stop_info.reason == eStopReasonExec)
659 // const bool force = true;
660 // InitializeRegisters(force);
663 StreamString response;
664 // Output the T packet with the thread
665 response.PutChar('T');
666 int signum = tid_stop_info.details.signal.signo;
668 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
670 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
671 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
672 tid_stop_info.reason, tid_stop_info.details.exception.type);
675 // Print the signal number.
676 response.PutHex8(signum & 0xff);
679 response.Printf("thread:%" PRIx64 ";", tid);
681 // Include the thread name if there is one.
682 const std::string thread_name = thread_sp->GetName();
683 if (!thread_name.empty()) {
684 size_t thread_name_len = thread_name.length();
686 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
687 response.PutCString("name:");
688 response.PutCString(thread_name);
690 // The thread name contains special chars, send as hex bytes.
691 response.PutCString("hexname:");
692 response.PutCStringAsRawHex8(thread_name.c_str());
694 response.PutChar(';');
697 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
698 // will send all thread IDs back in the "threads" key whose value is
699 // a list of hex thread IDs separated by commas:
700 // "threads:10a,10b,10c;"
701 // This will save the debugger from having to send a pair of qfThreadInfo
702 // and qsThreadInfo packets, but it also might take a lot of room in the
703 // stop reply packet, so it must be enabled only on systems where there
704 // are no limits on packet lengths.
705 if (m_list_threads_in_stop_reply) {
706 response.PutCString("threads:");
708 uint32_t thread_index = 0;
709 NativeThreadProtocolSP listed_thread_sp;
710 for (listed_thread_sp =
711 m_debugged_process_sp->GetThreadAtIndex(thread_index);
712 listed_thread_sp; ++thread_index,
713 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
715 if (thread_index > 0)
716 response.PutChar(',');
717 response.Printf("%" PRIx64, listed_thread_sp->GetID());
719 response.PutChar(';');
721 // Include JSON info that describes the stop reason for any threads
722 // that actually have stop reasons. We use the new "jstopinfo" key
723 // whose values is hex ascii JSON that contains the thread IDs
724 // thread stop info only for threads that have stop reasons. Only send
725 // this if we have more than one thread otherwise this packet has all
726 // the info it needs.
727 if (thread_index > 0) {
728 const bool threads_with_valid_stop_info_only = true;
729 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
730 *m_debugged_process_sp, threads_with_valid_stop_info_only);
731 if (threads_info_sp) {
732 response.PutCString("jstopinfo:");
733 StreamString unescaped_response;
734 threads_info_sp->Write(unescaped_response);
735 response.PutCStringAsRawHex8(unescaped_response.GetData());
736 response.PutChar(';');
738 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
739 "jstopinfo field for pid %" PRIu64,
740 __FUNCTION__, m_debugged_process_sp->GetID());
744 response.PutCString("thread-pcs");
745 char delimiter = ':';
746 for (NativeThreadProtocolSP thread_sp;
747 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
749 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
753 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
754 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
755 const RegisterInfo *const reg_info_p =
756 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
758 RegisterValue reg_value;
759 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
762 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
764 reg_info_p->name ? reg_info_p->name
765 : "<unnamed-register>",
766 reg_to_read, error.AsCString());
770 response.PutChar(delimiter);
772 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
773 ®_value, endian::InlHostByteOrder());
776 response.PutChar(';');
780 // Expedite registers.
783 // Grab the register context.
784 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
786 // Expedite all registers in the first register set (i.e. should be GPRs)
787 // that are not contained in other registers.
788 const RegisterSet *reg_set_p;
789 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
790 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
792 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
793 "from set '%s' (registers set count: %zu)",
795 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
796 reg_set_p->num_registers);
798 for (const uint32_t *reg_num_p = reg_set_p->registers;
799 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
800 const RegisterInfo *const reg_info_p =
801 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
802 if (reg_info_p == nullptr) {
804 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
805 "register info for register set '%s', register index "
808 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
810 } else if (reg_info_p->value_regs == nullptr) {
811 // Only expediate registers that are not contained in other registers.
812 RegisterValue reg_value;
813 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
814 if (error.Success()) {
815 response.Printf("%.02x:", *reg_num_p);
816 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
817 ®_value, lldb::eByteOrderBig);
818 response.PutChar(';');
821 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
822 "register '%s' index %" PRIu32 ": %s",
823 __FUNCTION__, reg_info_p->name ? reg_info_p->name
824 : "<unnamed-register>",
825 *reg_num_p, error.AsCString());
832 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
833 if (reason_str != nullptr) {
834 response.Printf("reason:%s;", reason_str);
837 if (!description.empty()) {
838 // Description may contains special chars, send as hex bytes.
839 response.PutCString("description:");
840 response.PutCStringAsRawHex8(description.c_str());
841 response.PutChar(';');
842 } else if ((tid_stop_info.reason == eStopReasonException) &&
843 tid_stop_info.details.exception.type) {
844 response.PutCString("metype:");
845 response.PutHex64(tid_stop_info.details.exception.type);
846 response.PutCString(";mecount:");
847 response.PutHex32(tid_stop_info.details.exception.data_count);
848 response.PutChar(';');
850 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
851 response.PutCString("medata:");
852 response.PutHex64(tid_stop_info.details.exception.data[i]);
853 response.PutChar(';');
857 return SendPacketNoLock(response.GetString());
860 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
861 NativeProcessProtocol *process) {
862 assert(process && "process cannot be NULL");
864 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
866 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
868 PacketResult result = SendStopReasonForState(StateType::eStateExited);
869 if (result != PacketResult::Success) {
871 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
872 "notification for PID %" PRIu64 ", state: eStateExited",
873 __FUNCTION__, process->GetID());
876 // Close the pipe to the inferior terminal i/o if we launched it
878 MaybeCloseInferiorTerminalConnection();
880 // We are ready to exit the debug monitor.
884 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
885 NativeProcessProtocol *process) {
886 assert(process && "process cannot be NULL");
888 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
890 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
892 // Send the stop reason unless this is the stop after the
894 switch (m_inferior_prev_state) {
895 case eStateLaunching:
896 case eStateAttaching:
897 // Don't send anything per debugserver behavior.
900 // In all other cases, send the stop reason.
901 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
902 if (result != PacketResult::Success) {
904 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
905 "notification for PID %" PRIu64 ", state: eStateExited",
906 __FUNCTION__, process->GetID());
912 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
913 NativeProcessProtocol *process, lldb::StateType state) {
914 assert(process && "process cannot be NULL");
915 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
917 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
918 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
919 __FUNCTION__, process->GetID(), StateAsCString(state));
923 case StateType::eStateRunning:
924 StartSTDIOForwarding();
927 case StateType::eStateStopped:
928 // Make sure we get all of the pending stdout/stderr from the inferior
929 // and send it to the lldb host before we send the state change
932 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
934 // interfere with our protocol.
935 StopSTDIOForwarding();
936 HandleInferiorState_Stopped(process);
939 case StateType::eStateExited:
942 StopSTDIOForwarding();
943 HandleInferiorState_Exited(process);
948 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
949 "change for pid %" PRIu64 ", new state: %s",
950 __FUNCTION__, process->GetID(), StateAsCString(state));
955 // Remember the previous state reported to us.
956 m_inferior_prev_state = state;
959 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
960 ClearProcessSpecificData();
963 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
964 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
966 if (!m_handshake_completed) {
967 if (!HandshakeWithClient()) {
969 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
970 "client failed, exiting",
972 m_mainloop.RequestTermination();
975 m_handshake_completed = true;
978 bool interrupt = false;
982 const PacketResult result = GetPacketAndSendResponse(
983 std::chrono::microseconds(0), error, interrupt, done);
984 if (result == PacketResult::ErrorReplyTimeout)
985 break; // No more packets in the queue
987 if ((result != PacketResult::Success)) {
989 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
991 __FUNCTION__, error.AsCString());
992 m_mainloop.RequestTermination();
998 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
999 std::unique_ptr<Connection> &&connection) {
1000 IOObjectSP read_object_sp = connection->GetReadObject();
1001 GDBRemoteCommunicationServer::SetConnection(connection.release());
1004 m_network_handle_up = m_mainloop.RegisterReadObject(
1005 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1010 GDBRemoteCommunication::PacketResult
1011 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1013 if ((buffer == nullptr) || (len == 0)) {
1015 return PacketResult::Success;
1018 StreamString response;
1019 response.PutChar('O');
1020 response.PutBytesAsRawHex8(buffer, len);
1022 return SendPacketNoLock(response.GetString());
1025 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1028 // Set up the reading/handling of process I/O
1029 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1030 new ConnectionFileDescriptor(fd, true));
1032 error.SetErrorString("failed to create ConnectionFileDescriptor");
1036 m_stdio_communication.SetCloseOnEOF(false);
1037 m_stdio_communication.SetConnection(conn_up.release());
1038 if (!m_stdio_communication.IsConnected()) {
1039 error.SetErrorString(
1040 "failed to set connection for inferior I/O communication");
1047 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1048 // Don't forward if not connected (e.g. when attaching).
1049 if (!m_stdio_communication.IsConnected())
1053 lldbassert(!m_stdio_handle_up);
1054 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1055 m_stdio_communication.GetConnection()->GetReadObject(),
1056 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1058 if (!m_stdio_handle_up) {
1059 // Not much we can do about the failure. Log it and continue without
1061 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1062 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1064 __FUNCTION__, error.AsCString());
1068 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1069 m_stdio_handle_up.reset();
1072 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1074 ConnectionStatus status;
1077 size_t bytes_read = m_stdio_communication.Read(
1078 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1080 case eConnectionStatusSuccess:
1081 SendONotification(buffer, bytes_read);
1083 case eConnectionStatusLostConnection:
1084 case eConnectionStatusEndOfFile:
1085 case eConnectionStatusError:
1086 case eConnectionStatusNoConnection:
1087 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1088 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1089 "forwarding as communication returned status %d (error: "
1091 __FUNCTION__, status, error.AsCString());
1092 m_stdio_handle_up.reset();
1095 case eConnectionStatusInterrupted:
1096 case eConnectionStatusTimedOut:
1102 GDBRemoteCommunication::PacketResult
1103 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1104 StringExtractorGDBRemote &packet) {
1105 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1106 // Fail if we don't have a current process.
1107 if (!m_debugged_process_sp ||
1108 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1109 return SendErrorResponse(68);
1111 if (!packet.ConsumeFront("jTraceStart:"))
1112 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1114 TraceOptions options;
1115 uint64_t type = std::numeric_limits<uint64_t>::max();
1116 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1117 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1118 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1120 auto json_object = StructuredData::ParseJSON(packet.Peek());
1123 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1124 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1126 auto json_dict = json_object->GetAsDictionary();
1128 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1129 options.setMetaDataBufferSize(metabuffersize);
1131 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1132 options.setTraceBufferSize(buffersize);
1134 json_dict->GetValueForKeyAsInteger("type", type);
1135 options.setType(static_cast<lldb::TraceType>(type));
1137 json_dict->GetValueForKeyAsInteger("threadid", tid);
1138 options.setThreadID(tid);
1140 StructuredData::ObjectSP custom_params_sp =
1141 json_dict->GetValueForKey("params");
1142 if (custom_params_sp &&
1143 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1144 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1146 options.setTraceParams(
1147 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1149 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1150 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1151 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1153 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1157 lldb::user_id_t uid = LLDB_INVALID_UID;
1158 uid = m_debugged_process_sp->StartTrace(options, error);
1159 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1161 return SendErrorResponse(error.GetError());
1163 StreamGDBRemote response;
1164 response.Printf("%" PRIx64, uid);
1165 return SendPacketNoLock(response.GetString());
1168 GDBRemoteCommunication::PacketResult
1169 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1170 StringExtractorGDBRemote &packet) {
1171 // Fail if we don't have a current process.
1172 if (!m_debugged_process_sp ||
1173 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1174 return SendErrorResponse(68);
1176 if (!packet.ConsumeFront("jTraceStop:"))
1177 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1179 lldb::user_id_t uid = LLDB_INVALID_UID;
1180 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1182 auto json_object = StructuredData::ParseJSON(packet.Peek());
1185 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1186 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1188 auto json_dict = json_object->GetAsDictionary();
1190 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1191 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1193 json_dict->GetValueForKeyAsInteger("threadid", tid);
1195 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1198 return SendErrorResponse(error.GetError());
1200 return SendOKResponse();
1203 GDBRemoteCommunication::PacketResult
1204 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1205 StringExtractorGDBRemote &packet) {
1207 // Fail if we don't have a current process.
1208 if (!m_debugged_process_sp ||
1209 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1210 return SendErrorResponse(68);
1212 if (!packet.ConsumeFront("jTraceConfigRead:"))
1213 return SendIllFormedResponse(packet,
1214 "jTraceConfigRead: Ill formed packet ");
1216 lldb::user_id_t uid = LLDB_INVALID_UID;
1217 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1219 auto json_object = StructuredData::ParseJSON(packet.Peek());
1222 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1223 return SendIllFormedResponse(packet,
1224 "jTraceConfigRead: Ill formed packet ");
1226 auto json_dict = json_object->GetAsDictionary();
1228 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1229 return SendIllFormedResponse(packet,
1230 "jTraceConfigRead: Ill formed packet ");
1232 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1234 TraceOptions options;
1235 StreamGDBRemote response;
1237 options.setThreadID(threadid);
1238 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1241 return SendErrorResponse(error.GetError());
1243 StreamGDBRemote escaped_response;
1244 StructuredData::Dictionary json_packet;
1246 json_packet.AddIntegerItem("type", options.getType());
1247 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1248 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1250 StructuredData::DictionarySP custom_params = options.getTraceParams();
1252 json_packet.AddItem("params", custom_params);
1254 StreamString json_string;
1255 json_packet.Dump(json_string, false);
1256 escaped_response.PutEscapedBytes(json_string.GetData(),
1257 json_string.GetSize());
1258 return SendPacketNoLock(escaped_response.GetString());
1261 GDBRemoteCommunication::PacketResult
1262 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1263 StringExtractorGDBRemote &packet) {
1265 // Fail if we don't have a current process.
1266 if (!m_debugged_process_sp ||
1267 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1268 return SendErrorResponse(68);
1270 enum PacketType { MetaData, BufferData };
1271 PacketType tracetype = MetaData;
1273 if (packet.ConsumeFront("jTraceBufferRead:"))
1274 tracetype = BufferData;
1275 else if (packet.ConsumeFront("jTraceMetaRead:"))
1276 tracetype = MetaData;
1278 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1281 lldb::user_id_t uid = LLDB_INVALID_UID;
1283 size_t byte_count = std::numeric_limits<size_t>::max();
1284 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1285 size_t offset = std::numeric_limits<size_t>::max();
1287 auto json_object = StructuredData::ParseJSON(packet.Peek());
1290 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1291 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1293 auto json_dict = json_object->GetAsDictionary();
1295 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1296 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1297 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1298 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1300 json_dict->GetValueForKeyAsInteger("threadid", tid);
1302 // Allocate the response buffer.
1303 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1305 return SendErrorResponse(0x78);
1307 StreamGDBRemote response;
1309 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1311 if (tracetype == BufferData)
1312 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1313 else if (tracetype == MetaData)
1314 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1317 return SendErrorResponse(error.GetError());
1319 for (size_t i = 0; i < buf.size(); ++i)
1320 response.PutHex8(buf[i]);
1322 StreamGDBRemote escaped_response;
1323 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1324 return SendPacketNoLock(escaped_response.GetString());
1327 GDBRemoteCommunication::PacketResult
1328 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1329 StringExtractorGDBRemote &packet) {
1330 // Fail if we don't have a current process.
1331 if (!m_debugged_process_sp ||
1332 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1333 return SendErrorResponse(68);
1335 lldb::pid_t pid = m_debugged_process_sp->GetID();
1337 if (pid == LLDB_INVALID_PROCESS_ID)
1338 return SendErrorResponse(1);
1340 ProcessInstanceInfo proc_info;
1341 if (!Host::GetProcessInfo(pid, proc_info))
1342 return SendErrorResponse(1);
1344 StreamString response;
1345 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1346 return SendPacketNoLock(response.GetString());
1349 GDBRemoteCommunication::PacketResult
1350 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1351 // Fail if we don't have a current process.
1352 if (!m_debugged_process_sp ||
1353 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1354 return SendErrorResponse(68);
1356 // Make sure we set the current thread so g and p packets return
1357 // the data the gdb will expect.
1358 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1359 SetCurrentThreadID(tid);
1361 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1363 return SendErrorResponse(69);
1365 StreamString response;
1366 response.Printf("QC%" PRIx64, thread_sp->GetID());
1368 return SendPacketNoLock(response.GetString());
1371 GDBRemoteCommunication::PacketResult
1372 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1373 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1375 StopSTDIOForwarding();
1377 if (!m_debugged_process_sp) {
1380 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1382 return PacketResult::Success;
1385 Status error = m_debugged_process_sp->Kill();
1386 if (error.Fail() && log)
1387 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1388 "process %" PRIu64 ": %s",
1389 __FUNCTION__, m_debugged_process_sp->GetID(),
1392 // No OK response for kill packet.
1393 // return SendOKResponse ();
1394 return PacketResult::Success;
1397 GDBRemoteCommunication::PacketResult
1398 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1399 StringExtractorGDBRemote &packet) {
1400 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1401 if (packet.GetU32(0))
1402 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1404 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1405 return SendOKResponse();
1408 GDBRemoteCommunication::PacketResult
1409 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1410 StringExtractorGDBRemote &packet) {
1411 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1413 packet.GetHexByteString(path);
1414 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1415 return SendOKResponse();
1418 GDBRemoteCommunication::PacketResult
1419 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1420 StringExtractorGDBRemote &packet) {
1421 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1423 StreamString response;
1424 response.PutCStringAsRawHex8(working_dir.GetCString());
1425 return SendPacketNoLock(response.GetString());
1428 return SendErrorResponse(14);
1431 GDBRemoteCommunication::PacketResult
1432 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1433 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1435 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1437 // Ensure we have a native process.
1438 if (!m_debugged_process_sp) {
1440 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1443 return SendErrorResponse(0x36);
1446 // Pull out the signal number.
1447 packet.SetFilePos(::strlen("C"));
1448 if (packet.GetBytesLeft() < 1) {
1449 // Shouldn't be using a C without a signal.
1450 return SendIllFormedResponse(packet, "C packet specified without signal.");
1452 const uint32_t signo =
1453 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1454 if (signo == std::numeric_limits<uint32_t>::max())
1455 return SendIllFormedResponse(packet, "failed to parse signal number");
1457 // Handle optional continue address.
1458 if (packet.GetBytesLeft() > 0) {
1459 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1460 if (*packet.Peek() == ';')
1461 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1463 return SendIllFormedResponse(
1464 packet, "unexpected content after $C{signal-number}");
1467 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1470 // We have two branches: what to do if a continue thread is specified (in
1471 // which case we target
1472 // sending the signal to that thread), or when we don't have a continue thread
1474 // case we send a signal to the process).
1476 // TODO discuss with Greg Clayton, make sure this makes sense.
1478 lldb::tid_t signal_tid = GetContinueThreadID();
1479 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1480 // The resume action for the continue thread (or all threads if a continue
1481 // thread is not set).
1482 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1483 static_cast<int>(signo)};
1485 // Add the action for the continue thread (or all threads when the continue
1486 // thread isn't present).
1487 resume_actions.Append(action);
1489 // Send the signal to the process since we weren't targeting a specific
1490 // continue thread with the signal.
1491 error = m_debugged_process_sp->Signal(signo);
1494 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1495 "signal for process %" PRIu64 ": %s",
1496 __FUNCTION__, m_debugged_process_sp->GetID(),
1499 return SendErrorResponse(0x52);
1503 // Resume the threads.
1504 error = m_debugged_process_sp->Resume(resume_actions);
1507 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1508 "threads for process %" PRIu64 ": %s",
1509 __FUNCTION__, m_debugged_process_sp->GetID(),
1512 return SendErrorResponse(0x38);
1515 // Don't send an "OK" packet; response is the stopped/exited message.
1516 return PacketResult::Success;
1519 GDBRemoteCommunication::PacketResult
1520 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1523 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1525 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1527 // For now just support all continue.
1528 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1529 if (has_continue_address) {
1531 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1532 "c{address} variant [%s remains]",
1533 __FUNCTION__, packet.Peek());
1534 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1537 // Ensure we have a native process.
1538 if (!m_debugged_process_sp) {
1540 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1543 return SendErrorResponse(0x36);
1546 // Build the ResumeActionList
1547 ResumeActionList actions(StateType::eStateRunning, 0);
1549 Status error = m_debugged_process_sp->Resume(actions);
1553 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1555 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1557 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1562 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1563 __FUNCTION__, m_debugged_process_sp->GetID());
1565 // No response required from continue.
1566 return PacketResult::Success;
1569 GDBRemoteCommunication::PacketResult
1570 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1571 StringExtractorGDBRemote &packet) {
1572 StreamString response;
1573 response.Printf("vCont;c;C;s;S");
1575 return SendPacketNoLock(response.GetString());
1578 GDBRemoteCommunication::PacketResult
1579 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1580 StringExtractorGDBRemote &packet) {
1581 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1583 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1586 packet.SetFilePos(::strlen("vCont"));
1588 if (packet.GetBytesLeft() == 0) {
1590 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1593 return SendIllFormedResponse(packet, "Missing action from vCont package");
1596 // Check if this is all continue (no options or ";c").
1597 if (::strcmp(packet.Peek(), ";c") == 0) {
1598 // Move past the ';', then do a simple 'c'.
1599 packet.SetFilePos(packet.GetFilePos() + 1);
1600 return Handle_c(packet);
1601 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1602 // Move past the ';', then do a simple 's'.
1603 packet.SetFilePos(packet.GetFilePos() + 1);
1604 return Handle_s(packet);
1607 // Ensure we have a native process.
1608 if (!m_debugged_process_sp) {
1610 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1613 return SendErrorResponse(0x36);
1616 ResumeActionList thread_actions;
1618 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1619 // Skip the semi-colon.
1622 // Build up the thread action.
1623 ResumeAction thread_action;
1624 thread_action.tid = LLDB_INVALID_THREAD_ID;
1625 thread_action.state = eStateInvalid;
1626 thread_action.signal = 0;
1628 const char action = packet.GetChar();
1631 thread_action.signal = packet.GetHexMaxU32(false, 0);
1632 if (thread_action.signal == 0)
1633 return SendIllFormedResponse(
1634 packet, "Could not parse signal in vCont packet C action");
1639 thread_action.state = eStateRunning;
1643 thread_action.signal = packet.GetHexMaxU32(false, 0);
1644 if (thread_action.signal == 0)
1645 return SendIllFormedResponse(
1646 packet, "Could not parse signal in vCont packet S action");
1651 thread_action.state = eStateStepping;
1655 return SendIllFormedResponse(packet, "Unsupported vCont action");
1659 // Parse out optional :{thread-id} value.
1660 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1661 // Consume the separator.
1664 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1665 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1666 return SendIllFormedResponse(
1667 packet, "Could not parse thread number in vCont packet");
1670 thread_actions.Append(thread_action);
1673 Status error = m_debugged_process_sp->Resume(thread_actions);
1676 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1677 "process %" PRIu64 ": %s",
1678 __FUNCTION__, m_debugged_process_sp->GetID(),
1681 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1686 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1687 __FUNCTION__, m_debugged_process_sp->GetID());
1689 // No response required from vCont.
1690 return PacketResult::Success;
1693 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1694 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1696 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1700 m_current_tid = tid;
1701 if (m_debugged_process_sp)
1702 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1705 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1706 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1708 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1712 m_continue_tid = tid;
1715 GDBRemoteCommunication::PacketResult
1716 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1717 StringExtractorGDBRemote &packet) {
1718 // Handle the $? gdbremote command.
1720 // If no process, indicate error
1721 if (!m_debugged_process_sp)
1722 return SendErrorResponse(02);
1724 return SendStopReasonForState(m_debugged_process_sp->GetState());
1727 GDBRemoteCommunication::PacketResult
1728 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1729 lldb::StateType process_state) {
1730 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1732 switch (process_state) {
1733 case eStateAttaching:
1734 case eStateLaunching:
1736 case eStateStepping:
1737 case eStateDetached:
1738 // NOTE: gdb protocol doc looks like it should return $OK
1739 // when everything is running (i.e. no stopped result).
1740 return PacketResult::Success; // Ignore
1742 case eStateSuspended:
1744 case eStateCrashed: {
1745 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1746 // Make sure we set the current thread so g and p packets return
1747 // the data the gdb will expect.
1748 SetCurrentThreadID(tid);
1749 return SendStopReplyPacketForThread(tid);
1753 case eStateUnloaded:
1755 return SendWResponse(m_debugged_process_sp.get());
1759 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1760 ", current state reporting not handled: %s",
1761 __FUNCTION__, m_debugged_process_sp->GetID(),
1762 StateAsCString(process_state));
1767 return SendErrorResponse(0);
1770 GDBRemoteCommunication::PacketResult
1771 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1772 StringExtractorGDBRemote &packet) {
1773 // Fail if we don't have a current process.
1774 if (!m_debugged_process_sp ||
1775 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1776 return SendErrorResponse(68);
1778 // Ensure we have a thread.
1779 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1781 return SendErrorResponse(69);
1783 // Get the register context for the first thread.
1784 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1785 if (!reg_context_sp)
1786 return SendErrorResponse(69);
1788 // Parse out the register number from the request.
1789 packet.SetFilePos(strlen("qRegisterInfo"));
1790 const uint32_t reg_index =
1791 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1792 if (reg_index == std::numeric_limits<uint32_t>::max())
1793 return SendErrorResponse(69);
1795 // Return the end of registers response if we've iterated one past the end of
1796 // the register set.
1797 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1798 return SendErrorResponse(69);
1800 const RegisterInfo *reg_info =
1801 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1803 return SendErrorResponse(69);
1805 // Build the reginfos response.
1806 StreamGDBRemote response;
1808 response.PutCString("name:");
1809 response.PutCString(reg_info->name);
1810 response.PutChar(';');
1812 if (reg_info->alt_name && reg_info->alt_name[0]) {
1813 response.PutCString("alt-name:");
1814 response.PutCString(reg_info->alt_name);
1815 response.PutChar(';');
1818 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1819 reg_info->byte_size * 8, reg_info->byte_offset);
1821 switch (reg_info->encoding) {
1823 response.PutCString("encoding:uint;");
1826 response.PutCString("encoding:sint;");
1828 case eEncodingIEEE754:
1829 response.PutCString("encoding:ieee754;");
1831 case eEncodingVector:
1832 response.PutCString("encoding:vector;");
1838 switch (reg_info->format) {
1840 response.PutCString("format:binary;");
1842 case eFormatDecimal:
1843 response.PutCString("format:decimal;");
1846 response.PutCString("format:hex;");
1849 response.PutCString("format:float;");
1851 case eFormatVectorOfSInt8:
1852 response.PutCString("format:vector-sint8;");
1854 case eFormatVectorOfUInt8:
1855 response.PutCString("format:vector-uint8;");
1857 case eFormatVectorOfSInt16:
1858 response.PutCString("format:vector-sint16;");
1860 case eFormatVectorOfUInt16:
1861 response.PutCString("format:vector-uint16;");
1863 case eFormatVectorOfSInt32:
1864 response.PutCString("format:vector-sint32;");
1866 case eFormatVectorOfUInt32:
1867 response.PutCString("format:vector-uint32;");
1869 case eFormatVectorOfFloat32:
1870 response.PutCString("format:vector-float32;");
1872 case eFormatVectorOfUInt64:
1873 response.PutCString("format:vector-uint64;");
1875 case eFormatVectorOfUInt128:
1876 response.PutCString("format:vector-uint128;");
1882 const char *const register_set_name =
1883 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1884 if (register_set_name) {
1885 response.PutCString("set:");
1886 response.PutCString(register_set_name);
1887 response.PutChar(';');
1890 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1891 LLDB_INVALID_REGNUM)
1892 response.Printf("ehframe:%" PRIu32 ";",
1893 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1895 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1896 response.Printf("dwarf:%" PRIu32 ";",
1897 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1899 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1900 case LLDB_REGNUM_GENERIC_PC:
1901 response.PutCString("generic:pc;");
1903 case LLDB_REGNUM_GENERIC_SP:
1904 response.PutCString("generic:sp;");
1906 case LLDB_REGNUM_GENERIC_FP:
1907 response.PutCString("generic:fp;");
1909 case LLDB_REGNUM_GENERIC_RA:
1910 response.PutCString("generic:ra;");
1912 case LLDB_REGNUM_GENERIC_FLAGS:
1913 response.PutCString("generic:flags;");
1915 case LLDB_REGNUM_GENERIC_ARG1:
1916 response.PutCString("generic:arg1;");
1918 case LLDB_REGNUM_GENERIC_ARG2:
1919 response.PutCString("generic:arg2;");
1921 case LLDB_REGNUM_GENERIC_ARG3:
1922 response.PutCString("generic:arg3;");
1924 case LLDB_REGNUM_GENERIC_ARG4:
1925 response.PutCString("generic:arg4;");
1927 case LLDB_REGNUM_GENERIC_ARG5:
1928 response.PutCString("generic:arg5;");
1930 case LLDB_REGNUM_GENERIC_ARG6:
1931 response.PutCString("generic:arg6;");
1933 case LLDB_REGNUM_GENERIC_ARG7:
1934 response.PutCString("generic:arg7;");
1936 case LLDB_REGNUM_GENERIC_ARG8:
1937 response.PutCString("generic:arg8;");
1943 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1944 response.PutCString("container-regs:");
1946 for (const uint32_t *reg_num = reg_info->value_regs;
1947 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1949 response.PutChar(',');
1950 response.Printf("%" PRIx32, *reg_num);
1952 response.PutChar(';');
1955 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1956 response.PutCString("invalidate-regs:");
1958 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1959 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1961 response.PutChar(',');
1962 response.Printf("%" PRIx32, *reg_num);
1964 response.PutChar(';');
1967 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1968 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1969 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1970 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1971 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1972 response.PutChar(';');
1974 return SendPacketNoLock(response.GetString());
1977 GDBRemoteCommunication::PacketResult
1978 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1979 StringExtractorGDBRemote &packet) {
1980 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1982 // Fail if we don't have a current process.
1983 if (!m_debugged_process_sp ||
1984 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1986 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1989 m_debugged_process_sp ? "invalid process id"
1990 : "null m_debugged_process_sp");
1991 return SendOKResponse();
1994 StreamGDBRemote response;
1995 response.PutChar('m');
1999 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
2002 NativeThreadProtocolSP thread_sp;
2003 uint32_t thread_index;
2004 for (thread_index = 0,
2005 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
2006 thread_sp; ++thread_index,
2007 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
2010 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
2011 "(%s, tid=0x%" PRIx64 ")",
2012 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
2013 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
2014 if (thread_index > 0)
2015 response.PutChar(',');
2016 response.Printf("%" PRIx64, thread_sp->GetID());
2021 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
2024 return SendPacketNoLock(response.GetString());
2027 GDBRemoteCommunication::PacketResult
2028 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2029 StringExtractorGDBRemote &packet) {
2030 // FIXME for now we return the full thread list in the initial packet and
2031 // always do nothing here.
2032 return SendPacketNoLock("l");
2035 GDBRemoteCommunication::PacketResult
2036 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2037 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2039 // Parse out the register number from the request.
2040 packet.SetFilePos(strlen("p"));
2041 const uint32_t reg_index =
2042 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2043 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2045 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2046 "parse register number from request \"%s\"",
2047 __FUNCTION__, packet.GetStringRef().c_str());
2048 return SendErrorResponse(0x15);
2051 // Get the thread to use.
2052 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2056 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2058 return SendErrorResponse(0x15);
2061 // Get the thread's register context.
2062 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2063 if (!reg_context_sp) {
2066 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2067 " failed, no register context available for the thread",
2068 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2069 return SendErrorResponse(0x15);
2072 // Return the end of registers response if we've iterated one past the end of
2073 // the register set.
2074 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2076 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2077 "register %" PRIu32 " beyond register count %" PRIu32,
2078 __FUNCTION__, reg_index,
2079 reg_context_sp->GetUserRegisterCount());
2080 return SendErrorResponse(0x15);
2083 const RegisterInfo *reg_info =
2084 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2087 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2088 "register %" PRIu32 " returned NULL",
2089 __FUNCTION__, reg_index);
2090 return SendErrorResponse(0x15);
2093 // Build the reginfos response.
2094 StreamGDBRemote response;
2096 // Retrieve the value
2097 RegisterValue reg_value;
2098 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
2101 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2102 "requested register %" PRIu32 " (%s) failed: %s",
2103 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2104 return SendErrorResponse(0x15);
2107 const uint8_t *const data =
2108 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2111 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2112 "bytes from requested register %" PRIu32,
2113 __FUNCTION__, reg_index);
2114 return SendErrorResponse(0x15);
2117 // FIXME flip as needed to get data in big/little endian format for this host.
2118 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2119 response.PutHex8(data[i]);
2121 return SendPacketNoLock(response.GetString());
2124 GDBRemoteCommunication::PacketResult
2125 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2126 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2128 // Ensure there is more content.
2129 if (packet.GetBytesLeft() < 1)
2130 return SendIllFormedResponse(packet, "Empty P packet");
2132 // Parse out the register number from the request.
2133 packet.SetFilePos(strlen("P"));
2134 const uint32_t reg_index =
2135 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2136 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2138 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2139 "parse register number from request \"%s\"",
2140 __FUNCTION__, packet.GetStringRef().c_str());
2141 return SendErrorResponse(0x29);
2144 // Note debugserver would send an E30 here.
2145 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2146 return SendIllFormedResponse(
2147 packet, "P packet missing '=' char after register number");
2149 // Get process architecture.
2150 ArchSpec process_arch;
2151 if (!m_debugged_process_sp ||
2152 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2154 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2155 "inferior architecture",
2157 return SendErrorResponse(0x49);
2160 // Parse out the value.
2161 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2162 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2164 // Get the thread to use.
2165 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2168 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2169 "available (thread index 0)",
2171 return SendErrorResponse(0x28);
2174 // Get the thread's register context.
2175 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2176 if (!reg_context_sp) {
2179 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2180 " failed, no register context available for the thread",
2181 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2182 return SendErrorResponse(0x15);
2185 const RegisterInfo *reg_info =
2186 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2189 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2190 "register %" PRIu32 " returned NULL",
2191 __FUNCTION__, reg_index);
2192 return SendErrorResponse(0x48);
2195 // Return the end of registers response if we've iterated one past the end of
2196 // the register set.
2197 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2199 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2200 "register %" PRIu32 " beyond register count %" PRIu32,
2201 __FUNCTION__, reg_index,
2202 reg_context_sp->GetUserRegisterCount());
2203 return SendErrorResponse(0x47);
2206 // The dwarf expression are evaluate on host site
2207 // which may cause register size to change
2208 // Hence the reg_size may not be same as reg_info->bytes_size
2209 if ((reg_size != reg_info->byte_size) &&
2210 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2211 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2214 // Build the reginfos response.
2215 StreamGDBRemote response;
2217 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
2218 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
2221 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2222 "requested register %" PRIu32 " (%s) failed: %s",
2223 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2224 return SendErrorResponse(0x32);
2227 return SendOKResponse();
2230 GDBRemoteCommunication::PacketResult
2231 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2232 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2234 // Fail if we don't have a current process.
2235 if (!m_debugged_process_sp ||
2236 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2239 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2241 return SendErrorResponse(0x15);
2244 // Parse out which variant of $H is requested.
2245 packet.SetFilePos(strlen("H"));
2246 if (packet.GetBytesLeft() < 1) {
2248 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2249 "missing {g,c} variant",
2251 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2254 const char h_variant = packet.GetChar();
2255 switch (h_variant) {
2265 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2266 __FUNCTION__, h_variant);
2267 return SendIllFormedResponse(packet,
2268 "H variant unsupported, should be c or g");
2271 // Parse out the thread number.
2272 // FIXME return a parse success/fail value. All values are valid here.
2273 const lldb::tid_t tid =
2274 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2276 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2278 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2279 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2282 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2285 return SendErrorResponse(0x15);
2289 // Now switch the given thread type.
2290 switch (h_variant) {
2292 SetCurrentThreadID(tid);
2296 SetContinueThreadID(tid);
2300 assert(false && "unsupported $H variant - shouldn't get here");
2301 return SendIllFormedResponse(packet,
2302 "H variant unsupported, should be c or g");
2305 return SendOKResponse();
2308 GDBRemoteCommunication::PacketResult
2309 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2310 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2312 // Fail if we don't have a current process.
2313 if (!m_debugged_process_sp ||
2314 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2317 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2319 return SendErrorResponse(0x15);
2322 packet.SetFilePos(::strlen("I"));
2325 size_t read = packet.GetHexBytesAvail(tmp);
2329 // write directly to stdin *this might block if stdin buffer is full*
2330 // TODO: enqueue this block in circular buffer and send window size to
2332 ConnectionStatus status;
2334 m_stdio_communication.Write(tmp, read, status, &error);
2336 return SendErrorResponse(0x15);
2340 return SendOKResponse();
2343 GDBRemoteCommunication::PacketResult
2344 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2345 StringExtractorGDBRemote &packet) {
2346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2348 // Fail if we don't have a current process.
2349 if (!m_debugged_process_sp ||
2350 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2353 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2355 return SendErrorResponse(0x15);
2358 // Interrupt the process.
2359 Status error = m_debugged_process_sp->Interrupt();
2363 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2365 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
2367 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2371 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2372 __FUNCTION__, m_debugged_process_sp->GetID());
2374 // No response required from stop all.
2375 return PacketResult::Success;
2378 GDBRemoteCommunication::PacketResult
2379 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2380 StringExtractorGDBRemote &packet) {
2381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2383 if (!m_debugged_process_sp ||
2384 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2387 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2389 return SendErrorResponse(0x15);
2392 // Parse out the memory address.
2393 packet.SetFilePos(strlen("m"));
2394 if (packet.GetBytesLeft() < 1)
2395 return SendIllFormedResponse(packet, "Too short m packet");
2397 // Read the address. Punting on validation.
2398 // FIXME replace with Hex U64 read with no default value that fails on failed
2400 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2403 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2404 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2406 // Get # bytes to read.
2407 if (packet.GetBytesLeft() < 1)
2408 return SendIllFormedResponse(packet, "Length missing in m packet");
2410 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2411 if (byte_count == 0) {
2413 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2414 "zero-length packet",
2416 return SendOKResponse();
2419 // Allocate the response buffer.
2420 std::string buf(byte_count, '\0');
2422 return SendErrorResponse(0x78);
2424 // Retrieve the process memory.
2425 size_t bytes_read = 0;
2426 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2427 read_addr, &buf[0], byte_count, bytes_read);
2430 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2431 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2432 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2434 return SendErrorResponse(0x08);
2437 if (bytes_read == 0) {
2439 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2440 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2441 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2443 return SendErrorResponse(0x08);
2446 StreamGDBRemote response;
2447 packet.SetFilePos(0);
2448 char kind = packet.GetChar('?');
2450 response.PutEscapedBytes(buf.data(), byte_count);
2452 assert(kind == 'm');
2453 for (size_t i = 0; i < bytes_read; ++i)
2454 response.PutHex8(buf[i]);
2457 return SendPacketNoLock(response.GetString());
2460 GDBRemoteCommunication::PacketResult
2461 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2462 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2464 if (!m_debugged_process_sp ||
2465 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2468 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2470 return SendErrorResponse(0x15);
2473 // Parse out the memory address.
2474 packet.SetFilePos(strlen("M"));
2475 if (packet.GetBytesLeft() < 1)
2476 return SendIllFormedResponse(packet, "Too short M packet");
2478 // Read the address. Punting on validation.
2479 // FIXME replace with Hex U64 read with no default value that fails on failed
2481 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2484 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2485 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2487 // Get # bytes to read.
2488 if (packet.GetBytesLeft() < 1)
2489 return SendIllFormedResponse(packet, "Length missing in M packet");
2491 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2492 if (byte_count == 0) {
2494 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2495 "zero-length packet",
2497 return PacketResult::Success;
2501 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2502 return SendIllFormedResponse(
2503 packet, "Comma sep missing in M packet after byte length");
2505 // Allocate the conversion buffer.
2506 std::vector<uint8_t> buf(byte_count, 0);
2508 return SendErrorResponse(0x78);
2510 // Convert the hex memory write contents to bytes.
2511 StreamGDBRemote response;
2512 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2513 if (convert_count != byte_count) {
2515 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2516 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2517 " bytes, but only found %" PRIu64 " to convert.",
2518 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2519 byte_count, convert_count);
2520 return SendIllFormedResponse(packet, "M content byte length specified did "
2521 "not match hex-encoded content "
2525 // Write the process memory.
2526 size_t bytes_written = 0;
2527 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2528 byte_count, bytes_written);
2531 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2532 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2533 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2535 return SendErrorResponse(0x09);
2538 if (bytes_written == 0) {
2540 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2541 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2542 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2544 return SendErrorResponse(0x09);
2547 return SendOKResponse();
2550 GDBRemoteCommunication::PacketResult
2551 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2552 StringExtractorGDBRemote &packet) {
2553 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2555 // Currently only the NativeProcessProtocol knows if it can handle a
2556 // qMemoryRegionInfoSupported
2557 // request, but we're not guaranteed to be attached to a process. For now
2559 // client only asks this when a process is being debugged.
2561 // Ensure we have a process running; otherwise, we can't figure this out
2562 // since we won't have a NativeProcessProtocol.
2563 if (!m_debugged_process_sp ||
2564 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2567 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2569 return SendErrorResponse(0x15);
2572 // Test if we can get any region back when asking for the region around NULL.
2573 MemoryRegionInfo region_info;
2574 const Status error =
2575 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2577 // We don't support memory region info collection for this
2578 // NativeProcessProtocol.
2579 return SendUnimplementedResponse("");
2582 return SendOKResponse();
2585 GDBRemoteCommunication::PacketResult
2586 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2587 StringExtractorGDBRemote &packet) {
2588 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2590 // Ensure we have a process.
2591 if (!m_debugged_process_sp ||
2592 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2595 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2597 return SendErrorResponse(0x15);
2600 // Parse out the memory address.
2601 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2602 if (packet.GetBytesLeft() < 1)
2603 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2605 // Read the address. Punting on validation.
2606 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2608 StreamGDBRemote response;
2610 // Get the memory region info for the target address.
2611 MemoryRegionInfo region_info;
2612 const Status error =
2613 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2615 // Return the error message.
2617 response.PutCString("error:");
2618 response.PutCStringAsRawHex8(error.AsCString());
2619 response.PutChar(';');
2621 // Range start and size.
2622 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2623 region_info.GetRange().GetRangeBase(),
2624 region_info.GetRange().GetByteSize());
2627 if (region_info.GetReadable() || region_info.GetWritable() ||
2628 region_info.GetExecutable()) {
2629 // Write permissions info.
2630 response.PutCString("permissions:");
2632 if (region_info.GetReadable())
2633 response.PutChar('r');
2634 if (region_info.GetWritable())
2635 response.PutChar('w');
2636 if (region_info.GetExecutable())
2637 response.PutChar('x');
2639 response.PutChar(';');
2643 ConstString name = region_info.GetName();
2645 response.PutCString("name:");
2646 response.PutCStringAsRawHex8(name.AsCString());
2647 response.PutChar(';');
2651 return SendPacketNoLock(response.GetString());
2654 GDBRemoteCommunication::PacketResult
2655 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2656 // Ensure we have a process.
2657 if (!m_debugged_process_sp ||
2658 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2659 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2662 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2664 return SendErrorResponse(0x15);
2667 // Parse out software or hardware breakpoint or watchpoint requested.
2668 packet.SetFilePos(strlen("Z"));
2669 if (packet.GetBytesLeft() < 1)
2670 return SendIllFormedResponse(
2671 packet, "Too short Z packet, missing software/hardware specifier");
2673 bool want_breakpoint = true;
2674 bool want_hardware = false;
2675 uint32_t watch_flags = 0;
2677 const GDBStoppointType stoppoint_type =
2678 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2679 switch (stoppoint_type) {
2680 case eBreakpointSoftware:
2681 want_hardware = false;
2682 want_breakpoint = true;
2684 case eBreakpointHardware:
2685 want_hardware = true;
2686 want_breakpoint = true;
2688 case eWatchpointWrite:
2690 want_hardware = true;
2691 want_breakpoint = false;
2693 case eWatchpointRead:
2695 want_hardware = true;
2696 want_breakpoint = false;
2698 case eWatchpointReadWrite:
2700 want_hardware = true;
2701 want_breakpoint = false;
2703 case eStoppointInvalid:
2704 return SendIllFormedResponse(
2705 packet, "Z packet had invalid software/hardware specifier");
2708 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2709 return SendIllFormedResponse(
2710 packet, "Malformed Z packet, expecting comma after stoppoint type");
2712 // Parse out the stoppoint address.
2713 if (packet.GetBytesLeft() < 1)
2714 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2715 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2717 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2718 return SendIllFormedResponse(
2719 packet, "Malformed Z packet, expecting comma after address");
2721 // Parse out the stoppoint size (i.e. size hint for opcode size).
2722 const uint32_t size =
2723 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2724 if (size == std::numeric_limits<uint32_t>::max())
2725 return SendIllFormedResponse(
2726 packet, "Malformed Z packet, failed to parse size argument");
2728 if (want_breakpoint) {
2729 // Try to set the breakpoint.
2730 const Status error =
2731 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2732 if (error.Success())
2733 return SendOKResponse();
2734 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2736 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2737 " failed to set breakpoint: %s",
2738 __FUNCTION__, m_debugged_process_sp->GetID(),
2740 return SendErrorResponse(0x09);
2742 // Try to set the watchpoint.
2743 const Status error = m_debugged_process_sp->SetWatchpoint(
2744 addr, size, watch_flags, want_hardware);
2745 if (error.Success())
2746 return SendOKResponse();
2747 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2749 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2750 " failed to set watchpoint: %s",
2751 __FUNCTION__, m_debugged_process_sp->GetID(),
2753 return SendErrorResponse(0x09);
2757 GDBRemoteCommunication::PacketResult
2758 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2759 // Ensure we have a process.
2760 if (!m_debugged_process_sp ||
2761 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2762 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2765 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2767 return SendErrorResponse(0x15);
2770 // Parse out software or hardware breakpoint or watchpoint requested.
2771 packet.SetFilePos(strlen("z"));
2772 if (packet.GetBytesLeft() < 1)
2773 return SendIllFormedResponse(
2774 packet, "Too short z packet, missing software/hardware specifier");
2776 bool want_breakpoint = true;
2777 bool want_hardware = false;
2779 const GDBStoppointType stoppoint_type =
2780 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2781 switch (stoppoint_type) {
2782 case eBreakpointHardware:
2783 want_breakpoint = true;
2784 want_hardware = true;
2786 case eBreakpointSoftware:
2787 want_breakpoint = true;
2789 case eWatchpointWrite:
2790 want_breakpoint = false;
2792 case eWatchpointRead:
2793 want_breakpoint = false;
2795 case eWatchpointReadWrite:
2796 want_breakpoint = false;
2799 return SendIllFormedResponse(
2800 packet, "z packet had invalid software/hardware specifier");
2803 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2804 return SendIllFormedResponse(
2805 packet, "Malformed z packet, expecting comma after stoppoint type");
2807 // Parse out the stoppoint address.
2808 if (packet.GetBytesLeft() < 1)
2809 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2810 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2812 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2813 return SendIllFormedResponse(
2814 packet, "Malformed z packet, expecting comma after address");
2817 // Parse out the stoppoint size (i.e. size hint for opcode size).
2818 const uint32_t size = packet.GetHexMaxU32 (false,
2819 std::numeric_limits<uint32_t>::max ());
2820 if (size == std::numeric_limits<uint32_t>::max ())
2821 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2825 if (want_breakpoint) {
2826 // Try to clear the breakpoint.
2827 const Status error =
2828 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
2829 if (error.Success())
2830 return SendOKResponse();
2831 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2833 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2834 " failed to remove breakpoint: %s",
2835 __FUNCTION__, m_debugged_process_sp->GetID(),
2837 return SendErrorResponse(0x09);
2839 // Try to clear the watchpoint.
2840 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
2841 if (error.Success())
2842 return SendOKResponse();
2843 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2845 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2846 " failed to remove watchpoint: %s",
2847 __FUNCTION__, m_debugged_process_sp->GetID(),
2849 return SendErrorResponse(0x09);
2853 GDBRemoteCommunication::PacketResult
2854 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2855 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2857 // Ensure we have a process.
2858 if (!m_debugged_process_sp ||
2859 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2862 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2864 return SendErrorResponse(0x32);
2867 // We first try to use a continue thread id. If any one or any all set, use
2868 // the current thread.
2869 // Bail out if we don't have a thread id.
2870 lldb::tid_t tid = GetContinueThreadID();
2871 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2872 tid = GetCurrentThreadID();
2873 if (tid == LLDB_INVALID_THREAD_ID)
2874 return SendErrorResponse(0x33);
2876 // Double check that we have such a thread.
2877 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2878 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2879 if (!thread_sp || thread_sp->GetID() != tid)
2880 return SendErrorResponse(0x33);
2882 // Create the step action for the given thread.
2883 ResumeAction action = {tid, eStateStepping, 0};
2885 // Setup the actions list.
2886 ResumeActionList actions;
2887 actions.Append(action);
2889 // All other threads stop while we're single stepping a thread.
2890 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2891 Status error = m_debugged_process_sp->Resume(actions);
2894 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2895 " tid %" PRIu64 " Resume() failed with error: %s",
2896 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2898 return SendErrorResponse(0x49);
2901 // No response here - the stop or exit will come from the resulting action.
2902 return PacketResult::Success;
2905 GDBRemoteCommunication::PacketResult
2906 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2907 StringExtractorGDBRemote &packet) {
2908 // *BSD impls should be able to do this too.
2909 #if defined(__linux__) || defined(__NetBSD__)
2910 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2912 // Parse out the offset.
2913 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2914 if (packet.GetBytesLeft() < 1)
2915 return SendIllFormedResponse(packet,
2916 "qXfer:auxv:read:: packet missing offset");
2918 const uint64_t auxv_offset =
2919 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2920 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2921 return SendIllFormedResponse(packet,
2922 "qXfer:auxv:read:: packet missing offset");
2925 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2926 return SendIllFormedResponse(
2927 packet, "qXfer:auxv:read:: packet missing comma after offset");
2929 // Parse out the length.
2930 const uint64_t auxv_length =
2931 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2932 if (auxv_length == std::numeric_limits<uint64_t>::max())
2933 return SendIllFormedResponse(packet,
2934 "qXfer:auxv:read:: packet missing length");
2936 // Grab the auxv data if we need it.
2937 if (!m_active_auxv_buffer_up) {
2938 // Make sure we have a valid process.
2939 if (!m_debugged_process_sp ||
2940 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2943 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2945 return SendErrorResponse(0x10);
2948 // Grab the auxv data.
2949 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2950 if (!buffer_or_error) {
2951 std::error_code ec = buffer_or_error.getError();
2952 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2953 return SendErrorResponse(ec.value());
2955 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2958 StreamGDBRemote response;
2959 bool done_with_buffer = false;
2961 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2962 if (auxv_offset >= buffer.size()) {
2963 // We have nothing left to send. Mark the buffer as complete.
2964 response.PutChar('l');
2965 done_with_buffer = true;
2967 // Figure out how many bytes are available starting at the given offset.
2968 buffer = buffer.drop_front(auxv_offset);
2970 // Mark the response type according to whether we're reading the remainder
2971 // of the auxv data.
2972 if (auxv_length >= buffer.size()) {
2973 // There will be nothing left to read after this
2974 response.PutChar('l');
2975 done_with_buffer = true;
2977 // There will still be bytes to read after this request.
2978 response.PutChar('m');
2979 buffer = buffer.take_front(auxv_length);
2982 // Now write the data in encoded binary form.
2983 response.PutEscapedBytes(buffer.data(), buffer.size());
2986 if (done_with_buffer)
2987 m_active_auxv_buffer_up.reset();
2989 return SendPacketNoLock(response.GetString());
2991 return SendUnimplementedResponse("not implemented on this platform");
2995 GDBRemoteCommunication::PacketResult
2996 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2997 StringExtractorGDBRemote &packet) {
2998 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3000 // Move past packet name.
3001 packet.SetFilePos(strlen("QSaveRegisterState"));
3003 // Get the thread to use.
3004 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3006 if (m_thread_suffix_supported)
3007 return SendIllFormedResponse(
3008 packet, "No thread specified in QSaveRegisterState packet");
3010 return SendIllFormedResponse(packet,
3011 "No thread was is set with the Hg packet");
3014 // Grab the register context for the thread.
3015 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3016 if (!reg_context_sp) {
3019 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3020 " failed, no register context available for the thread",
3021 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3022 return SendErrorResponse(0x15);
3025 // Save registers to a buffer.
3026 DataBufferSP register_data_sp;
3027 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
3030 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3031 " failed to save all register values: %s",
3032 __FUNCTION__, m_debugged_process_sp->GetID(),
3034 return SendErrorResponse(0x75);
3037 // Allocate a new save id.
3038 const uint32_t save_id = GetNextSavedRegistersID();
3039 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3040 "GetNextRegisterSaveID() returned an existing register save id");
3042 // Save the register data buffer under the save id.
3044 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3045 m_saved_registers_map[save_id] = register_data_sp;
3048 // Write the response.
3049 StreamGDBRemote response;
3050 response.Printf("%" PRIu32, save_id);
3051 return SendPacketNoLock(response.GetString());
3054 GDBRemoteCommunication::PacketResult
3055 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3056 StringExtractorGDBRemote &packet) {
3057 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3059 // Parse out save id.
3060 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3061 if (packet.GetBytesLeft() < 1)
3062 return SendIllFormedResponse(
3063 packet, "QRestoreRegisterState packet missing register save id");
3065 const uint32_t save_id = packet.GetU32(0);
3068 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3069 "packet has malformed save id, expecting decimal uint32_t",
3071 return SendErrorResponse(0x76);
3074 // Get the thread to use.
3075 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3077 if (m_thread_suffix_supported)
3078 return SendIllFormedResponse(
3079 packet, "No thread specified in QRestoreRegisterState packet");
3081 return SendIllFormedResponse(packet,
3082 "No thread was is set with the Hg packet");
3085 // Grab the register context for the thread.
3086 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3087 if (!reg_context_sp) {
3090 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3091 " failed, no register context available for the thread",
3092 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3093 return SendErrorResponse(0x15);
3096 // Retrieve register state buffer, then remove from the list.
3097 DataBufferSP register_data_sp;
3099 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3101 // Find the register set buffer for the given save id.
3102 auto it = m_saved_registers_map.find(save_id);
3103 if (it == m_saved_registers_map.end()) {
3105 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3106 " does not have a register set save buffer for id %" PRIu32,
3107 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3108 return SendErrorResponse(0x77);
3110 register_data_sp = it->second;
3112 // Remove it from the map.
3113 m_saved_registers_map.erase(it);
3116 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
3119 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3120 " failed to restore all register values: %s",
3121 __FUNCTION__, m_debugged_process_sp->GetID(),
3123 return SendErrorResponse(0x77);
3126 return SendOKResponse();
3129 GDBRemoteCommunication::PacketResult
3130 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3131 StringExtractorGDBRemote &packet) {
3132 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3134 // Consume the ';' after vAttach.
3135 packet.SetFilePos(strlen("vAttach"));
3136 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3137 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3139 // Grab the PID to which we will attach (assume hex encoding).
3140 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3141 if (pid == LLDB_INVALID_PROCESS_ID)
3142 return SendIllFormedResponse(packet,
3143 "vAttach failed to parse the process id");
3145 // Attempt to attach.
3147 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3151 Status error = AttachToProcess(pid);
3155 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3156 "pid %" PRIu64 ": %s\n",
3157 __FUNCTION__, pid, error.AsCString());
3158 return SendErrorResponse(0x01);
3161 // Notify we attached by sending a stop packet.
3162 return SendStopReasonForState(m_debugged_process_sp->GetState());
3165 GDBRemoteCommunication::PacketResult
3166 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3167 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3169 StopSTDIOForwarding();
3171 // Fail if we don't have a current process.
3172 if (!m_debugged_process_sp ||
3173 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3176 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3178 return SendErrorResponse(0x15);
3181 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3183 // Consume the ';' after D.
3184 packet.SetFilePos(1);
3185 if (packet.GetBytesLeft()) {
3186 if (packet.GetChar() != ';')
3187 return SendIllFormedResponse(packet, "D missing expected ';'");
3189 // Grab the PID from which we will detach (assume hex encoding).
3190 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3191 if (pid == LLDB_INVALID_PROCESS_ID)
3192 return SendIllFormedResponse(packet, "D failed to parse the process id");
3195 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3196 return SendIllFormedResponse(packet, "Invalid pid");
3199 const Status error = m_debugged_process_sp->Detach();
3202 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3203 "pid %" PRIu64 ": %s\n",
3204 __FUNCTION__, m_debugged_process_sp->GetID(),
3206 return SendErrorResponse(0x01);
3209 return SendOKResponse();
3212 GDBRemoteCommunication::PacketResult
3213 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3214 StringExtractorGDBRemote &packet) {
3215 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3217 packet.SetFilePos(strlen("qThreadStopInfo"));
3218 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3219 if (tid == LLDB_INVALID_THREAD_ID) {
3221 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3222 "parse thread id from request \"%s\"",
3223 __FUNCTION__, packet.GetStringRef().c_str());
3224 return SendErrorResponse(0x15);
3226 return SendStopReplyPacketForThread(tid);
3229 GDBRemoteCommunication::PacketResult
3230 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3231 StringExtractorGDBRemote &) {
3232 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3234 // Ensure we have a debugged process.
3235 if (!m_debugged_process_sp ||
3236 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3237 return SendErrorResponse(50);
3240 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3242 __FUNCTION__, m_debugged_process_sp->GetID());
3244 StreamString response;
3245 const bool threads_with_valid_stop_info_only = false;
3246 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3247 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3248 if (!threads_array_sp) {
3250 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3251 "packet for pid %" PRIu64,
3252 __FUNCTION__, m_debugged_process_sp->GetID());
3253 return SendErrorResponse(52);
3256 threads_array_sp->Write(response);
3257 StreamGDBRemote escaped_response;
3258 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3259 return SendPacketNoLock(escaped_response.GetString());
3262 GDBRemoteCommunication::PacketResult
3263 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3264 StringExtractorGDBRemote &packet) {
3265 // Fail if we don't have a current process.
3266 if (!m_debugged_process_sp ||
3267 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3268 return SendErrorResponse(68);
3270 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3271 if (packet.GetBytesLeft() == 0)
3272 return SendOKResponse();
3273 if (packet.GetChar() != ':')
3274 return SendErrorResponse(67);
3276 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3278 StreamGDBRemote response;
3279 if (hw_debug_cap == llvm::None)
3280 response.Printf("num:0;");
3282 response.Printf("num:%d;", hw_debug_cap->second);
3284 return SendPacketNoLock(response.GetString());
3287 GDBRemoteCommunication::PacketResult
3288 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3289 StringExtractorGDBRemote &packet) {
3290 // Fail if we don't have a current process.
3291 if (!m_debugged_process_sp ||
3292 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3293 return SendErrorResponse(67);
3295 packet.SetFilePos(strlen("qFileLoadAddress:"));
3296 if (packet.GetBytesLeft() == 0)
3297 return SendErrorResponse(68);
3299 std::string file_name;
3300 packet.GetHexByteString(file_name);
3302 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3304 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3306 return SendErrorResponse(69);
3308 if (file_load_address == LLDB_INVALID_ADDRESS)
3309 return SendErrorResponse(1); // File not loaded
3311 StreamGDBRemote response;
3312 response.PutHex64(file_load_address);
3313 return SendPacketNoLock(response.GetString());
3316 GDBRemoteCommunication::PacketResult
3317 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3318 StringExtractorGDBRemote &packet) {
3319 std::vector<int> signals;
3320 packet.SetFilePos(strlen("QPassSignals:"));
3322 // Read sequence of hex signal numbers divided by a semicolon and
3323 // optionally spaces.
3324 while (packet.GetBytesLeft() > 0) {
3325 int signal = packet.GetS32(-1, 16);
3327 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3328 signals.push_back(signal);
3330 packet.SkipSpaces();
3331 char separator = packet.GetChar();
3332 if (separator == '\0')
3333 break; // End of string
3334 if (separator != ';')
3335 return SendIllFormedResponse(packet, "Invalid separator,"
3336 " expected semicolon.");
3339 // Fail if we don't have a current process.
3340 if (!m_debugged_process_sp)
3341 return SendErrorResponse(68);
3343 Status error = m_debugged_process_sp->IgnoreSignals(signals);
3345 return SendErrorResponse(69);
3347 return SendOKResponse();
3350 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3353 // Tell the stdio connection to shut down.
3354 if (m_stdio_communication.IsConnected()) {
3355 auto connection = m_stdio_communication.GetConnection();
3358 connection->Disconnect(&error);
3360 if (error.Success()) {
3362 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3363 "terminal stdio - SUCCESS",
3367 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3368 "terminal stdio - FAIL: %s",
3369 __FUNCTION__, error.AsCString());
3375 NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3376 StringExtractorGDBRemote &packet) {
3377 NativeThreadProtocolSP thread_sp;
3379 // We have no thread if we don't have a process.
3380 if (!m_debugged_process_sp ||
3381 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3384 // If the client hasn't asked for thread suffix support, there will not be a
3386 // Use the current thread in that case.
3387 if (!m_thread_suffix_supported) {
3388 const lldb::tid_t current_tid = GetCurrentThreadID();
3389 if (current_tid == LLDB_INVALID_THREAD_ID)
3391 else if (current_tid == 0) {
3393 return m_debugged_process_sp->GetThreadAtIndex(0);
3395 return m_debugged_process_sp->GetThreadByID(current_tid);
3398 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3400 // Parse out the ';'.
3401 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3403 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3404 "error: expected ';' prior to start of thread suffix: packet "
3406 __FUNCTION__, packet.GetStringRef().c_str());
3410 if (!packet.GetBytesLeft())
3413 // Parse out thread: portion.
3414 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3416 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3417 "error: expected 'thread:' but not found, packet contents = "
3419 __FUNCTION__, packet.GetStringRef().c_str());
3422 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3423 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3425 return m_debugged_process_sp->GetThreadByID(tid);
3430 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3431 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3432 // Use whatever the debug process says is the current thread id
3433 // since the protocol either didn't specify or specified we want
3434 // any/all threads marked as the current thread.
3435 if (!m_debugged_process_sp)
3436 return LLDB_INVALID_THREAD_ID;
3437 return m_debugged_process_sp->GetCurrentThreadID();
3439 // Use the specific current thread id set by the gdb remote protocol.
3440 return m_current_tid;
3443 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3444 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3445 return m_next_saved_registers_id++;
3448 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3449 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3451 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3452 m_active_auxv_buffer_up.reset();
3456 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3457 const ArchSpec &arch) {
3458 if (m_debugged_process_sp) {
3460 if (m_debugged_process_sp
3461 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3463 if (file_spec.Exists())
3468 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);