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"
21 #include "lldb/Host/ConnectionFileDescriptor.h"
22 #include "lldb/Host/Debug.h"
23 #include "lldb/Host/File.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/PosixApi.h"
28 #include "lldb/Host/common/NativeProcessProtocol.h"
29 #include "lldb/Host/common/NativeRegisterContext.h"
30 #include "lldb/Host/common/NativeThreadProtocol.h"
31 #include "lldb/Target/FileAction.h"
32 #include "lldb/Target/MemoryRegionInfo.h"
33 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/DataBuffer.h"
35 #include "lldb/Utility/Endian.h"
36 #include "lldb/Utility/JSON.h"
37 #include "lldb/Utility/LLDBAssert.h"
38 #include "lldb/Utility/Log.h"
39 #include "lldb/Utility/RegisterValue.h"
40 #include "lldb/Utility/State.h"
41 #include "lldb/Utility/StreamString.h"
42 #include "lldb/Utility/UriParser.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Support/ScopedPrinter.h"
46 #include "ProcessGDBRemote.h"
47 #include "ProcessGDBRemoteLog.h"
48 #include "lldb/Utility/StringExtractorGDBRemote.h"
51 using namespace lldb_private;
52 using namespace lldb_private::process_gdb_remote;
55 //----------------------------------------------------------------------
57 //----------------------------------------------------------------------
60 enum GDBRemoteServerError {
61 // Set to the first unused error number in literal form below
63 eErrorNoProcess = eErrorFirst,
69 //----------------------------------------------------------------------
70 // GDBRemoteCommunicationServerLLGS constructor
71 //----------------------------------------------------------------------
72 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
73 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
74 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
75 "gdb-remote.server.rx_packet"),
76 m_mainloop(mainloop), m_process_factory(process_factory),
77 m_stdio_communication("process.stdio") {
78 RegisterPacketHandlers();
81 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
83 &GDBRemoteCommunicationServerLLGS::Handle_C);
84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
85 &GDBRemoteCommunicationServerLLGS::Handle_c);
86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
87 &GDBRemoteCommunicationServerLLGS::Handle_D);
88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
89 &GDBRemoteCommunicationServerLLGS::Handle_H);
90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
91 &GDBRemoteCommunicationServerLLGS::Handle_I);
92 RegisterMemberFunctionHandler(
93 StringExtractorGDBRemote::eServerPacketType_interrupt,
94 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
95 RegisterMemberFunctionHandler(
96 StringExtractorGDBRemote::eServerPacketType_m,
97 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
99 &GDBRemoteCommunicationServerLLGS::Handle_M);
100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
101 &GDBRemoteCommunicationServerLLGS::Handle_p);
102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
103 &GDBRemoteCommunicationServerLLGS::Handle_P);
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
105 &GDBRemoteCommunicationServerLLGS::Handle_qC);
106 RegisterMemberFunctionHandler(
107 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
108 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
109 RegisterMemberFunctionHandler(
110 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
111 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
112 RegisterMemberFunctionHandler(
113 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
114 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
117 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
120 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
123 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
129 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
132 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
135 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
138 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
141 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
144 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
147 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
153 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
154 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
155 &GDBRemoteCommunicationServerLLGS::Handle_s);
156 RegisterMemberFunctionHandler(
157 StringExtractorGDBRemote::eServerPacketType_stop_reason,
158 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
159 RegisterMemberFunctionHandler(
160 StringExtractorGDBRemote::eServerPacketType_vAttach,
161 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
162 RegisterMemberFunctionHandler(
163 StringExtractorGDBRemote::eServerPacketType_vCont,
164 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
167 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_x,
170 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
171 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
172 &GDBRemoteCommunicationServerLLGS::Handle_Z);
173 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
174 &GDBRemoteCommunicationServerLLGS::Handle_z);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
177 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
179 RegisterMemberFunctionHandler(
180 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
181 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
184 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
185 RegisterMemberFunctionHandler(
186 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
187 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
188 RegisterMemberFunctionHandler(
189 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
190 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
191 RegisterMemberFunctionHandler(
192 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
193 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
195 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
196 [this](StringExtractorGDBRemote packet, Status &error,
197 bool &interrupt, bool &quit) {
199 return this->Handle_k(packet);
203 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
204 m_process_launch_info = info;
207 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
208 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
210 if (!m_process_launch_info.GetArguments().GetArgumentCount())
211 return Status("%s: no process command line specified to launch",
214 const bool should_forward_stdio =
215 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
216 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
217 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
218 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
219 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
221 if (should_forward_stdio) {
222 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
223 return Status(std::move(Err));
227 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
228 assert(!m_debugged_process_up && "lldb-server creating debugged "
229 "process but one already exists");
231 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
233 return Status(process_or.takeError());
234 m_debugged_process_up = std::move(*process_or);
237 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
238 // needed. llgs local-process debugging may specify PTY paths, which will
239 // make these file actions non-null process launch -i/e/o will also make
240 // these file actions non-null nullptr means that the traffic is expected to
241 // flow over gdb-remote protocol
242 if (should_forward_stdio) {
243 // nullptr means it's not redirected to file or pty (in case of LLGS local)
244 // at least one of stdio will be transferred pty<->gdb-remote we need to
245 // give the pty master handle to this object to read and/or write
247 "pid = {0}: setting up stdout/stderr redirection via $O "
248 "gdb-remote commands",
249 m_debugged_process_up->GetID());
251 // Setup stdout/stderr mapping from inferior to $O
252 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
253 if (terminal_fd >= 0) {
255 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
256 "inferior STDIO fd to %d",
257 __FUNCTION__, terminal_fd);
258 Status status = SetSTDIOFileDescriptor(terminal_fd);
263 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
264 "inferior STDIO since terminal fd reported as %d",
265 __FUNCTION__, terminal_fd);
269 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
270 "will communicate over client-provided file descriptors",
271 m_debugged_process_up->GetID());
274 printf("Launched '%s' as process %" PRIu64 "...\n",
275 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
276 m_debugged_process_up->GetID());
281 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
282 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
284 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
287 // Before we try to attach, make sure we aren't already monitoring something
289 if (m_debugged_process_up &&
290 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
291 return Status("cannot attach to process %" PRIu64
292 " when another process with pid %" PRIu64
293 " is being debugged.",
294 pid, m_debugged_process_up->GetID());
297 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
299 Status status(process_or.takeError());
300 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
304 m_debugged_process_up = std::move(*process_or);
306 // Setup stdout/stderr mapping from inferior.
307 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
308 if (terminal_fd >= 0) {
310 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
311 "inferior STDIO fd to %d",
312 __FUNCTION__, terminal_fd);
313 Status status = SetSTDIOFileDescriptor(terminal_fd);
318 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
319 "inferior STDIO since terminal fd reported as %d",
320 __FUNCTION__, terminal_fd);
323 printf("Attached to process %" PRIu64 "...\n", pid);
327 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
328 NativeProcessProtocol *process) {
329 assert(process && "process cannot be NULL");
330 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
332 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
333 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
334 __FUNCTION__, process->GetID(),
335 StateAsCString(process->GetState()));
339 GDBRemoteCommunication::PacketResult
340 GDBRemoteCommunicationServerLLGS::SendWResponse(
341 NativeProcessProtocol *process) {
342 assert(process && "process cannot be NULL");
343 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
345 // send W notification
346 auto wait_status = process->GetExitStatus();
348 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
351 StreamGDBRemote response;
352 response.PutChar('E');
353 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
354 return SendPacketNoLock(response.GetString());
357 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
360 StreamGDBRemote response;
361 response.Format("{0:g}", *wait_status);
362 return SendPacketNoLock(response.GetString());
365 static void AppendHexValue(StreamString &response, const uint8_t *buf,
366 uint32_t buf_size, bool swap) {
369 for (i = buf_size - 1; i >= 0; i--)
370 response.PutHex8(buf[i]);
372 for (i = 0; i < buf_size; i++)
373 response.PutHex8(buf[i]);
377 static void WriteRegisterValueInHexFixedWidth(
378 StreamString &response, NativeRegisterContext ®_ctx,
379 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
380 lldb::ByteOrder byte_order) {
381 RegisterValue reg_value;
383 Status error = reg_ctx.ReadRegister(®_info, reg_value);
385 reg_value_p = ®_value;
390 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
391 reg_value_p->GetByteSize(),
392 byte_order == lldb::eByteOrderLittle);
394 // Zero-out any unreadable values.
395 if (reg_info.byte_size > 0) {
396 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
397 AppendHexValue(response, zeros.data(), zeros.size(), false);
402 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
403 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
405 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
407 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
409 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
410 // Expedite all registers in the first register set (i.e. should be GPRs)
411 // that are not contained in other registers.
412 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
415 for (const uint32_t *reg_num_p = reg_set_p->registers;
416 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
417 uint32_t reg_num = *reg_num_p;
419 // Expedite only a couple of registers until we figure out why sending
420 // registers is expensive.
421 static const uint32_t k_expedited_registers[] = {
422 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
423 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
425 for (const uint32_t *generic_reg_p = k_expedited_registers;
426 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
427 uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
428 eRegisterKindGeneric, *generic_reg_p);
429 if (reg_num == LLDB_INVALID_REGNUM)
430 continue; // Target does not support the given register.
433 const RegisterInfo *const reg_info_p =
434 reg_ctx.GetRegisterInfoAtIndex(reg_num);
435 if (reg_info_p == nullptr) {
438 "%s failed to get register info for register index %" PRIu32,
439 __FUNCTION__, reg_num);
443 if (reg_info_p->value_regs != nullptr)
444 continue; // Only expedite registers that are not contained in other
447 RegisterValue reg_value;
448 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
451 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
453 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
454 reg_num, error.AsCString());
459 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
460 ®_value, lldb::eByteOrderBig);
462 register_object_sp->SetObject(
463 llvm::to_string(reg_num),
464 std::make_shared<JSONString>(stream.GetString()));
467 return register_object_sp;
470 static const char *GetStopReasonString(StopReason stop_reason) {
471 switch (stop_reason) {
472 case eStopReasonTrace:
474 case eStopReasonBreakpoint:
476 case eStopReasonWatchpoint:
478 case eStopReasonSignal:
480 case eStopReasonException:
482 case eStopReasonExec:
484 case eStopReasonInstrumentation:
485 case eStopReasonInvalid:
486 case eStopReasonPlanComplete:
487 case eStopReasonThreadExiting:
488 case eStopReasonNone:
494 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
496 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
498 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
500 // Ensure we can get info on the given thread.
501 uint32_t thread_idx = 0;
502 for (NativeThreadProtocol *thread;
503 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
506 lldb::tid_t tid = thread->GetID();
508 // Grab the reason this thread stopped.
509 struct ThreadStopInfo tid_stop_info;
510 std::string description;
511 if (!thread->GetStopReason(tid_stop_info, description))
514 const int signum = tid_stop_info.details.signal.signo;
516 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
518 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
519 __FUNCTION__, process.GetID(), tid, signum,
520 tid_stop_info.reason, tid_stop_info.details.exception.type);
523 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
524 threads_array_sp->AppendObject(thread_obj_sp);
527 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread))
528 thread_obj_sp->SetObject("registers", registers_sp);
531 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
533 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
535 const std::string thread_name = thread->GetName();
536 if (!thread_name.empty())
537 thread_obj_sp->SetObject("name",
538 std::make_shared<JSONString>(thread_name));
540 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
541 thread_obj_sp->SetObject("reason",
542 std::make_shared<JSONString>(stop_reason_str));
544 if (!description.empty())
545 thread_obj_sp->SetObject("description",
546 std::make_shared<JSONString>(description));
548 if ((tid_stop_info.reason == eStopReasonException) &&
549 tid_stop_info.details.exception.type) {
550 thread_obj_sp->SetObject(
552 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
554 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
555 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
557 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
558 tid_stop_info.details.exception.data[i]));
560 thread_obj_sp->SetObject("medata", medata_array_sp);
563 // TODO: Expedite interesting regions of inferior memory
566 return threads_array_sp;
569 GDBRemoteCommunication::PacketResult
570 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
572 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
574 // Ensure we have a debugged process.
575 if (!m_debugged_process_up ||
576 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
577 return SendErrorResponse(50);
579 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
580 m_debugged_process_up->GetID(), tid);
582 // Ensure we can get info on the given thread.
583 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
585 return SendErrorResponse(51);
587 // Grab the reason this thread stopped.
588 struct ThreadStopInfo tid_stop_info;
589 std::string description;
590 if (!thread->GetStopReason(tid_stop_info, description))
591 return SendErrorResponse(52);
593 // FIXME implement register handling for exec'd inferiors.
594 // if (tid_stop_info.reason == eStopReasonExec) {
595 // const bool force = true;
596 // InitializeRegisters(force);
599 StreamString response;
600 // Output the T packet with the thread
601 response.PutChar('T');
602 int signum = tid_stop_info.details.signal.signo;
605 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
606 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
607 tid_stop_info.details.exception.type);
609 // Print the signal number.
610 response.PutHex8(signum & 0xff);
613 response.Printf("thread:%" PRIx64 ";", tid);
615 // Include the thread name if there is one.
616 const std::string thread_name = thread->GetName();
617 if (!thread_name.empty()) {
618 size_t thread_name_len = thread_name.length();
620 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
621 response.PutCString("name:");
622 response.PutCString(thread_name);
624 // The thread name contains special chars, send as hex bytes.
625 response.PutCString("hexname:");
626 response.PutCStringAsRawHex8(thread_name.c_str());
628 response.PutChar(';');
631 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
632 // send all thread IDs back in the "threads" key whose value is a list of hex
633 // thread IDs separated by commas:
634 // "threads:10a,10b,10c;"
635 // This will save the debugger from having to send a pair of qfThreadInfo and
636 // qsThreadInfo packets, but it also might take a lot of room in the stop
637 // reply packet, so it must be enabled only on systems where there are no
638 // limits on packet lengths.
639 if (m_list_threads_in_stop_reply) {
640 response.PutCString("threads:");
642 uint32_t thread_index = 0;
643 NativeThreadProtocol *listed_thread;
644 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
645 listed_thread; ++thread_index,
646 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
647 if (thread_index > 0)
648 response.PutChar(',');
649 response.Printf("%" PRIx64, listed_thread->GetID());
651 response.PutChar(';');
653 // Include JSON info that describes the stop reason for any threads that
654 // actually have stop reasons. We use the new "jstopinfo" key whose values
655 // is hex ascii JSON that contains the thread IDs thread stop info only for
656 // threads that have stop reasons. Only send this if we have more than one
657 // thread otherwise this packet has all the info it needs.
658 if (thread_index > 0) {
659 const bool threads_with_valid_stop_info_only = true;
660 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
661 *m_debugged_process_up, threads_with_valid_stop_info_only);
662 if (threads_info_sp) {
663 response.PutCString("jstopinfo:");
664 StreamString unescaped_response;
665 threads_info_sp->Write(unescaped_response);
666 response.PutCStringAsRawHex8(unescaped_response.GetData());
667 response.PutChar(';');
669 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
670 m_debugged_process_up->GetID());
674 response.PutCString("thread-pcs");
675 char delimiter = ':';
676 for (NativeThreadProtocol *thread;
677 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
679 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
681 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
682 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
683 const RegisterInfo *const reg_info_p =
684 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
686 RegisterValue reg_value;
687 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
690 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
692 reg_info_p->name ? reg_info_p->name
693 : "<unnamed-register>",
694 reg_to_read, error.AsCString());
698 response.PutChar(delimiter);
700 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
701 ®_value, endian::InlHostByteOrder());
704 response.PutChar(';');
708 // Expedite registers.
711 // Grab the register context.
712 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
713 // Expedite all registers in the first register set (i.e. should be GPRs)
714 // that are not contained in other registers.
715 const RegisterSet *reg_set_p;
716 if (reg_ctx.GetRegisterSetCount() > 0 &&
717 ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
719 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
720 "from set '%s' (registers set count: %zu)",
722 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
723 reg_set_p->num_registers);
725 for (const uint32_t *reg_num_p = reg_set_p->registers;
726 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
727 const RegisterInfo *const reg_info_p =
728 reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
729 if (reg_info_p == nullptr) {
731 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
732 "register info for register set '%s', register index "
735 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
737 } else if (reg_info_p->value_regs == nullptr) {
738 // Only expediate registers that are not contained in other registers.
739 RegisterValue reg_value;
740 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
741 if (error.Success()) {
742 response.Printf("%.02x:", *reg_num_p);
743 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
744 ®_value, lldb::eByteOrderBig);
745 response.PutChar(';');
748 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
749 "register '%s' index %" PRIu32 ": %s",
751 reg_info_p->name ? reg_info_p->name
752 : "<unnamed-register>",
753 *reg_num_p, error.AsCString());
759 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
760 if (reason_str != nullptr) {
761 response.Printf("reason:%s;", reason_str);
764 if (!description.empty()) {
765 // Description may contains special chars, send as hex bytes.
766 response.PutCString("description:");
767 response.PutCStringAsRawHex8(description.c_str());
768 response.PutChar(';');
769 } else if ((tid_stop_info.reason == eStopReasonException) &&
770 tid_stop_info.details.exception.type) {
771 response.PutCString("metype:");
772 response.PutHex64(tid_stop_info.details.exception.type);
773 response.PutCString(";mecount:");
774 response.PutHex32(tid_stop_info.details.exception.data_count);
775 response.PutChar(';');
777 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
778 response.PutCString("medata:");
779 response.PutHex64(tid_stop_info.details.exception.data[i]);
780 response.PutChar(';');
784 return SendPacketNoLock(response.GetString());
787 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
788 NativeProcessProtocol *process) {
789 assert(process && "process cannot be NULL");
791 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
793 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
795 PacketResult result = SendStopReasonForState(StateType::eStateExited);
796 if (result != PacketResult::Success) {
798 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
799 "notification for PID %" PRIu64 ", state: eStateExited",
800 __FUNCTION__, process->GetID());
803 // Close the pipe to the inferior terminal i/o if we launched it and set one
805 MaybeCloseInferiorTerminalConnection();
807 // We are ready to exit the debug monitor.
809 m_mainloop.RequestTermination();
812 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
813 NativeProcessProtocol *process) {
814 assert(process && "process cannot be NULL");
816 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
818 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
820 // Send the stop reason unless this is the stop after the launch or attach.
821 switch (m_inferior_prev_state) {
822 case eStateLaunching:
823 case eStateAttaching:
824 // Don't send anything per debugserver behavior.
827 // In all other cases, send the stop reason.
828 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
829 if (result != PacketResult::Success) {
831 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
832 "notification for PID %" PRIu64 ", state: eStateExited",
833 __FUNCTION__, process->GetID());
839 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
840 NativeProcessProtocol *process, lldb::StateType state) {
841 assert(process && "process cannot be NULL");
842 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
844 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
845 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
846 __FUNCTION__, process->GetID(), StateAsCString(state));
850 case StateType::eStateRunning:
851 StartSTDIOForwarding();
854 case StateType::eStateStopped:
855 // Make sure we get all of the pending stdout/stderr from the inferior and
856 // send it to the lldb host before we send the state change notification
858 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
859 // does not interfere with our protocol.
860 StopSTDIOForwarding();
861 HandleInferiorState_Stopped(process);
864 case StateType::eStateExited:
867 StopSTDIOForwarding();
868 HandleInferiorState_Exited(process);
873 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
874 "change for pid %" PRIu64 ", new state: %s",
875 __FUNCTION__, process->GetID(), StateAsCString(state));
880 // Remember the previous state reported to us.
881 m_inferior_prev_state = state;
884 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
885 ClearProcessSpecificData();
888 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
889 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
891 if (!m_handshake_completed) {
892 if (!HandshakeWithClient()) {
894 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
895 "client failed, exiting",
897 m_mainloop.RequestTermination();
900 m_handshake_completed = true;
903 bool interrupt = false;
907 const PacketResult result = GetPacketAndSendResponse(
908 std::chrono::microseconds(0), error, interrupt, done);
909 if (result == PacketResult::ErrorReplyTimeout)
910 break; // No more packets in the queue
912 if ((result != PacketResult::Success)) {
914 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
916 __FUNCTION__, error.AsCString());
917 m_mainloop.RequestTermination();
923 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
924 std::unique_ptr<Connection> &&connection) {
925 IOObjectSP read_object_sp = connection->GetReadObject();
926 GDBRemoteCommunicationServer::SetConnection(connection.release());
929 m_network_handle_up = m_mainloop.RegisterReadObject(
930 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
935 GDBRemoteCommunication::PacketResult
936 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
938 if ((buffer == nullptr) || (len == 0)) {
940 return PacketResult::Success;
943 StreamString response;
944 response.PutChar('O');
945 response.PutBytesAsRawHex8(buffer, len);
947 return SendPacketNoLock(response.GetString());
950 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
953 // Set up the reading/handling of process I/O
954 std::unique_ptr<ConnectionFileDescriptor> conn_up(
955 new ConnectionFileDescriptor(fd, true));
957 error.SetErrorString("failed to create ConnectionFileDescriptor");
961 m_stdio_communication.SetCloseOnEOF(false);
962 m_stdio_communication.SetConnection(conn_up.release());
963 if (!m_stdio_communication.IsConnected()) {
964 error.SetErrorString(
965 "failed to set connection for inferior I/O communication");
972 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
973 // Don't forward if not connected (e.g. when attaching).
974 if (!m_stdio_communication.IsConnected())
978 lldbassert(!m_stdio_handle_up);
979 m_stdio_handle_up = m_mainloop.RegisterReadObject(
980 m_stdio_communication.GetConnection()->GetReadObject(),
981 [this](MainLoopBase &) { SendProcessOutput(); }, error);
983 if (!m_stdio_handle_up) {
984 // Not much we can do about the failure. Log it and continue without
986 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
987 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
989 __FUNCTION__, error.AsCString());
993 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
994 m_stdio_handle_up.reset();
997 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
999 ConnectionStatus status;
1002 size_t bytes_read = m_stdio_communication.Read(
1003 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1005 case eConnectionStatusSuccess:
1006 SendONotification(buffer, bytes_read);
1008 case eConnectionStatusLostConnection:
1009 case eConnectionStatusEndOfFile:
1010 case eConnectionStatusError:
1011 case eConnectionStatusNoConnection:
1012 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1013 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1014 "forwarding as communication returned status %d (error: "
1016 __FUNCTION__, status, error.AsCString());
1017 m_stdio_handle_up.reset();
1020 case eConnectionStatusInterrupted:
1021 case eConnectionStatusTimedOut:
1027 GDBRemoteCommunication::PacketResult
1028 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1029 StringExtractorGDBRemote &packet) {
1030 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1031 // Fail if we don't have a current process.
1032 if (!m_debugged_process_up ||
1033 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1034 return SendErrorResponse(68);
1036 if (!packet.ConsumeFront("jTraceStart:"))
1037 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1039 TraceOptions options;
1040 uint64_t type = std::numeric_limits<uint64_t>::max();
1041 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1042 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1043 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1045 auto json_object = StructuredData::ParseJSON(packet.Peek());
1048 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1049 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1051 auto json_dict = json_object->GetAsDictionary();
1053 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1054 options.setMetaDataBufferSize(metabuffersize);
1056 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1057 options.setTraceBufferSize(buffersize);
1059 json_dict->GetValueForKeyAsInteger("type", type);
1060 options.setType(static_cast<lldb::TraceType>(type));
1062 json_dict->GetValueForKeyAsInteger("threadid", tid);
1063 options.setThreadID(tid);
1065 StructuredData::ObjectSP custom_params_sp =
1066 json_dict->GetValueForKey("params");
1067 if (custom_params_sp &&
1068 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1069 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1071 options.setTraceParams(
1072 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1074 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1075 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1076 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1078 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1082 lldb::user_id_t uid = LLDB_INVALID_UID;
1083 uid = m_debugged_process_up->StartTrace(options, error);
1084 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1086 return SendErrorResponse(error);
1088 StreamGDBRemote response;
1089 response.Printf("%" PRIx64, uid);
1090 return SendPacketNoLock(response.GetString());
1093 GDBRemoteCommunication::PacketResult
1094 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1095 StringExtractorGDBRemote &packet) {
1096 // Fail if we don't have a current process.
1097 if (!m_debugged_process_up ||
1098 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1099 return SendErrorResponse(68);
1101 if (!packet.ConsumeFront("jTraceStop:"))
1102 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1104 lldb::user_id_t uid = LLDB_INVALID_UID;
1105 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1107 auto json_object = StructuredData::ParseJSON(packet.Peek());
1110 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1111 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1113 auto json_dict = json_object->GetAsDictionary();
1115 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1116 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1118 json_dict->GetValueForKeyAsInteger("threadid", tid);
1120 Status error = m_debugged_process_up->StopTrace(uid, tid);
1123 return SendErrorResponse(error);
1125 return SendOKResponse();
1128 GDBRemoteCommunication::PacketResult
1129 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1130 StringExtractorGDBRemote &packet) {
1132 // Fail if we don't have a current process.
1133 if (!m_debugged_process_up ||
1134 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1135 return SendErrorResponse(68);
1137 if (!packet.ConsumeFront("jTraceConfigRead:"))
1138 return SendIllFormedResponse(packet,
1139 "jTraceConfigRead: Ill formed packet ");
1141 lldb::user_id_t uid = LLDB_INVALID_UID;
1142 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1144 auto json_object = StructuredData::ParseJSON(packet.Peek());
1147 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1148 return SendIllFormedResponse(packet,
1149 "jTraceConfigRead: Ill formed packet ");
1151 auto json_dict = json_object->GetAsDictionary();
1153 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1154 return SendIllFormedResponse(packet,
1155 "jTraceConfigRead: Ill formed packet ");
1157 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1159 TraceOptions options;
1160 StreamGDBRemote response;
1162 options.setThreadID(threadid);
1163 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1166 return SendErrorResponse(error);
1168 StreamGDBRemote escaped_response;
1169 StructuredData::Dictionary json_packet;
1171 json_packet.AddIntegerItem("type", options.getType());
1172 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1173 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1175 StructuredData::DictionarySP custom_params = options.getTraceParams();
1177 json_packet.AddItem("params", custom_params);
1179 StreamString json_string;
1180 json_packet.Dump(json_string, false);
1181 escaped_response.PutEscapedBytes(json_string.GetData(),
1182 json_string.GetSize());
1183 return SendPacketNoLock(escaped_response.GetString());
1186 GDBRemoteCommunication::PacketResult
1187 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1188 StringExtractorGDBRemote &packet) {
1190 // Fail if we don't have a current process.
1191 if (!m_debugged_process_up ||
1192 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1193 return SendErrorResponse(68);
1195 enum PacketType { MetaData, BufferData };
1196 PacketType tracetype = MetaData;
1198 if (packet.ConsumeFront("jTraceBufferRead:"))
1199 tracetype = BufferData;
1200 else if (packet.ConsumeFront("jTraceMetaRead:"))
1201 tracetype = MetaData;
1203 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1206 lldb::user_id_t uid = LLDB_INVALID_UID;
1208 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1209 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1210 uint64_t offset = std::numeric_limits<uint64_t>::max();
1212 auto json_object = StructuredData::ParseJSON(packet.Peek());
1215 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1216 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1218 auto json_dict = json_object->GetAsDictionary();
1220 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1221 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1222 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1223 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1225 json_dict->GetValueForKeyAsInteger("threadid", tid);
1227 // Allocate the response buffer.
1228 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1230 return SendErrorResponse(0x78);
1232 StreamGDBRemote response;
1234 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1236 if (tracetype == BufferData)
1237 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1238 else if (tracetype == MetaData)
1239 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1242 return SendErrorResponse(error);
1245 response.PutHex8(i);
1247 StreamGDBRemote escaped_response;
1248 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1249 return SendPacketNoLock(escaped_response.GetString());
1252 GDBRemoteCommunication::PacketResult
1253 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1254 StringExtractorGDBRemote &packet) {
1255 // Fail if we don't have a current process.
1256 if (!m_debugged_process_up ||
1257 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1258 return SendErrorResponse(68);
1260 lldb::pid_t pid = m_debugged_process_up->GetID();
1262 if (pid == LLDB_INVALID_PROCESS_ID)
1263 return SendErrorResponse(1);
1265 ProcessInstanceInfo proc_info;
1266 if (!Host::GetProcessInfo(pid, proc_info))
1267 return SendErrorResponse(1);
1269 StreamString response;
1270 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1271 return SendPacketNoLock(response.GetString());
1274 GDBRemoteCommunication::PacketResult
1275 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1276 // Fail if we don't have a current process.
1277 if (!m_debugged_process_up ||
1278 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1279 return SendErrorResponse(68);
1281 // Make sure we set the current thread so g and p packets return the data the
1283 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1284 SetCurrentThreadID(tid);
1286 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1288 return SendErrorResponse(69);
1290 StreamString response;
1291 response.Printf("QC%" PRIx64, thread->GetID());
1293 return SendPacketNoLock(response.GetString());
1296 GDBRemoteCommunication::PacketResult
1297 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1298 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1300 StopSTDIOForwarding();
1302 if (!m_debugged_process_up) {
1303 LLDB_LOG(log, "No debugged process found.");
1304 return PacketResult::Success;
1307 Status error = m_debugged_process_up->Kill();
1309 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1310 m_debugged_process_up->GetID(), error);
1312 // No OK response for kill packet.
1313 // return SendOKResponse ();
1314 return PacketResult::Success;
1317 GDBRemoteCommunication::PacketResult
1318 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1319 StringExtractorGDBRemote &packet) {
1320 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1321 if (packet.GetU32(0))
1322 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1324 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1325 return SendOKResponse();
1328 GDBRemoteCommunication::PacketResult
1329 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1330 StringExtractorGDBRemote &packet) {
1331 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1333 packet.GetHexByteString(path);
1334 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1335 return SendOKResponse();
1338 GDBRemoteCommunication::PacketResult
1339 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1340 StringExtractorGDBRemote &packet) {
1341 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1343 StreamString response;
1344 response.PutCStringAsRawHex8(working_dir.GetCString());
1345 return SendPacketNoLock(response.GetString());
1348 return SendErrorResponse(14);
1351 GDBRemoteCommunication::PacketResult
1352 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1353 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1355 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1357 // Ensure we have a native process.
1358 if (!m_debugged_process_up) {
1360 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1363 return SendErrorResponse(0x36);
1366 // Pull out the signal number.
1367 packet.SetFilePos(::strlen("C"));
1368 if (packet.GetBytesLeft() < 1) {
1369 // Shouldn't be using a C without a signal.
1370 return SendIllFormedResponse(packet, "C packet specified without signal.");
1372 const uint32_t signo =
1373 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1374 if (signo == std::numeric_limits<uint32_t>::max())
1375 return SendIllFormedResponse(packet, "failed to parse signal number");
1377 // Handle optional continue address.
1378 if (packet.GetBytesLeft() > 0) {
1379 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1380 if (*packet.Peek() == ';')
1381 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1383 return SendIllFormedResponse(
1384 packet, "unexpected content after $C{signal-number}");
1387 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1390 // We have two branches: what to do if a continue thread is specified (in
1391 // which case we target sending the signal to that thread), or when we don't
1392 // have a continue thread set (in which case we send a signal to the
1395 // TODO discuss with Greg Clayton, make sure this makes sense.
1397 lldb::tid_t signal_tid = GetContinueThreadID();
1398 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1399 // The resume action for the continue thread (or all threads if a continue
1400 // thread is not set).
1401 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1402 static_cast<int>(signo)};
1404 // Add the action for the continue thread (or all threads when the continue
1405 // thread isn't present).
1406 resume_actions.Append(action);
1408 // Send the signal to the process since we weren't targeting a specific
1409 // continue thread with the signal.
1410 error = m_debugged_process_up->Signal(signo);
1412 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1413 m_debugged_process_up->GetID(), error);
1415 return SendErrorResponse(0x52);
1419 // Resume the threads.
1420 error = m_debugged_process_up->Resume(resume_actions);
1422 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1423 m_debugged_process_up->GetID(), error);
1425 return SendErrorResponse(0x38);
1428 // Don't send an "OK" packet; response is the stopped/exited message.
1429 return PacketResult::Success;
1432 GDBRemoteCommunication::PacketResult
1433 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1434 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1436 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1438 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1440 // For now just support all continue.
1441 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1442 if (has_continue_address) {
1443 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1445 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1448 // Ensure we have a native process.
1449 if (!m_debugged_process_up) {
1451 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1454 return SendErrorResponse(0x36);
1457 // Build the ResumeActionList
1458 ResumeActionList actions(StateType::eStateRunning, 0);
1460 Status error = m_debugged_process_up->Resume(actions);
1462 LLDB_LOG(log, "c failed for process {0}: {1}",
1463 m_debugged_process_up->GetID(), error);
1464 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1467 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1468 // No response required from continue.
1469 return PacketResult::Success;
1472 GDBRemoteCommunication::PacketResult
1473 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1474 StringExtractorGDBRemote &packet) {
1475 StreamString response;
1476 response.Printf("vCont;c;C;s;S");
1478 return SendPacketNoLock(response.GetString());
1481 GDBRemoteCommunication::PacketResult
1482 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1483 StringExtractorGDBRemote &packet) {
1484 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1486 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1489 packet.SetFilePos(::strlen("vCont"));
1491 if (packet.GetBytesLeft() == 0) {
1493 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1496 return SendIllFormedResponse(packet, "Missing action from vCont package");
1499 // Check if this is all continue (no options or ";c").
1500 if (::strcmp(packet.Peek(), ";c") == 0) {
1501 // Move past the ';', then do a simple 'c'.
1502 packet.SetFilePos(packet.GetFilePos() + 1);
1503 return Handle_c(packet);
1504 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1505 // Move past the ';', then do a simple 's'.
1506 packet.SetFilePos(packet.GetFilePos() + 1);
1507 return Handle_s(packet);
1510 // Ensure we have a native process.
1511 if (!m_debugged_process_up) {
1512 LLDB_LOG(log, "no debugged process");
1513 return SendErrorResponse(0x36);
1516 ResumeActionList thread_actions;
1518 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1519 // Skip the semi-colon.
1522 // Build up the thread action.
1523 ResumeAction thread_action;
1524 thread_action.tid = LLDB_INVALID_THREAD_ID;
1525 thread_action.state = eStateInvalid;
1526 thread_action.signal = 0;
1528 const char action = packet.GetChar();
1531 thread_action.signal = packet.GetHexMaxU32(false, 0);
1532 if (thread_action.signal == 0)
1533 return SendIllFormedResponse(
1534 packet, "Could not parse signal in vCont packet C action");
1539 thread_action.state = eStateRunning;
1543 thread_action.signal = packet.GetHexMaxU32(false, 0);
1544 if (thread_action.signal == 0)
1545 return SendIllFormedResponse(
1546 packet, "Could not parse signal in vCont packet S action");
1551 thread_action.state = eStateStepping;
1555 return SendIllFormedResponse(packet, "Unsupported vCont action");
1559 // Parse out optional :{thread-id} value.
1560 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1561 // Consume the separator.
1564 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1565 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1566 return SendIllFormedResponse(
1567 packet, "Could not parse thread number in vCont packet");
1570 thread_actions.Append(thread_action);
1573 Status error = m_debugged_process_up->Resume(thread_actions);
1575 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1576 m_debugged_process_up->GetID(), error);
1577 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1580 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1581 // No response required from vCont.
1582 return PacketResult::Success;
1585 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1586 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1587 LLDB_LOG(log, "setting current thread id to {0}", tid);
1589 m_current_tid = tid;
1590 if (m_debugged_process_up)
1591 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1594 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1595 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1596 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1598 m_continue_tid = tid;
1601 GDBRemoteCommunication::PacketResult
1602 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1603 StringExtractorGDBRemote &packet) {
1604 // Handle the $? gdbremote command.
1606 // If no process, indicate error
1607 if (!m_debugged_process_up)
1608 return SendErrorResponse(02);
1610 return SendStopReasonForState(m_debugged_process_up->GetState());
1613 GDBRemoteCommunication::PacketResult
1614 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1615 lldb::StateType process_state) {
1616 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1618 switch (process_state) {
1619 case eStateAttaching:
1620 case eStateLaunching:
1622 case eStateStepping:
1623 case eStateDetached:
1624 // NOTE: gdb protocol doc looks like it should return $OK
1625 // when everything is running (i.e. no stopped result).
1626 return PacketResult::Success; // Ignore
1628 case eStateSuspended:
1630 case eStateCrashed: {
1631 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1632 // Make sure we set the current thread so g and p packets return the data
1633 // the gdb will expect.
1634 SetCurrentThreadID(tid);
1635 return SendStopReplyPacketForThread(tid);
1639 case eStateUnloaded:
1641 return SendWResponse(m_debugged_process_up.get());
1644 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1645 m_debugged_process_up->GetID(), process_state);
1649 return SendErrorResponse(0);
1652 GDBRemoteCommunication::PacketResult
1653 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1654 StringExtractorGDBRemote &packet) {
1655 // Fail if we don't have a current process.
1656 if (!m_debugged_process_up ||
1657 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1658 return SendErrorResponse(68);
1660 // Ensure we have a thread.
1661 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1663 return SendErrorResponse(69);
1665 // Get the register context for the first thread.
1666 NativeRegisterContext ®_context = thread->GetRegisterContext();
1668 // Parse out the register number from the request.
1669 packet.SetFilePos(strlen("qRegisterInfo"));
1670 const uint32_t reg_index =
1671 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1672 if (reg_index == std::numeric_limits<uint32_t>::max())
1673 return SendErrorResponse(69);
1675 // Return the end of registers response if we've iterated one past the end of
1676 // the register set.
1677 if (reg_index >= reg_context.GetUserRegisterCount())
1678 return SendErrorResponse(69);
1680 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1682 return SendErrorResponse(69);
1684 // Build the reginfos response.
1685 StreamGDBRemote response;
1687 response.PutCString("name:");
1688 response.PutCString(reg_info->name);
1689 response.PutChar(';');
1691 if (reg_info->alt_name && reg_info->alt_name[0]) {
1692 response.PutCString("alt-name:");
1693 response.PutCString(reg_info->alt_name);
1694 response.PutChar(';');
1697 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1698 reg_info->byte_size * 8, reg_info->byte_offset);
1700 switch (reg_info->encoding) {
1702 response.PutCString("encoding:uint;");
1705 response.PutCString("encoding:sint;");
1707 case eEncodingIEEE754:
1708 response.PutCString("encoding:ieee754;");
1710 case eEncodingVector:
1711 response.PutCString("encoding:vector;");
1717 switch (reg_info->format) {
1719 response.PutCString("format:binary;");
1721 case eFormatDecimal:
1722 response.PutCString("format:decimal;");
1725 response.PutCString("format:hex;");
1728 response.PutCString("format:float;");
1730 case eFormatVectorOfSInt8:
1731 response.PutCString("format:vector-sint8;");
1733 case eFormatVectorOfUInt8:
1734 response.PutCString("format:vector-uint8;");
1736 case eFormatVectorOfSInt16:
1737 response.PutCString("format:vector-sint16;");
1739 case eFormatVectorOfUInt16:
1740 response.PutCString("format:vector-uint16;");
1742 case eFormatVectorOfSInt32:
1743 response.PutCString("format:vector-sint32;");
1745 case eFormatVectorOfUInt32:
1746 response.PutCString("format:vector-uint32;");
1748 case eFormatVectorOfFloat32:
1749 response.PutCString("format:vector-float32;");
1751 case eFormatVectorOfUInt64:
1752 response.PutCString("format:vector-uint64;");
1754 case eFormatVectorOfUInt128:
1755 response.PutCString("format:vector-uint128;");
1761 const char *const register_set_name =
1762 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1763 if (register_set_name) {
1764 response.PutCString("set:");
1765 response.PutCString(register_set_name);
1766 response.PutChar(';');
1769 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1770 LLDB_INVALID_REGNUM)
1771 response.Printf("ehframe:%" PRIu32 ";",
1772 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1774 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1775 response.Printf("dwarf:%" PRIu32 ";",
1776 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1778 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1779 case LLDB_REGNUM_GENERIC_PC:
1780 response.PutCString("generic:pc;");
1782 case LLDB_REGNUM_GENERIC_SP:
1783 response.PutCString("generic:sp;");
1785 case LLDB_REGNUM_GENERIC_FP:
1786 response.PutCString("generic:fp;");
1788 case LLDB_REGNUM_GENERIC_RA:
1789 response.PutCString("generic:ra;");
1791 case LLDB_REGNUM_GENERIC_FLAGS:
1792 response.PutCString("generic:flags;");
1794 case LLDB_REGNUM_GENERIC_ARG1:
1795 response.PutCString("generic:arg1;");
1797 case LLDB_REGNUM_GENERIC_ARG2:
1798 response.PutCString("generic:arg2;");
1800 case LLDB_REGNUM_GENERIC_ARG3:
1801 response.PutCString("generic:arg3;");
1803 case LLDB_REGNUM_GENERIC_ARG4:
1804 response.PutCString("generic:arg4;");
1806 case LLDB_REGNUM_GENERIC_ARG5:
1807 response.PutCString("generic:arg5;");
1809 case LLDB_REGNUM_GENERIC_ARG6:
1810 response.PutCString("generic:arg6;");
1812 case LLDB_REGNUM_GENERIC_ARG7:
1813 response.PutCString("generic:arg7;");
1815 case LLDB_REGNUM_GENERIC_ARG8:
1816 response.PutCString("generic:arg8;");
1822 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1823 response.PutCString("container-regs:");
1825 for (const uint32_t *reg_num = reg_info->value_regs;
1826 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1828 response.PutChar(',');
1829 response.Printf("%" PRIx32, *reg_num);
1831 response.PutChar(';');
1834 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1835 response.PutCString("invalidate-regs:");
1837 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1838 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1840 response.PutChar(',');
1841 response.Printf("%" PRIx32, *reg_num);
1843 response.PutChar(';');
1846 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1847 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1848 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1849 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1850 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1851 response.PutChar(';');
1853 return SendPacketNoLock(response.GetString());
1856 GDBRemoteCommunication::PacketResult
1857 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1858 StringExtractorGDBRemote &packet) {
1859 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1861 // Fail if we don't have a current process.
1862 if (!m_debugged_process_up ||
1863 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1864 LLDB_LOG(log, "no process ({0}), returning OK",
1865 m_debugged_process_up ? "invalid process id"
1866 : "null m_debugged_process_up");
1867 return SendOKResponse();
1870 StreamGDBRemote response;
1871 response.PutChar('m');
1873 LLDB_LOG(log, "starting thread iteration");
1874 NativeThreadProtocol *thread;
1875 uint32_t thread_index;
1876 for (thread_index = 0,
1877 thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1878 thread; ++thread_index,
1879 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1880 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1882 if (thread_index > 0)
1883 response.PutChar(',');
1884 response.Printf("%" PRIx64, thread->GetID());
1887 LLDB_LOG(log, "finished thread iteration");
1888 return SendPacketNoLock(response.GetString());
1891 GDBRemoteCommunication::PacketResult
1892 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1893 StringExtractorGDBRemote &packet) {
1894 // FIXME for now we return the full thread list in the initial packet and
1895 // always do nothing here.
1896 return SendPacketNoLock("l");
1899 GDBRemoteCommunication::PacketResult
1900 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1901 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1903 // Parse out the register number from the request.
1904 packet.SetFilePos(strlen("p"));
1905 const uint32_t reg_index =
1906 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1907 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1909 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1910 "parse register number from request \"%s\"",
1911 __FUNCTION__, packet.GetStringRef().c_str());
1912 return SendErrorResponse(0x15);
1915 // Get the thread to use.
1916 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1918 LLDB_LOG(log, "failed, no thread available");
1919 return SendErrorResponse(0x15);
1922 // Get the thread's register context.
1923 NativeRegisterContext ®_context = thread->GetRegisterContext();
1925 // Return the end of registers response if we've iterated one past the end of
1926 // the register set.
1927 if (reg_index >= reg_context.GetUserRegisterCount()) {
1929 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1930 "register %" PRIu32 " beyond register count %" PRIu32,
1931 __FUNCTION__, reg_index,
1932 reg_context.GetUserRegisterCount());
1933 return SendErrorResponse(0x15);
1936 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1939 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1940 "register %" PRIu32 " returned NULL",
1941 __FUNCTION__, reg_index);
1942 return SendErrorResponse(0x15);
1945 // Build the reginfos response.
1946 StreamGDBRemote response;
1948 // Retrieve the value
1949 RegisterValue reg_value;
1950 Status error = reg_context.ReadRegister(reg_info, reg_value);
1953 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1954 "requested register %" PRIu32 " (%s) failed: %s",
1955 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1956 return SendErrorResponse(0x15);
1959 const uint8_t *const data =
1960 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1963 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1964 "bytes from requested register %" PRIu32,
1965 __FUNCTION__, reg_index);
1966 return SendErrorResponse(0x15);
1969 // FIXME flip as needed to get data in big/little endian format for this host.
1970 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1971 response.PutHex8(data[i]);
1973 return SendPacketNoLock(response.GetString());
1976 GDBRemoteCommunication::PacketResult
1977 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1978 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1980 // Ensure there is more content.
1981 if (packet.GetBytesLeft() < 1)
1982 return SendIllFormedResponse(packet, "Empty P packet");
1984 // Parse out the register number from the request.
1985 packet.SetFilePos(strlen("P"));
1986 const uint32_t reg_index =
1987 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1988 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1990 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1991 "parse register number from request \"%s\"",
1992 __FUNCTION__, packet.GetStringRef().c_str());
1993 return SendErrorResponse(0x29);
1996 // Note debugserver would send an E30 here.
1997 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
1998 return SendIllFormedResponse(
1999 packet, "P packet missing '=' char after register number");
2001 // Parse out the value.
2002 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2003 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2005 // Get the thread to use.
2006 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2009 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2010 "available (thread index 0)",
2012 return SendErrorResponse(0x28);
2015 // Get the thread's register context.
2016 NativeRegisterContext ®_context = thread->GetRegisterContext();
2017 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2020 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2021 "register %" PRIu32 " returned NULL",
2022 __FUNCTION__, reg_index);
2023 return SendErrorResponse(0x48);
2026 // Return the end of registers response if we've iterated one past the end of
2027 // the register set.
2028 if (reg_index >= reg_context.GetUserRegisterCount()) {
2030 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2031 "register %" PRIu32 " beyond register count %" PRIu32,
2032 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2033 return SendErrorResponse(0x47);
2036 // The dwarf expression are evaluate on host site which may cause register
2037 // size to change Hence the reg_size may not be same as reg_info->bytes_size
2038 if ((reg_size != reg_info->byte_size) &&
2039 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2040 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2043 // Build the reginfos response.
2044 StreamGDBRemote response;
2046 RegisterValue reg_value(
2047 reg_bytes, reg_size,
2048 m_debugged_process_up->GetArchitecture().GetByteOrder());
2049 Status error = reg_context.WriteRegister(reg_info, reg_value);
2052 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2053 "requested register %" PRIu32 " (%s) failed: %s",
2054 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2055 return SendErrorResponse(0x32);
2058 return SendOKResponse();
2061 GDBRemoteCommunication::PacketResult
2062 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2063 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2065 // Fail if we don't have a current process.
2066 if (!m_debugged_process_up ||
2067 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2070 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2072 return SendErrorResponse(0x15);
2075 // Parse out which variant of $H is requested.
2076 packet.SetFilePos(strlen("H"));
2077 if (packet.GetBytesLeft() < 1) {
2079 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2080 "missing {g,c} variant",
2082 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2085 const char h_variant = packet.GetChar();
2086 switch (h_variant) {
2096 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2097 __FUNCTION__, h_variant);
2098 return SendIllFormedResponse(packet,
2099 "H variant unsupported, should be c or g");
2102 // Parse out the thread number.
2103 // FIXME return a parse success/fail value. All values are valid here.
2104 const lldb::tid_t tid =
2105 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2107 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2109 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2110 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2113 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2116 return SendErrorResponse(0x15);
2120 // Now switch the given thread type.
2121 switch (h_variant) {
2123 SetCurrentThreadID(tid);
2127 SetContinueThreadID(tid);
2131 assert(false && "unsupported $H variant - shouldn't get here");
2132 return SendIllFormedResponse(packet,
2133 "H variant unsupported, should be c or g");
2136 return SendOKResponse();
2139 GDBRemoteCommunication::PacketResult
2140 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2141 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2143 // Fail if we don't have a current process.
2144 if (!m_debugged_process_up ||
2145 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2148 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2150 return SendErrorResponse(0x15);
2153 packet.SetFilePos(::strlen("I"));
2156 size_t read = packet.GetHexBytesAvail(tmp);
2160 // write directly to stdin *this might block if stdin buffer is full*
2161 // TODO: enqueue this block in circular buffer and send window size to
2163 ConnectionStatus status;
2165 m_stdio_communication.Write(tmp, read, status, &error);
2167 return SendErrorResponse(0x15);
2171 return SendOKResponse();
2174 GDBRemoteCommunication::PacketResult
2175 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2176 StringExtractorGDBRemote &packet) {
2177 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2179 // Fail if we don't have a current process.
2180 if (!m_debugged_process_up ||
2181 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2182 LLDB_LOG(log, "failed, no process available");
2183 return SendErrorResponse(0x15);
2186 // Interrupt the process.
2187 Status error = m_debugged_process_up->Interrupt();
2189 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2191 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2194 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2196 // No response required from stop all.
2197 return PacketResult::Success;
2200 GDBRemoteCommunication::PacketResult
2201 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2202 StringExtractorGDBRemote &packet) {
2203 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2205 if (!m_debugged_process_up ||
2206 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2209 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2211 return SendErrorResponse(0x15);
2214 // Parse out the memory address.
2215 packet.SetFilePos(strlen("m"));
2216 if (packet.GetBytesLeft() < 1)
2217 return SendIllFormedResponse(packet, "Too short m packet");
2219 // Read the address. Punting on validation.
2220 // FIXME replace with Hex U64 read with no default value that fails on failed
2222 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2225 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2226 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2228 // Get # bytes to read.
2229 if (packet.GetBytesLeft() < 1)
2230 return SendIllFormedResponse(packet, "Length missing in m packet");
2232 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2233 if (byte_count == 0) {
2235 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2236 "zero-length packet",
2238 return SendOKResponse();
2241 // Allocate the response buffer.
2242 std::string buf(byte_count, '\0');
2244 return SendErrorResponse(0x78);
2246 // Retrieve the process memory.
2247 size_t bytes_read = 0;
2248 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2249 read_addr, &buf[0], byte_count, bytes_read);
2252 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2253 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2254 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2256 return SendErrorResponse(0x08);
2259 if (bytes_read == 0) {
2261 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2262 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2263 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2265 return SendErrorResponse(0x08);
2268 StreamGDBRemote response;
2269 packet.SetFilePos(0);
2270 char kind = packet.GetChar('?');
2272 response.PutEscapedBytes(buf.data(), byte_count);
2274 assert(kind == 'm');
2275 for (size_t i = 0; i < bytes_read; ++i)
2276 response.PutHex8(buf[i]);
2279 return SendPacketNoLock(response.GetString());
2282 GDBRemoteCommunication::PacketResult
2283 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2284 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2286 if (!m_debugged_process_up ||
2287 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2290 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2292 return SendErrorResponse(0x15);
2295 // Parse out the memory address.
2296 packet.SetFilePos(strlen("M"));
2297 if (packet.GetBytesLeft() < 1)
2298 return SendIllFormedResponse(packet, "Too short M packet");
2300 // Read the address. Punting on validation.
2301 // FIXME replace with Hex U64 read with no default value that fails on failed
2303 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2306 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2307 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2309 // Get # bytes to read.
2310 if (packet.GetBytesLeft() < 1)
2311 return SendIllFormedResponse(packet, "Length missing in M packet");
2313 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2314 if (byte_count == 0) {
2315 LLDB_LOG(log, "nothing to write: zero-length packet");
2316 return PacketResult::Success;
2320 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2321 return SendIllFormedResponse(
2322 packet, "Comma sep missing in M packet after byte length");
2324 // Allocate the conversion buffer.
2325 std::vector<uint8_t> buf(byte_count, 0);
2327 return SendErrorResponse(0x78);
2329 // Convert the hex memory write contents to bytes.
2330 StreamGDBRemote response;
2331 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2332 if (convert_count != byte_count) {
2334 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2336 m_debugged_process_up->GetID(), write_addr, byte_count,
2338 return SendIllFormedResponse(packet, "M content byte length specified did "
2339 "not match hex-encoded content "
2343 // Write the process memory.
2344 size_t bytes_written = 0;
2345 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2346 byte_count, bytes_written);
2348 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2349 m_debugged_process_up->GetID(), write_addr, error);
2350 return SendErrorResponse(0x09);
2353 if (bytes_written == 0) {
2354 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2355 m_debugged_process_up->GetID(), write_addr, byte_count);
2356 return SendErrorResponse(0x09);
2359 return SendOKResponse();
2362 GDBRemoteCommunication::PacketResult
2363 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2364 StringExtractorGDBRemote &packet) {
2365 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2367 // Currently only the NativeProcessProtocol knows if it can handle a
2368 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2369 // attached to a process. For now we'll assume the client only asks this
2370 // when a process is being debugged.
2372 // Ensure we have a process running; otherwise, we can't figure this out
2373 // since we won't have a NativeProcessProtocol.
2374 if (!m_debugged_process_up ||
2375 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2378 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2380 return SendErrorResponse(0x15);
2383 // Test if we can get any region back when asking for the region around NULL.
2384 MemoryRegionInfo region_info;
2385 const Status error =
2386 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2388 // We don't support memory region info collection for this
2389 // NativeProcessProtocol.
2390 return SendUnimplementedResponse("");
2393 return SendOKResponse();
2396 GDBRemoteCommunication::PacketResult
2397 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2398 StringExtractorGDBRemote &packet) {
2399 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2401 // Ensure we have a process.
2402 if (!m_debugged_process_up ||
2403 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2406 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2408 return SendErrorResponse(0x15);
2411 // Parse out the memory address.
2412 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2413 if (packet.GetBytesLeft() < 1)
2414 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2416 // Read the address. Punting on validation.
2417 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2419 StreamGDBRemote response;
2421 // Get the memory region info for the target address.
2422 MemoryRegionInfo region_info;
2423 const Status error =
2424 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2426 // Return the error message.
2428 response.PutCString("error:");
2429 response.PutCStringAsRawHex8(error.AsCString());
2430 response.PutChar(';');
2432 // Range start and size.
2433 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2434 region_info.GetRange().GetRangeBase(),
2435 region_info.GetRange().GetByteSize());
2438 if (region_info.GetReadable() || region_info.GetWritable() ||
2439 region_info.GetExecutable()) {
2440 // Write permissions info.
2441 response.PutCString("permissions:");
2443 if (region_info.GetReadable())
2444 response.PutChar('r');
2445 if (region_info.GetWritable())
2446 response.PutChar('w');
2447 if (region_info.GetExecutable())
2448 response.PutChar('x');
2450 response.PutChar(';');
2454 ConstString name = region_info.GetName();
2456 response.PutCString("name:");
2457 response.PutCStringAsRawHex8(name.AsCString());
2458 response.PutChar(';');
2462 return SendPacketNoLock(response.GetString());
2465 GDBRemoteCommunication::PacketResult
2466 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2467 // Ensure we have a process.
2468 if (!m_debugged_process_up ||
2469 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2470 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2471 LLDB_LOG(log, "failed, no process available");
2472 return SendErrorResponse(0x15);
2475 // Parse out software or hardware breakpoint or watchpoint requested.
2476 packet.SetFilePos(strlen("Z"));
2477 if (packet.GetBytesLeft() < 1)
2478 return SendIllFormedResponse(
2479 packet, "Too short Z packet, missing software/hardware specifier");
2481 bool want_breakpoint = true;
2482 bool want_hardware = false;
2483 uint32_t watch_flags = 0;
2485 const GDBStoppointType stoppoint_type =
2486 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2487 switch (stoppoint_type) {
2488 case eBreakpointSoftware:
2489 want_hardware = false;
2490 want_breakpoint = true;
2492 case eBreakpointHardware:
2493 want_hardware = true;
2494 want_breakpoint = true;
2496 case eWatchpointWrite:
2498 want_hardware = true;
2499 want_breakpoint = false;
2501 case eWatchpointRead:
2503 want_hardware = true;
2504 want_breakpoint = false;
2506 case eWatchpointReadWrite:
2508 want_hardware = true;
2509 want_breakpoint = false;
2511 case eStoppointInvalid:
2512 return SendIllFormedResponse(
2513 packet, "Z packet had invalid software/hardware specifier");
2516 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2517 return SendIllFormedResponse(
2518 packet, "Malformed Z packet, expecting comma after stoppoint type");
2520 // Parse out the stoppoint address.
2521 if (packet.GetBytesLeft() < 1)
2522 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2523 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2525 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2526 return SendIllFormedResponse(
2527 packet, "Malformed Z packet, expecting comma after address");
2529 // Parse out the stoppoint size (i.e. size hint for opcode size).
2530 const uint32_t size =
2531 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2532 if (size == std::numeric_limits<uint32_t>::max())
2533 return SendIllFormedResponse(
2534 packet, "Malformed Z packet, failed to parse size argument");
2536 if (want_breakpoint) {
2537 // Try to set the breakpoint.
2538 const Status error =
2539 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2540 if (error.Success())
2541 return SendOKResponse();
2542 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2543 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2544 m_debugged_process_up->GetID(), error);
2545 return SendErrorResponse(0x09);
2547 // Try to set the watchpoint.
2548 const Status error = m_debugged_process_up->SetWatchpoint(
2549 addr, size, watch_flags, want_hardware);
2550 if (error.Success())
2551 return SendOKResponse();
2552 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2553 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2554 m_debugged_process_up->GetID(), error);
2555 return SendErrorResponse(0x09);
2559 GDBRemoteCommunication::PacketResult
2560 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2561 // Ensure we have a process.
2562 if (!m_debugged_process_up ||
2563 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2564 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2565 LLDB_LOG(log, "failed, no process available");
2566 return SendErrorResponse(0x15);
2569 // Parse out software or hardware breakpoint or watchpoint requested.
2570 packet.SetFilePos(strlen("z"));
2571 if (packet.GetBytesLeft() < 1)
2572 return SendIllFormedResponse(
2573 packet, "Too short z packet, missing software/hardware specifier");
2575 bool want_breakpoint = true;
2576 bool want_hardware = false;
2578 const GDBStoppointType stoppoint_type =
2579 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2580 switch (stoppoint_type) {
2581 case eBreakpointHardware:
2582 want_breakpoint = true;
2583 want_hardware = true;
2585 case eBreakpointSoftware:
2586 want_breakpoint = true;
2588 case eWatchpointWrite:
2589 want_breakpoint = false;
2591 case eWatchpointRead:
2592 want_breakpoint = false;
2594 case eWatchpointReadWrite:
2595 want_breakpoint = false;
2598 return SendIllFormedResponse(
2599 packet, "z packet had invalid software/hardware specifier");
2602 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2603 return SendIllFormedResponse(
2604 packet, "Malformed z packet, expecting comma after stoppoint type");
2606 // Parse out the stoppoint address.
2607 if (packet.GetBytesLeft() < 1)
2608 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2609 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2611 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2612 return SendIllFormedResponse(
2613 packet, "Malformed z packet, expecting comma after address");
2616 // Parse out the stoppoint size (i.e. size hint for opcode size).
2617 const uint32_t size = packet.GetHexMaxU32 (false,
2618 std::numeric_limits<uint32_t>::max ());
2619 if (size == std::numeric_limits<uint32_t>::max ())
2620 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2624 if (want_breakpoint) {
2625 // Try to clear the breakpoint.
2626 const Status error =
2627 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2628 if (error.Success())
2629 return SendOKResponse();
2630 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2631 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2632 m_debugged_process_up->GetID(), error);
2633 return SendErrorResponse(0x09);
2635 // Try to clear the watchpoint.
2636 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2637 if (error.Success())
2638 return SendOKResponse();
2639 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2640 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2641 m_debugged_process_up->GetID(), error);
2642 return SendErrorResponse(0x09);
2646 GDBRemoteCommunication::PacketResult
2647 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2648 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2650 // Ensure we have a process.
2651 if (!m_debugged_process_up ||
2652 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2655 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2657 return SendErrorResponse(0x32);
2660 // We first try to use a continue thread id. If any one or any all set, use
2661 // the current thread. Bail out if we don't have a thread id.
2662 lldb::tid_t tid = GetContinueThreadID();
2663 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2664 tid = GetCurrentThreadID();
2665 if (tid == LLDB_INVALID_THREAD_ID)
2666 return SendErrorResponse(0x33);
2668 // Double check that we have such a thread.
2669 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2670 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2672 return SendErrorResponse(0x33);
2674 // Create the step action for the given thread.
2675 ResumeAction action = {tid, eStateStepping, 0};
2677 // Setup the actions list.
2678 ResumeActionList actions;
2679 actions.Append(action);
2681 // All other threads stop while we're single stepping a thread.
2682 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2683 Status error = m_debugged_process_up->Resume(actions);
2686 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2687 " tid %" PRIu64 " Resume() failed with error: %s",
2688 __FUNCTION__, m_debugged_process_up->GetID(), tid,
2690 return SendErrorResponse(0x49);
2693 // No response here - the stop or exit will come from the resulting action.
2694 return PacketResult::Success;
2697 GDBRemoteCommunication::PacketResult
2698 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2699 StringExtractorGDBRemote &packet) {
2700 // *BSD impls should be able to do this too.
2701 #if defined(__linux__) || defined(__NetBSD__)
2702 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2704 // Parse out the offset.
2705 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2706 if (packet.GetBytesLeft() < 1)
2707 return SendIllFormedResponse(packet,
2708 "qXfer:auxv:read:: packet missing offset");
2710 const uint64_t auxv_offset =
2711 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2712 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2713 return SendIllFormedResponse(packet,
2714 "qXfer:auxv:read:: packet missing offset");
2717 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2718 return SendIllFormedResponse(
2719 packet, "qXfer:auxv:read:: packet missing comma after offset");
2721 // Parse out the length.
2722 const uint64_t auxv_length =
2723 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2724 if (auxv_length == std::numeric_limits<uint64_t>::max())
2725 return SendIllFormedResponse(packet,
2726 "qXfer:auxv:read:: packet missing length");
2728 // Grab the auxv data if we need it.
2729 if (!m_active_auxv_buffer_up) {
2730 // Make sure we have a valid process.
2731 if (!m_debugged_process_up ||
2732 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2735 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2737 return SendErrorResponse(0x10);
2740 // Grab the auxv data.
2741 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2742 if (!buffer_or_error) {
2743 std::error_code ec = buffer_or_error.getError();
2744 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2745 return SendErrorResponse(ec.value());
2747 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2750 StreamGDBRemote response;
2751 bool done_with_buffer = false;
2753 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2754 if (auxv_offset >= buffer.size()) {
2755 // We have nothing left to send. Mark the buffer as complete.
2756 response.PutChar('l');
2757 done_with_buffer = true;
2759 // Figure out how many bytes are available starting at the given offset.
2760 buffer = buffer.drop_front(auxv_offset);
2762 // Mark the response type according to whether we're reading the remainder
2763 // of the auxv data.
2764 if (auxv_length >= buffer.size()) {
2765 // There will be nothing left to read after this
2766 response.PutChar('l');
2767 done_with_buffer = true;
2769 // There will still be bytes to read after this request.
2770 response.PutChar('m');
2771 buffer = buffer.take_front(auxv_length);
2774 // Now write the data in encoded binary form.
2775 response.PutEscapedBytes(buffer.data(), buffer.size());
2778 if (done_with_buffer)
2779 m_active_auxv_buffer_up.reset();
2781 return SendPacketNoLock(response.GetString());
2783 return SendUnimplementedResponse("not implemented on this platform");
2787 GDBRemoteCommunication::PacketResult
2788 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2789 StringExtractorGDBRemote &packet) {
2790 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2792 // Move past packet name.
2793 packet.SetFilePos(strlen("QSaveRegisterState"));
2795 // Get the thread to use.
2796 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2798 if (m_thread_suffix_supported)
2799 return SendIllFormedResponse(
2800 packet, "No thread specified in QSaveRegisterState packet");
2802 return SendIllFormedResponse(packet,
2803 "No thread was is set with the Hg packet");
2806 // Grab the register context for the thread.
2807 NativeRegisterContext& reg_context = thread->GetRegisterContext();
2809 // Save registers to a buffer.
2810 DataBufferSP register_data_sp;
2811 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2813 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2814 m_debugged_process_up->GetID(), error);
2815 return SendErrorResponse(0x75);
2818 // Allocate a new save id.
2819 const uint32_t save_id = GetNextSavedRegistersID();
2820 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2821 "GetNextRegisterSaveID() returned an existing register save id");
2823 // Save the register data buffer under the save id.
2825 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2826 m_saved_registers_map[save_id] = register_data_sp;
2829 // Write the response.
2830 StreamGDBRemote response;
2831 response.Printf("%" PRIu32, save_id);
2832 return SendPacketNoLock(response.GetString());
2835 GDBRemoteCommunication::PacketResult
2836 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2837 StringExtractorGDBRemote &packet) {
2838 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2840 // Parse out save id.
2841 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2842 if (packet.GetBytesLeft() < 1)
2843 return SendIllFormedResponse(
2844 packet, "QRestoreRegisterState packet missing register save id");
2846 const uint32_t save_id = packet.GetU32(0);
2848 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2849 "expecting decimal uint32_t");
2850 return SendErrorResponse(0x76);
2853 // Get the thread to use.
2854 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2856 if (m_thread_suffix_supported)
2857 return SendIllFormedResponse(
2858 packet, "No thread specified in QRestoreRegisterState packet");
2860 return SendIllFormedResponse(packet,
2861 "No thread was is set with the Hg packet");
2864 // Grab the register context for the thread.
2865 NativeRegisterContext ®_context = thread->GetRegisterContext();
2867 // Retrieve register state buffer, then remove from the list.
2868 DataBufferSP register_data_sp;
2870 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2872 // Find the register set buffer for the given save id.
2873 auto it = m_saved_registers_map.find(save_id);
2874 if (it == m_saved_registers_map.end()) {
2876 "pid {0} does not have a register set save buffer for id {1}",
2877 m_debugged_process_up->GetID(), save_id);
2878 return SendErrorResponse(0x77);
2880 register_data_sp = it->second;
2882 // Remove it from the map.
2883 m_saved_registers_map.erase(it);
2886 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
2888 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2889 m_debugged_process_up->GetID(), error);
2890 return SendErrorResponse(0x77);
2893 return SendOKResponse();
2896 GDBRemoteCommunication::PacketResult
2897 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2898 StringExtractorGDBRemote &packet) {
2899 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2901 // Consume the ';' after vAttach.
2902 packet.SetFilePos(strlen("vAttach"));
2903 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2904 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2906 // Grab the PID to which we will attach (assume hex encoding).
2907 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2908 if (pid == LLDB_INVALID_PROCESS_ID)
2909 return SendIllFormedResponse(packet,
2910 "vAttach failed to parse the process id");
2912 // Attempt to attach.
2914 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2918 Status error = AttachToProcess(pid);
2922 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2923 "pid %" PRIu64 ": %s\n",
2924 __FUNCTION__, pid, error.AsCString());
2925 return SendErrorResponse(error);
2928 // Notify we attached by sending a stop packet.
2929 return SendStopReasonForState(m_debugged_process_up->GetState());
2932 GDBRemoteCommunication::PacketResult
2933 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2934 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2936 StopSTDIOForwarding();
2938 // Fail if we don't have a current process.
2939 if (!m_debugged_process_up ||
2940 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2943 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2945 return SendErrorResponse(0x15);
2948 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2950 // Consume the ';' after D.
2951 packet.SetFilePos(1);
2952 if (packet.GetBytesLeft()) {
2953 if (packet.GetChar() != ';')
2954 return SendIllFormedResponse(packet, "D missing expected ';'");
2956 // Grab the PID from which we will detach (assume hex encoding).
2957 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2958 if (pid == LLDB_INVALID_PROCESS_ID)
2959 return SendIllFormedResponse(packet, "D failed to parse the process id");
2962 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
2963 return SendIllFormedResponse(packet, "Invalid pid");
2966 const Status error = m_debugged_process_up->Detach();
2969 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2970 "pid %" PRIu64 ": %s\n",
2971 __FUNCTION__, m_debugged_process_up->GetID(),
2973 return SendErrorResponse(0x01);
2976 return SendOKResponse();
2979 GDBRemoteCommunication::PacketResult
2980 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2981 StringExtractorGDBRemote &packet) {
2982 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2984 packet.SetFilePos(strlen("qThreadStopInfo"));
2985 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2986 if (tid == LLDB_INVALID_THREAD_ID) {
2988 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2989 "parse thread id from request \"%s\"",
2990 __FUNCTION__, packet.GetStringRef().c_str());
2991 return SendErrorResponse(0x15);
2993 return SendStopReplyPacketForThread(tid);
2996 GDBRemoteCommunication::PacketResult
2997 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
2998 StringExtractorGDBRemote &) {
2999 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3001 // Ensure we have a debugged process.
3002 if (!m_debugged_process_up ||
3003 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3004 return SendErrorResponse(50);
3005 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3007 StreamString response;
3008 const bool threads_with_valid_stop_info_only = false;
3009 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3010 *m_debugged_process_up, threads_with_valid_stop_info_only);
3011 if (!threads_array_sp) {
3012 LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3013 m_debugged_process_up->GetID());
3014 return SendErrorResponse(52);
3017 threads_array_sp->Write(response);
3018 StreamGDBRemote escaped_response;
3019 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3020 return SendPacketNoLock(escaped_response.GetString());
3023 GDBRemoteCommunication::PacketResult
3024 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3025 StringExtractorGDBRemote &packet) {
3026 // Fail if we don't have a current process.
3027 if (!m_debugged_process_up ||
3028 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3029 return SendErrorResponse(68);
3031 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3032 if (packet.GetBytesLeft() == 0)
3033 return SendOKResponse();
3034 if (packet.GetChar() != ':')
3035 return SendErrorResponse(67);
3037 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3039 StreamGDBRemote response;
3040 if (hw_debug_cap == llvm::None)
3041 response.Printf("num:0;");
3043 response.Printf("num:%d;", hw_debug_cap->second);
3045 return SendPacketNoLock(response.GetString());
3048 GDBRemoteCommunication::PacketResult
3049 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3050 StringExtractorGDBRemote &packet) {
3051 // Fail if we don't have a current process.
3052 if (!m_debugged_process_up ||
3053 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3054 return SendErrorResponse(67);
3056 packet.SetFilePos(strlen("qFileLoadAddress:"));
3057 if (packet.GetBytesLeft() == 0)
3058 return SendErrorResponse(68);
3060 std::string file_name;
3061 packet.GetHexByteString(file_name);
3063 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3065 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3067 return SendErrorResponse(69);
3069 if (file_load_address == LLDB_INVALID_ADDRESS)
3070 return SendErrorResponse(1); // File not loaded
3072 StreamGDBRemote response;
3073 response.PutHex64(file_load_address);
3074 return SendPacketNoLock(response.GetString());
3077 GDBRemoteCommunication::PacketResult
3078 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3079 StringExtractorGDBRemote &packet) {
3080 std::vector<int> signals;
3081 packet.SetFilePos(strlen("QPassSignals:"));
3083 // Read sequence of hex signal numbers divided by a semicolon and optionally
3085 while (packet.GetBytesLeft() > 0) {
3086 int signal = packet.GetS32(-1, 16);
3088 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3089 signals.push_back(signal);
3091 packet.SkipSpaces();
3092 char separator = packet.GetChar();
3093 if (separator == '\0')
3094 break; // End of string
3095 if (separator != ';')
3096 return SendIllFormedResponse(packet, "Invalid separator,"
3097 " expected semicolon.");
3100 // Fail if we don't have a current process.
3101 if (!m_debugged_process_up)
3102 return SendErrorResponse(68);
3104 Status error = m_debugged_process_up->IgnoreSignals(signals);
3106 return SendErrorResponse(69);
3108 return SendOKResponse();
3111 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3112 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3114 // Tell the stdio connection to shut down.
3115 if (m_stdio_communication.IsConnected()) {
3116 auto connection = m_stdio_communication.GetConnection();
3119 connection->Disconnect(&error);
3121 if (error.Success()) {
3123 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3124 "terminal stdio - SUCCESS",
3128 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3129 "terminal stdio - FAIL: %s",
3130 __FUNCTION__, error.AsCString());
3136 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3137 StringExtractorGDBRemote &packet) {
3138 // We have no thread if we don't have a process.
3139 if (!m_debugged_process_up ||
3140 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3143 // If the client hasn't asked for thread suffix support, there will not be a
3144 // thread suffix. Use the current thread in that case.
3145 if (!m_thread_suffix_supported) {
3146 const lldb::tid_t current_tid = GetCurrentThreadID();
3147 if (current_tid == LLDB_INVALID_THREAD_ID)
3149 else if (current_tid == 0) {
3151 return m_debugged_process_up->GetThreadAtIndex(0);
3153 return m_debugged_process_up->GetThreadByID(current_tid);
3156 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3158 // Parse out the ';'.
3159 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3161 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3162 "error: expected ';' prior to start of thread suffix: packet "
3164 __FUNCTION__, packet.GetStringRef().c_str());
3168 if (!packet.GetBytesLeft())
3171 // Parse out thread: portion.
3172 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3174 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3175 "error: expected 'thread:' but not found, packet contents = "
3177 __FUNCTION__, packet.GetStringRef().c_str());
3180 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3181 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3183 return m_debugged_process_up->GetThreadByID(tid);
3188 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3189 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3190 // Use whatever the debug process says is the current thread id since the
3191 // protocol either didn't specify or specified we want any/all threads
3192 // marked as the current thread.
3193 if (!m_debugged_process_up)
3194 return LLDB_INVALID_THREAD_ID;
3195 return m_debugged_process_up->GetCurrentThreadID();
3197 // Use the specific current thread id set by the gdb remote protocol.
3198 return m_current_tid;
3201 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3202 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3203 return m_next_saved_registers_id++;
3206 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3207 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3209 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3210 m_active_auxv_buffer_up.reset();
3214 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3215 const ArchSpec &arch) {
3216 if (m_debugged_process_up) {
3218 if (m_debugged_process_up
3219 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3221 if (FileSystem::Instance().Exists(file_spec))
3226 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);