1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "lldb/Host/Config.h"
14 #include "GDBRemoteCommunicationServerLLGS.h"
15 #include "lldb/Utility/StreamGDBRemote.h"
23 // Other libraries and framework includes
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Host/ConnectionFileDescriptor.h"
27 #include "lldb/Host/Debug.h"
28 #include "lldb/Host/File.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/PosixApi.h"
33 #include "lldb/Host/common/NativeProcessProtocol.h"
34 #include "lldb/Host/common/NativeRegisterContext.h"
35 #include "lldb/Host/common/NativeThreadProtocol.h"
36 #include "lldb/Interpreter/Args.h"
37 #include "lldb/Target/FileAction.h"
38 #include "lldb/Target/MemoryRegionInfo.h"
39 #include "lldb/Utility/DataBuffer.h"
40 #include "lldb/Utility/Endian.h"
41 #include "lldb/Utility/JSON.h"
42 #include "lldb/Utility/LLDBAssert.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/StreamString.h"
45 #include "lldb/Utility/UriParser.h"
46 #include "llvm/ADT/Triple.h"
47 #include "llvm/Support/ScopedPrinter.h"
50 #include "ProcessGDBRemote.h"
51 #include "ProcessGDBRemoteLog.h"
52 #include "Utility/StringExtractorGDBRemote.h"
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
64 enum GDBRemoteServerError {
65 // Set to the first unused error number in literal form below
67 eErrorNoProcess = eErrorFirst,
73 //----------------------------------------------------------------------
74 // GDBRemoteCommunicationServerLLGS constructor
75 //----------------------------------------------------------------------
76 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
77 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
78 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
79 "gdb-remote.server.rx_packet"),
80 m_mainloop(mainloop), m_process_factory(process_factory),
81 m_stdio_communication("process.stdio") {
82 RegisterPacketHandlers();
85 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
87 &GDBRemoteCommunicationServerLLGS::Handle_C);
88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
89 &GDBRemoteCommunicationServerLLGS::Handle_c);
90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
91 &GDBRemoteCommunicationServerLLGS::Handle_D);
92 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
93 &GDBRemoteCommunicationServerLLGS::Handle_H);
94 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
95 &GDBRemoteCommunicationServerLLGS::Handle_I);
96 RegisterMemberFunctionHandler(
97 StringExtractorGDBRemote::eServerPacketType_interrupt,
98 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_m,
101 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
103 &GDBRemoteCommunicationServerLLGS::Handle_M);
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
105 &GDBRemoteCommunicationServerLLGS::Handle_p);
106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
107 &GDBRemoteCommunicationServerLLGS::Handle_P);
108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
109 &GDBRemoteCommunicationServerLLGS::Handle_qC);
110 RegisterMemberFunctionHandler(
111 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
112 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
115 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
118 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
121 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
127 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
133 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
145 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
157 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
158 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
159 &GDBRemoteCommunicationServerLLGS::Handle_s);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_stop_reason,
162 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_vAttach,
165 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vCont,
168 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_x,
174 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
175 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
176 &GDBRemoteCommunicationServerLLGS::Handle_Z);
177 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
178 &GDBRemoteCommunicationServerLLGS::Handle_z);
179 RegisterMemberFunctionHandler(
180 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
181 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
183 RegisterMemberFunctionHandler(
184 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
185 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
191 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
194 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
195 RegisterMemberFunctionHandler(
196 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
197 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
199 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
200 [this](StringExtractorGDBRemote packet, Status &error,
201 bool &interrupt, bool &quit) {
203 return this->Handle_k(packet);
207 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
208 m_process_launch_info = info;
211 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
212 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
214 if (!m_process_launch_info.GetArguments().GetArgumentCount())
215 return Status("%s: no process command line specified to launch",
218 const bool should_forward_stdio =
219 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
220 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
221 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
222 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
223 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
225 const bool default_to_use_pty = true;
226 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
229 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
230 assert(!m_debugged_process_up && "lldb-server creating debugged "
231 "process but one already exists");
233 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
235 return Status(process_or.takeError());
236 m_debugged_process_up = std::move(*process_or);
239 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
241 // llgs local-process debugging may specify PTY paths, which will make these
242 // file actions non-null
243 // process launch -i/e/o will also make these file actions non-null
244 // nullptr means that the traffic is expected to flow over gdb-remote protocol
245 if (should_forward_stdio) {
246 // nullptr means it's not redirected to file or pty (in case of LLGS local)
247 // at least one of stdio will be transferred pty<->gdb-remote
248 // we need to give the pty master handle to this object to read and/or write
250 "pid = {0}: setting up stdout/stderr redirection via $O "
251 "gdb-remote commands",
252 m_debugged_process_up->GetID());
254 // Setup stdout/stderr mapping from inferior to $O
255 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
256 if (terminal_fd >= 0) {
258 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
259 "inferior STDIO fd to %d",
260 __FUNCTION__, terminal_fd);
261 Status status = SetSTDIOFileDescriptor(terminal_fd);
266 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
267 "inferior STDIO since terminal fd reported as %d",
268 __FUNCTION__, terminal_fd);
272 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
273 "will communicate over client-provided file descriptors",
274 m_debugged_process_up->GetID());
277 printf("Launched '%s' as process %" PRIu64 "...\n",
278 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
279 m_debugged_process_up->GetID());
284 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
285 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
287 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
290 // Before we try to attach, make sure we aren't already monitoring something
292 if (m_debugged_process_up &&
293 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
294 return Status("cannot attach to a process %" PRIu64
295 " when another process with pid %" PRIu64
296 " is being debugged.",
297 pid, m_debugged_process_up->GetID());
300 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
302 Status status(process_or.takeError());
303 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
307 m_debugged_process_up = std::move(*process_or);
309 // Setup stdout/stderr mapping from inferior.
310 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
311 if (terminal_fd >= 0) {
313 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
314 "inferior STDIO fd to %d",
315 __FUNCTION__, terminal_fd);
316 Status status = SetSTDIOFileDescriptor(terminal_fd);
321 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
322 "inferior STDIO since terminal fd reported as %d",
323 __FUNCTION__, terminal_fd);
326 printf("Attached to process %" PRIu64 "...\n", pid);
330 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
331 NativeProcessProtocol *process) {
332 assert(process && "process cannot be NULL");
333 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
335 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
336 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
337 __FUNCTION__, process->GetID(),
338 StateAsCString(process->GetState()));
342 GDBRemoteCommunication::PacketResult
343 GDBRemoteCommunicationServerLLGS::SendWResponse(
344 NativeProcessProtocol *process) {
345 assert(process && "process cannot be NULL");
346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
348 // send W notification
349 auto wait_status = process->GetExitStatus();
351 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
354 StreamGDBRemote response;
355 response.PutChar('E');
356 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
357 return SendPacketNoLock(response.GetString());
360 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
363 StreamGDBRemote response;
364 response.Format("{0:g}", *wait_status);
365 return SendPacketNoLock(response.GetString());
368 static void AppendHexValue(StreamString &response, const uint8_t *buf,
369 uint32_t buf_size, bool swap) {
372 for (i = buf_size - 1; i >= 0; i--)
373 response.PutHex8(buf[i]);
375 for (i = 0; i < buf_size; i++)
376 response.PutHex8(buf[i]);
380 static void WriteRegisterValueInHexFixedWidth(
381 StreamString &response, NativeRegisterContext ®_ctx,
382 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
383 lldb::ByteOrder byte_order) {
384 RegisterValue reg_value;
386 Status error = reg_ctx.ReadRegister(®_info, reg_value);
388 reg_value_p = ®_value;
393 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
394 reg_value_p->GetByteSize(),
395 byte_order == lldb::eByteOrderLittle);
397 // Zero-out any unreadable values.
398 if (reg_info.byte_size > 0) {
399 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
400 AppendHexValue(response, zeros.data(), zeros.size(), false);
405 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
406 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
408 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
410 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
412 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
413 // Expedite all registers in the first register set (i.e. should be GPRs) that
414 // are not contained in other registers.
415 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
418 for (const uint32_t *reg_num_p = reg_set_p->registers;
419 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
420 uint32_t reg_num = *reg_num_p;
422 // Expedite only a couple of registers until we figure out why sending
425 static const uint32_t k_expedited_registers[] = {
426 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
427 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
429 for (const uint32_t *generic_reg_p = k_expedited_registers;
430 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
431 uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
432 eRegisterKindGeneric, *generic_reg_p);
433 if (reg_num == LLDB_INVALID_REGNUM)
434 continue; // Target does not support the given register.
437 const RegisterInfo *const reg_info_p =
438 reg_ctx.GetRegisterInfoAtIndex(reg_num);
439 if (reg_info_p == nullptr) {
442 "%s failed to get register info for register index %" PRIu32,
443 __FUNCTION__, reg_num);
447 if (reg_info_p->value_regs != nullptr)
448 continue; // Only expedite registers that are not contained in other
451 RegisterValue reg_value;
452 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
455 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
457 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
458 reg_num, error.AsCString());
463 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
464 ®_value, lldb::eByteOrderBig);
466 register_object_sp->SetObject(
467 llvm::to_string(reg_num),
468 std::make_shared<JSONString>(stream.GetString()));
471 return register_object_sp;
474 static const char *GetStopReasonString(StopReason stop_reason) {
475 switch (stop_reason) {
476 case eStopReasonTrace:
478 case eStopReasonBreakpoint:
480 case eStopReasonWatchpoint:
482 case eStopReasonSignal:
484 case eStopReasonException:
486 case eStopReasonExec:
488 case eStopReasonInstrumentation:
489 case eStopReasonInvalid:
490 case eStopReasonPlanComplete:
491 case eStopReasonThreadExiting:
492 case eStopReasonNone:
498 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
500 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
502 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
504 // Ensure we can get info on the given thread.
505 uint32_t thread_idx = 0;
506 for (NativeThreadProtocol *thread;
507 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
510 lldb::tid_t tid = thread->GetID();
512 // Grab the reason this thread stopped.
513 struct ThreadStopInfo tid_stop_info;
514 std::string description;
515 if (!thread->GetStopReason(tid_stop_info, description))
518 const int signum = tid_stop_info.details.signal.signo;
520 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
522 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
523 __FUNCTION__, process.GetID(), tid, signum,
524 tid_stop_info.reason, tid_stop_info.details.exception.type);
527 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
528 threads_array_sp->AppendObject(thread_obj_sp);
531 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread))
532 thread_obj_sp->SetObject("registers", registers_sp);
535 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
537 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
539 const std::string thread_name = thread->GetName();
540 if (!thread_name.empty())
541 thread_obj_sp->SetObject("name",
542 std::make_shared<JSONString>(thread_name));
544 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
545 thread_obj_sp->SetObject("reason",
546 std::make_shared<JSONString>(stop_reason_str));
548 if (!description.empty())
549 thread_obj_sp->SetObject("description",
550 std::make_shared<JSONString>(description));
552 if ((tid_stop_info.reason == eStopReasonException) &&
553 tid_stop_info.details.exception.type) {
554 thread_obj_sp->SetObject(
556 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
558 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
559 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
561 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
562 tid_stop_info.details.exception.data[i]));
564 thread_obj_sp->SetObject("medata", medata_array_sp);
567 // TODO: Expedite interesting regions of inferior memory
570 return threads_array_sp;
573 GDBRemoteCommunication::PacketResult
574 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
576 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
578 // Ensure we have a debugged process.
579 if (!m_debugged_process_up ||
580 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
581 return SendErrorResponse(50);
583 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
584 m_debugged_process_up->GetID(), tid);
586 // Ensure we can get info on the given thread.
587 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
589 return SendErrorResponse(51);
591 // Grab the reason this thread stopped.
592 struct ThreadStopInfo tid_stop_info;
593 std::string description;
594 if (!thread->GetStopReason(tid_stop_info, description))
595 return SendErrorResponse(52);
597 // FIXME implement register handling for exec'd inferiors.
598 // if (tid_stop_info.reason == eStopReasonExec)
600 // const bool force = true;
601 // InitializeRegisters(force);
604 StreamString response;
605 // Output the T packet with the thread
606 response.PutChar('T');
607 int signum = tid_stop_info.details.signal.signo;
610 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
611 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
612 tid_stop_info.details.exception.type);
614 // Print the signal number.
615 response.PutHex8(signum & 0xff);
618 response.Printf("thread:%" PRIx64 ";", tid);
620 // Include the thread name if there is one.
621 const std::string thread_name = thread->GetName();
622 if (!thread_name.empty()) {
623 size_t thread_name_len = thread_name.length();
625 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
626 response.PutCString("name:");
627 response.PutCString(thread_name);
629 // The thread name contains special chars, send as hex bytes.
630 response.PutCString("hexname:");
631 response.PutCStringAsRawHex8(thread_name.c_str());
633 response.PutChar(';');
636 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
637 // will send all thread IDs back in the "threads" key whose value is
638 // a list of hex thread IDs separated by commas:
639 // "threads:10a,10b,10c;"
640 // This will save the debugger from having to send a pair of qfThreadInfo
641 // and qsThreadInfo packets, but it also might take a lot of room in the
642 // stop reply packet, so it must be enabled only on systems where there
643 // are no limits on packet lengths.
644 if (m_list_threads_in_stop_reply) {
645 response.PutCString("threads:");
647 uint32_t thread_index = 0;
648 NativeThreadProtocol *listed_thread;
649 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
650 listed_thread; ++thread_index,
651 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
652 if (thread_index > 0)
653 response.PutChar(',');
654 response.Printf("%" PRIx64, listed_thread->GetID());
656 response.PutChar(';');
658 // Include JSON info that describes the stop reason for any threads
659 // that actually have stop reasons. We use the new "jstopinfo" key
660 // whose values is hex ascii JSON that contains the thread IDs
661 // thread stop info only for threads that have stop reasons. Only send
662 // this if we have more than one thread otherwise this packet has all
663 // the info it needs.
664 if (thread_index > 0) {
665 const bool threads_with_valid_stop_info_only = true;
666 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
667 *m_debugged_process_up, threads_with_valid_stop_info_only);
668 if (threads_info_sp) {
669 response.PutCString("jstopinfo:");
670 StreamString unescaped_response;
671 threads_info_sp->Write(unescaped_response);
672 response.PutCStringAsRawHex8(unescaped_response.GetData());
673 response.PutChar(';');
675 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
676 m_debugged_process_up->GetID());
680 response.PutCString("thread-pcs");
681 char delimiter = ':';
682 for (NativeThreadProtocol *thread;
683 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
685 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
687 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
688 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
689 const RegisterInfo *const reg_info_p =
690 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
692 RegisterValue reg_value;
693 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
696 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
698 reg_info_p->name ? reg_info_p->name
699 : "<unnamed-register>",
700 reg_to_read, error.AsCString());
704 response.PutChar(delimiter);
706 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
707 ®_value, endian::InlHostByteOrder());
710 response.PutChar(';');
714 // Expedite registers.
717 // Grab the register context.
718 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
719 // Expedite all registers in the first register set (i.e. should be GPRs)
720 // that are not contained in other registers.
721 const RegisterSet *reg_set_p;
722 if (reg_ctx.GetRegisterSetCount() > 0 &&
723 ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
725 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
726 "from set '%s' (registers set count: %zu)",
728 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
729 reg_set_p->num_registers);
731 for (const uint32_t *reg_num_p = reg_set_p->registers;
732 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
733 const RegisterInfo *const reg_info_p =
734 reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
735 if (reg_info_p == nullptr) {
737 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
738 "register info for register set '%s', register index "
741 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
743 } else if (reg_info_p->value_regs == nullptr) {
744 // Only expediate registers that are not contained in other registers.
745 RegisterValue reg_value;
746 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
747 if (error.Success()) {
748 response.Printf("%.02x:", *reg_num_p);
749 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
750 ®_value, lldb::eByteOrderBig);
751 response.PutChar(';');
754 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
755 "register '%s' index %" PRIu32 ": %s",
757 reg_info_p->name ? reg_info_p->name
758 : "<unnamed-register>",
759 *reg_num_p, error.AsCString());
765 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
766 if (reason_str != nullptr) {
767 response.Printf("reason:%s;", reason_str);
770 if (!description.empty()) {
771 // Description may contains special chars, send as hex bytes.
772 response.PutCString("description:");
773 response.PutCStringAsRawHex8(description.c_str());
774 response.PutChar(';');
775 } else if ((tid_stop_info.reason == eStopReasonException) &&
776 tid_stop_info.details.exception.type) {
777 response.PutCString("metype:");
778 response.PutHex64(tid_stop_info.details.exception.type);
779 response.PutCString(";mecount:");
780 response.PutHex32(tid_stop_info.details.exception.data_count);
781 response.PutChar(';');
783 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
784 response.PutCString("medata:");
785 response.PutHex64(tid_stop_info.details.exception.data[i]);
786 response.PutChar(';');
790 return SendPacketNoLock(response.GetString());
793 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
794 NativeProcessProtocol *process) {
795 assert(process && "process cannot be NULL");
797 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
799 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
801 PacketResult result = SendStopReasonForState(StateType::eStateExited);
802 if (result != PacketResult::Success) {
804 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
805 "notification for PID %" PRIu64 ", state: eStateExited",
806 __FUNCTION__, process->GetID());
809 // Close the pipe to the inferior terminal i/o if we launched it
811 MaybeCloseInferiorTerminalConnection();
813 // We are ready to exit the debug monitor.
815 m_mainloop.RequestTermination();
818 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
819 NativeProcessProtocol *process) {
820 assert(process && "process cannot be NULL");
822 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
824 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
826 // Send the stop reason unless this is the stop after the
828 switch (m_inferior_prev_state) {
829 case eStateLaunching:
830 case eStateAttaching:
831 // Don't send anything per debugserver behavior.
834 // In all other cases, send the stop reason.
835 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
836 if (result != PacketResult::Success) {
838 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
839 "notification for PID %" PRIu64 ", state: eStateExited",
840 __FUNCTION__, process->GetID());
846 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
847 NativeProcessProtocol *process, lldb::StateType state) {
848 assert(process && "process cannot be NULL");
849 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
851 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
852 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
853 __FUNCTION__, process->GetID(), StateAsCString(state));
857 case StateType::eStateRunning:
858 StartSTDIOForwarding();
861 case StateType::eStateStopped:
862 // Make sure we get all of the pending stdout/stderr from the inferior
863 // and send it to the lldb host before we send the state change
866 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
868 // interfere with our protocol.
869 StopSTDIOForwarding();
870 HandleInferiorState_Stopped(process);
873 case StateType::eStateExited:
876 StopSTDIOForwarding();
877 HandleInferiorState_Exited(process);
882 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
883 "change for pid %" PRIu64 ", new state: %s",
884 __FUNCTION__, process->GetID(), StateAsCString(state));
889 // Remember the previous state reported to us.
890 m_inferior_prev_state = state;
893 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
894 ClearProcessSpecificData();
897 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
898 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
900 if (!m_handshake_completed) {
901 if (!HandshakeWithClient()) {
903 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
904 "client failed, exiting",
906 m_mainloop.RequestTermination();
909 m_handshake_completed = true;
912 bool interrupt = false;
916 const PacketResult result = GetPacketAndSendResponse(
917 std::chrono::microseconds(0), error, interrupt, done);
918 if (result == PacketResult::ErrorReplyTimeout)
919 break; // No more packets in the queue
921 if ((result != PacketResult::Success)) {
923 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
925 __FUNCTION__, error.AsCString());
926 m_mainloop.RequestTermination();
932 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
933 std::unique_ptr<Connection> &&connection) {
934 IOObjectSP read_object_sp = connection->GetReadObject();
935 GDBRemoteCommunicationServer::SetConnection(connection.release());
938 m_network_handle_up = m_mainloop.RegisterReadObject(
939 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
944 GDBRemoteCommunication::PacketResult
945 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
947 if ((buffer == nullptr) || (len == 0)) {
949 return PacketResult::Success;
952 StreamString response;
953 response.PutChar('O');
954 response.PutBytesAsRawHex8(buffer, len);
956 return SendPacketNoLock(response.GetString());
959 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
962 // Set up the reading/handling of process I/O
963 std::unique_ptr<ConnectionFileDescriptor> conn_up(
964 new ConnectionFileDescriptor(fd, true));
966 error.SetErrorString("failed to create ConnectionFileDescriptor");
970 m_stdio_communication.SetCloseOnEOF(false);
971 m_stdio_communication.SetConnection(conn_up.release());
972 if (!m_stdio_communication.IsConnected()) {
973 error.SetErrorString(
974 "failed to set connection for inferior I/O communication");
981 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
982 // Don't forward if not connected (e.g. when attaching).
983 if (!m_stdio_communication.IsConnected())
987 lldbassert(!m_stdio_handle_up);
988 m_stdio_handle_up = m_mainloop.RegisterReadObject(
989 m_stdio_communication.GetConnection()->GetReadObject(),
990 [this](MainLoopBase &) { SendProcessOutput(); }, error);
992 if (!m_stdio_handle_up) {
993 // Not much we can do about the failure. Log it and continue without
995 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
996 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
998 __FUNCTION__, error.AsCString());
1002 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1003 m_stdio_handle_up.reset();
1006 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1008 ConnectionStatus status;
1011 size_t bytes_read = m_stdio_communication.Read(
1012 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1014 case eConnectionStatusSuccess:
1015 SendONotification(buffer, bytes_read);
1017 case eConnectionStatusLostConnection:
1018 case eConnectionStatusEndOfFile:
1019 case eConnectionStatusError:
1020 case eConnectionStatusNoConnection:
1021 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1022 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1023 "forwarding as communication returned status %d (error: "
1025 __FUNCTION__, status, error.AsCString());
1026 m_stdio_handle_up.reset();
1029 case eConnectionStatusInterrupted:
1030 case eConnectionStatusTimedOut:
1036 GDBRemoteCommunication::PacketResult
1037 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1038 StringExtractorGDBRemote &packet) {
1039 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1040 // Fail if we don't have a current process.
1041 if (!m_debugged_process_up ||
1042 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1043 return SendErrorResponse(68);
1045 if (!packet.ConsumeFront("jTraceStart:"))
1046 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1048 TraceOptions options;
1049 uint64_t type = std::numeric_limits<uint64_t>::max();
1050 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1051 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1052 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1054 auto json_object = StructuredData::ParseJSON(packet.Peek());
1057 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1058 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1060 auto json_dict = json_object->GetAsDictionary();
1062 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1063 options.setMetaDataBufferSize(metabuffersize);
1065 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1066 options.setTraceBufferSize(buffersize);
1068 json_dict->GetValueForKeyAsInteger("type", type);
1069 options.setType(static_cast<lldb::TraceType>(type));
1071 json_dict->GetValueForKeyAsInteger("threadid", tid);
1072 options.setThreadID(tid);
1074 StructuredData::ObjectSP custom_params_sp =
1075 json_dict->GetValueForKey("params");
1076 if (custom_params_sp &&
1077 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1078 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1080 options.setTraceParams(
1081 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1083 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1084 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1085 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1087 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1091 lldb::user_id_t uid = LLDB_INVALID_UID;
1092 uid = m_debugged_process_up->StartTrace(options, error);
1093 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1095 return SendErrorResponse(error);
1097 StreamGDBRemote response;
1098 response.Printf("%" PRIx64, uid);
1099 return SendPacketNoLock(response.GetString());
1102 GDBRemoteCommunication::PacketResult
1103 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1104 StringExtractorGDBRemote &packet) {
1105 // Fail if we don't have a current process.
1106 if (!m_debugged_process_up ||
1107 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1108 return SendErrorResponse(68);
1110 if (!packet.ConsumeFront("jTraceStop:"))
1111 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1113 lldb::user_id_t uid = LLDB_INVALID_UID;
1114 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1116 auto json_object = StructuredData::ParseJSON(packet.Peek());
1119 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1120 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1122 auto json_dict = json_object->GetAsDictionary();
1124 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1125 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1127 json_dict->GetValueForKeyAsInteger("threadid", tid);
1129 Status error = m_debugged_process_up->StopTrace(uid, tid);
1132 return SendErrorResponse(error);
1134 return SendOKResponse();
1137 GDBRemoteCommunication::PacketResult
1138 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1139 StringExtractorGDBRemote &packet) {
1141 // Fail if we don't have a current process.
1142 if (!m_debugged_process_up ||
1143 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1144 return SendErrorResponse(68);
1146 if (!packet.ConsumeFront("jTraceConfigRead:"))
1147 return SendIllFormedResponse(packet,
1148 "jTraceConfigRead: Ill formed packet ");
1150 lldb::user_id_t uid = LLDB_INVALID_UID;
1151 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1153 auto json_object = StructuredData::ParseJSON(packet.Peek());
1156 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1157 return SendIllFormedResponse(packet,
1158 "jTraceConfigRead: Ill formed packet ");
1160 auto json_dict = json_object->GetAsDictionary();
1162 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1163 return SendIllFormedResponse(packet,
1164 "jTraceConfigRead: Ill formed packet ");
1166 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1168 TraceOptions options;
1169 StreamGDBRemote response;
1171 options.setThreadID(threadid);
1172 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1175 return SendErrorResponse(error);
1177 StreamGDBRemote escaped_response;
1178 StructuredData::Dictionary json_packet;
1180 json_packet.AddIntegerItem("type", options.getType());
1181 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1182 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1184 StructuredData::DictionarySP custom_params = options.getTraceParams();
1186 json_packet.AddItem("params", custom_params);
1188 StreamString json_string;
1189 json_packet.Dump(json_string, false);
1190 escaped_response.PutEscapedBytes(json_string.GetData(),
1191 json_string.GetSize());
1192 return SendPacketNoLock(escaped_response.GetString());
1195 GDBRemoteCommunication::PacketResult
1196 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1197 StringExtractorGDBRemote &packet) {
1199 // Fail if we don't have a current process.
1200 if (!m_debugged_process_up ||
1201 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1202 return SendErrorResponse(68);
1204 enum PacketType { MetaData, BufferData };
1205 PacketType tracetype = MetaData;
1207 if (packet.ConsumeFront("jTraceBufferRead:"))
1208 tracetype = BufferData;
1209 else if (packet.ConsumeFront("jTraceMetaRead:"))
1210 tracetype = MetaData;
1212 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1215 lldb::user_id_t uid = LLDB_INVALID_UID;
1217 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1218 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1219 uint64_t offset = std::numeric_limits<uint64_t>::max();
1221 auto json_object = StructuredData::ParseJSON(packet.Peek());
1224 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1225 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1227 auto json_dict = json_object->GetAsDictionary();
1229 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1230 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1231 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1232 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1234 json_dict->GetValueForKeyAsInteger("threadid", tid);
1236 // Allocate the response buffer.
1237 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1239 return SendErrorResponse(0x78);
1241 StreamGDBRemote response;
1243 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1245 if (tracetype == BufferData)
1246 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1247 else if (tracetype == MetaData)
1248 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1251 return SendErrorResponse(error);
1254 response.PutHex8(i);
1256 StreamGDBRemote escaped_response;
1257 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1258 return SendPacketNoLock(escaped_response.GetString());
1261 GDBRemoteCommunication::PacketResult
1262 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1263 StringExtractorGDBRemote &packet) {
1264 // Fail if we don't have a current process.
1265 if (!m_debugged_process_up ||
1266 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1267 return SendErrorResponse(68);
1269 lldb::pid_t pid = m_debugged_process_up->GetID();
1271 if (pid == LLDB_INVALID_PROCESS_ID)
1272 return SendErrorResponse(1);
1274 ProcessInstanceInfo proc_info;
1275 if (!Host::GetProcessInfo(pid, proc_info))
1276 return SendErrorResponse(1);
1278 StreamString response;
1279 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1280 return SendPacketNoLock(response.GetString());
1283 GDBRemoteCommunication::PacketResult
1284 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1285 // Fail if we don't have a current process.
1286 if (!m_debugged_process_up ||
1287 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1288 return SendErrorResponse(68);
1290 // Make sure we set the current thread so g and p packets return
1291 // the data the gdb will expect.
1292 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1293 SetCurrentThreadID(tid);
1295 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1297 return SendErrorResponse(69);
1299 StreamString response;
1300 response.Printf("QC%" PRIx64, thread->GetID());
1302 return SendPacketNoLock(response.GetString());
1305 GDBRemoteCommunication::PacketResult
1306 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1307 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1309 StopSTDIOForwarding();
1311 if (!m_debugged_process_up) {
1312 LLDB_LOG(log, "No debugged process found.");
1313 return PacketResult::Success;
1316 Status error = m_debugged_process_up->Kill();
1318 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1319 m_debugged_process_up->GetID(), error);
1321 // No OK response for kill packet.
1322 // return SendOKResponse ();
1323 return PacketResult::Success;
1326 GDBRemoteCommunication::PacketResult
1327 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1328 StringExtractorGDBRemote &packet) {
1329 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1330 if (packet.GetU32(0))
1331 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1333 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1334 return SendOKResponse();
1337 GDBRemoteCommunication::PacketResult
1338 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1339 StringExtractorGDBRemote &packet) {
1340 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1342 packet.GetHexByteString(path);
1343 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1344 return SendOKResponse();
1347 GDBRemoteCommunication::PacketResult
1348 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1349 StringExtractorGDBRemote &packet) {
1350 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1352 StreamString response;
1353 response.PutCStringAsRawHex8(working_dir.GetCString());
1354 return SendPacketNoLock(response.GetString());
1357 return SendErrorResponse(14);
1360 GDBRemoteCommunication::PacketResult
1361 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1362 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1364 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1366 // Ensure we have a native process.
1367 if (!m_debugged_process_up) {
1369 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1372 return SendErrorResponse(0x36);
1375 // Pull out the signal number.
1376 packet.SetFilePos(::strlen("C"));
1377 if (packet.GetBytesLeft() < 1) {
1378 // Shouldn't be using a C without a signal.
1379 return SendIllFormedResponse(packet, "C packet specified without signal.");
1381 const uint32_t signo =
1382 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1383 if (signo == std::numeric_limits<uint32_t>::max())
1384 return SendIllFormedResponse(packet, "failed to parse signal number");
1386 // Handle optional continue address.
1387 if (packet.GetBytesLeft() > 0) {
1388 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1389 if (*packet.Peek() == ';')
1390 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1392 return SendIllFormedResponse(
1393 packet, "unexpected content after $C{signal-number}");
1396 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1399 // We have two branches: what to do if a continue thread is specified (in
1400 // which case we target
1401 // sending the signal to that thread), or when we don't have a continue thread
1403 // case we send a signal to the process).
1405 // TODO discuss with Greg Clayton, make sure this makes sense.
1407 lldb::tid_t signal_tid = GetContinueThreadID();
1408 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1409 // The resume action for the continue thread (or all threads if a continue
1410 // thread is not set).
1411 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1412 static_cast<int>(signo)};
1414 // Add the action for the continue thread (or all threads when the continue
1415 // thread isn't present).
1416 resume_actions.Append(action);
1418 // Send the signal to the process since we weren't targeting a specific
1419 // continue thread with the signal.
1420 error = m_debugged_process_up->Signal(signo);
1422 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1423 m_debugged_process_up->GetID(), error);
1425 return SendErrorResponse(0x52);
1429 // Resume the threads.
1430 error = m_debugged_process_up->Resume(resume_actions);
1432 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1433 m_debugged_process_up->GetID(), error);
1435 return SendErrorResponse(0x38);
1438 // Don't send an "OK" packet; response is the stopped/exited message.
1439 return PacketResult::Success;
1442 GDBRemoteCommunication::PacketResult
1443 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1444 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1446 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1448 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1450 // For now just support all continue.
1451 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1452 if (has_continue_address) {
1453 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1455 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1458 // Ensure we have a native process.
1459 if (!m_debugged_process_up) {
1461 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1464 return SendErrorResponse(0x36);
1467 // Build the ResumeActionList
1468 ResumeActionList actions(StateType::eStateRunning, 0);
1470 Status error = m_debugged_process_up->Resume(actions);
1472 LLDB_LOG(log, "c failed for process {0}: {1}",
1473 m_debugged_process_up->GetID(), error);
1474 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1477 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1478 // No response required from continue.
1479 return PacketResult::Success;
1482 GDBRemoteCommunication::PacketResult
1483 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1484 StringExtractorGDBRemote &packet) {
1485 StreamString response;
1486 response.Printf("vCont;c;C;s;S");
1488 return SendPacketNoLock(response.GetString());
1491 GDBRemoteCommunication::PacketResult
1492 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1493 StringExtractorGDBRemote &packet) {
1494 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1496 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1499 packet.SetFilePos(::strlen("vCont"));
1501 if (packet.GetBytesLeft() == 0) {
1503 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1506 return SendIllFormedResponse(packet, "Missing action from vCont package");
1509 // Check if this is all continue (no options or ";c").
1510 if (::strcmp(packet.Peek(), ";c") == 0) {
1511 // Move past the ';', then do a simple 'c'.
1512 packet.SetFilePos(packet.GetFilePos() + 1);
1513 return Handle_c(packet);
1514 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1515 // Move past the ';', then do a simple 's'.
1516 packet.SetFilePos(packet.GetFilePos() + 1);
1517 return Handle_s(packet);
1520 // Ensure we have a native process.
1521 if (!m_debugged_process_up) {
1522 LLDB_LOG(log, "no debugged process");
1523 return SendErrorResponse(0x36);
1526 ResumeActionList thread_actions;
1528 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1529 // Skip the semi-colon.
1532 // Build up the thread action.
1533 ResumeAction thread_action;
1534 thread_action.tid = LLDB_INVALID_THREAD_ID;
1535 thread_action.state = eStateInvalid;
1536 thread_action.signal = 0;
1538 const char action = packet.GetChar();
1541 thread_action.signal = packet.GetHexMaxU32(false, 0);
1542 if (thread_action.signal == 0)
1543 return SendIllFormedResponse(
1544 packet, "Could not parse signal in vCont packet C action");
1549 thread_action.state = eStateRunning;
1553 thread_action.signal = packet.GetHexMaxU32(false, 0);
1554 if (thread_action.signal == 0)
1555 return SendIllFormedResponse(
1556 packet, "Could not parse signal in vCont packet S action");
1561 thread_action.state = eStateStepping;
1565 return SendIllFormedResponse(packet, "Unsupported vCont action");
1569 // Parse out optional :{thread-id} value.
1570 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1571 // Consume the separator.
1574 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1575 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1576 return SendIllFormedResponse(
1577 packet, "Could not parse thread number in vCont packet");
1580 thread_actions.Append(thread_action);
1583 Status error = m_debugged_process_up->Resume(thread_actions);
1585 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1586 m_debugged_process_up->GetID(), error);
1587 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1590 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1591 // No response required from vCont.
1592 return PacketResult::Success;
1595 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1596 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1597 LLDB_LOG(log, "setting current thread id to {0}", tid);
1599 m_current_tid = tid;
1600 if (m_debugged_process_up)
1601 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1604 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1605 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1606 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1608 m_continue_tid = tid;
1611 GDBRemoteCommunication::PacketResult
1612 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1613 StringExtractorGDBRemote &packet) {
1614 // Handle the $? gdbremote command.
1616 // If no process, indicate error
1617 if (!m_debugged_process_up)
1618 return SendErrorResponse(02);
1620 return SendStopReasonForState(m_debugged_process_up->GetState());
1623 GDBRemoteCommunication::PacketResult
1624 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1625 lldb::StateType process_state) {
1626 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1628 switch (process_state) {
1629 case eStateAttaching:
1630 case eStateLaunching:
1632 case eStateStepping:
1633 case eStateDetached:
1634 // NOTE: gdb protocol doc looks like it should return $OK
1635 // when everything is running (i.e. no stopped result).
1636 return PacketResult::Success; // Ignore
1638 case eStateSuspended:
1640 case eStateCrashed: {
1641 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1642 // Make sure we set the current thread so g and p packets return
1643 // the data the gdb will expect.
1644 SetCurrentThreadID(tid);
1645 return SendStopReplyPacketForThread(tid);
1649 case eStateUnloaded:
1651 return SendWResponse(m_debugged_process_up.get());
1654 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1655 m_debugged_process_up->GetID(), process_state);
1659 return SendErrorResponse(0);
1662 GDBRemoteCommunication::PacketResult
1663 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1664 StringExtractorGDBRemote &packet) {
1665 // Fail if we don't have a current process.
1666 if (!m_debugged_process_up ||
1667 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1668 return SendErrorResponse(68);
1670 // Ensure we have a thread.
1671 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1673 return SendErrorResponse(69);
1675 // Get the register context for the first thread.
1676 NativeRegisterContext ®_context = thread->GetRegisterContext();
1678 // Parse out the register number from the request.
1679 packet.SetFilePos(strlen("qRegisterInfo"));
1680 const uint32_t reg_index =
1681 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1682 if (reg_index == std::numeric_limits<uint32_t>::max())
1683 return SendErrorResponse(69);
1685 // Return the end of registers response if we've iterated one past the end of
1686 // the register set.
1687 if (reg_index >= reg_context.GetUserRegisterCount())
1688 return SendErrorResponse(69);
1690 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1692 return SendErrorResponse(69);
1694 // Build the reginfos response.
1695 StreamGDBRemote response;
1697 response.PutCString("name:");
1698 response.PutCString(reg_info->name);
1699 response.PutChar(';');
1701 if (reg_info->alt_name && reg_info->alt_name[0]) {
1702 response.PutCString("alt-name:");
1703 response.PutCString(reg_info->alt_name);
1704 response.PutChar(';');
1707 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1708 reg_info->byte_size * 8, reg_info->byte_offset);
1710 switch (reg_info->encoding) {
1712 response.PutCString("encoding:uint;");
1715 response.PutCString("encoding:sint;");
1717 case eEncodingIEEE754:
1718 response.PutCString("encoding:ieee754;");
1720 case eEncodingVector:
1721 response.PutCString("encoding:vector;");
1727 switch (reg_info->format) {
1729 response.PutCString("format:binary;");
1731 case eFormatDecimal:
1732 response.PutCString("format:decimal;");
1735 response.PutCString("format:hex;");
1738 response.PutCString("format:float;");
1740 case eFormatVectorOfSInt8:
1741 response.PutCString("format:vector-sint8;");
1743 case eFormatVectorOfUInt8:
1744 response.PutCString("format:vector-uint8;");
1746 case eFormatVectorOfSInt16:
1747 response.PutCString("format:vector-sint16;");
1749 case eFormatVectorOfUInt16:
1750 response.PutCString("format:vector-uint16;");
1752 case eFormatVectorOfSInt32:
1753 response.PutCString("format:vector-sint32;");
1755 case eFormatVectorOfUInt32:
1756 response.PutCString("format:vector-uint32;");
1758 case eFormatVectorOfFloat32:
1759 response.PutCString("format:vector-float32;");
1761 case eFormatVectorOfUInt64:
1762 response.PutCString("format:vector-uint64;");
1764 case eFormatVectorOfUInt128:
1765 response.PutCString("format:vector-uint128;");
1771 const char *const register_set_name =
1772 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1773 if (register_set_name) {
1774 response.PutCString("set:");
1775 response.PutCString(register_set_name);
1776 response.PutChar(';');
1779 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1780 LLDB_INVALID_REGNUM)
1781 response.Printf("ehframe:%" PRIu32 ";",
1782 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1784 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1785 response.Printf("dwarf:%" PRIu32 ";",
1786 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1788 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1789 case LLDB_REGNUM_GENERIC_PC:
1790 response.PutCString("generic:pc;");
1792 case LLDB_REGNUM_GENERIC_SP:
1793 response.PutCString("generic:sp;");
1795 case LLDB_REGNUM_GENERIC_FP:
1796 response.PutCString("generic:fp;");
1798 case LLDB_REGNUM_GENERIC_RA:
1799 response.PutCString("generic:ra;");
1801 case LLDB_REGNUM_GENERIC_FLAGS:
1802 response.PutCString("generic:flags;");
1804 case LLDB_REGNUM_GENERIC_ARG1:
1805 response.PutCString("generic:arg1;");
1807 case LLDB_REGNUM_GENERIC_ARG2:
1808 response.PutCString("generic:arg2;");
1810 case LLDB_REGNUM_GENERIC_ARG3:
1811 response.PutCString("generic:arg3;");
1813 case LLDB_REGNUM_GENERIC_ARG4:
1814 response.PutCString("generic:arg4;");
1816 case LLDB_REGNUM_GENERIC_ARG5:
1817 response.PutCString("generic:arg5;");
1819 case LLDB_REGNUM_GENERIC_ARG6:
1820 response.PutCString("generic:arg6;");
1822 case LLDB_REGNUM_GENERIC_ARG7:
1823 response.PutCString("generic:arg7;");
1825 case LLDB_REGNUM_GENERIC_ARG8:
1826 response.PutCString("generic:arg8;");
1832 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1833 response.PutCString("container-regs:");
1835 for (const uint32_t *reg_num = reg_info->value_regs;
1836 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1838 response.PutChar(',');
1839 response.Printf("%" PRIx32, *reg_num);
1841 response.PutChar(';');
1844 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1845 response.PutCString("invalidate-regs:");
1847 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1848 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1850 response.PutChar(',');
1851 response.Printf("%" PRIx32, *reg_num);
1853 response.PutChar(';');
1856 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1857 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1858 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1859 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1860 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1861 response.PutChar(';');
1863 return SendPacketNoLock(response.GetString());
1866 GDBRemoteCommunication::PacketResult
1867 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1868 StringExtractorGDBRemote &packet) {
1869 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1871 // Fail if we don't have a current process.
1872 if (!m_debugged_process_up ||
1873 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1874 LLDB_LOG(log, "no process ({0}), returning OK",
1875 m_debugged_process_up ? "invalid process id"
1876 : "null m_debugged_process_up");
1877 return SendOKResponse();
1880 StreamGDBRemote response;
1881 response.PutChar('m');
1883 LLDB_LOG(log, "starting thread iteration");
1884 NativeThreadProtocol *thread;
1885 uint32_t thread_index;
1886 for (thread_index = 0,
1887 thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1888 thread; ++thread_index,
1889 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1890 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1892 if (thread_index > 0)
1893 response.PutChar(',');
1894 response.Printf("%" PRIx64, thread->GetID());
1897 LLDB_LOG(log, "finished thread iteration");
1898 return SendPacketNoLock(response.GetString());
1901 GDBRemoteCommunication::PacketResult
1902 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1903 StringExtractorGDBRemote &packet) {
1904 // FIXME for now we return the full thread list in the initial packet and
1905 // always do nothing here.
1906 return SendPacketNoLock("l");
1909 GDBRemoteCommunication::PacketResult
1910 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1911 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1913 // Parse out the register number from the request.
1914 packet.SetFilePos(strlen("p"));
1915 const uint32_t reg_index =
1916 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1917 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1919 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1920 "parse register number from request \"%s\"",
1921 __FUNCTION__, packet.GetStringRef().c_str());
1922 return SendErrorResponse(0x15);
1925 // Get the thread to use.
1926 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1928 LLDB_LOG(log, "failed, no thread available");
1929 return SendErrorResponse(0x15);
1932 // Get the thread's register context.
1933 NativeRegisterContext ®_context = thread->GetRegisterContext();
1935 // Return the end of registers response if we've iterated one past the end of
1936 // the register set.
1937 if (reg_index >= reg_context.GetUserRegisterCount()) {
1939 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1940 "register %" PRIu32 " beyond register count %" PRIu32,
1941 __FUNCTION__, reg_index,
1942 reg_context.GetUserRegisterCount());
1943 return SendErrorResponse(0x15);
1946 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1949 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1950 "register %" PRIu32 " returned NULL",
1951 __FUNCTION__, reg_index);
1952 return SendErrorResponse(0x15);
1955 // Build the reginfos response.
1956 StreamGDBRemote response;
1958 // Retrieve the value
1959 RegisterValue reg_value;
1960 Status error = reg_context.ReadRegister(reg_info, reg_value);
1963 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1964 "requested register %" PRIu32 " (%s) failed: %s",
1965 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1966 return SendErrorResponse(0x15);
1969 const uint8_t *const data =
1970 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1973 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1974 "bytes from requested register %" PRIu32,
1975 __FUNCTION__, reg_index);
1976 return SendErrorResponse(0x15);
1979 // FIXME flip as needed to get data in big/little endian format for this host.
1980 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1981 response.PutHex8(data[i]);
1983 return SendPacketNoLock(response.GetString());
1986 GDBRemoteCommunication::PacketResult
1987 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1988 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1990 // Ensure there is more content.
1991 if (packet.GetBytesLeft() < 1)
1992 return SendIllFormedResponse(packet, "Empty P packet");
1994 // Parse out the register number from the request.
1995 packet.SetFilePos(strlen("P"));
1996 const uint32_t reg_index =
1997 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1998 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2000 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2001 "parse register number from request \"%s\"",
2002 __FUNCTION__, packet.GetStringRef().c_str());
2003 return SendErrorResponse(0x29);
2006 // Note debugserver would send an E30 here.
2007 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2008 return SendIllFormedResponse(
2009 packet, "P packet missing '=' char after register number");
2011 // Parse out the value.
2012 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2013 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2015 // Get the thread to use.
2016 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2019 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2020 "available (thread index 0)",
2022 return SendErrorResponse(0x28);
2025 // Get the thread's register context.
2026 NativeRegisterContext ®_context = thread->GetRegisterContext();
2027 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2030 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2031 "register %" PRIu32 " returned NULL",
2032 __FUNCTION__, reg_index);
2033 return SendErrorResponse(0x48);
2036 // Return the end of registers response if we've iterated one past the end of
2037 // the register set.
2038 if (reg_index >= reg_context.GetUserRegisterCount()) {
2040 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2041 "register %" PRIu32 " beyond register count %" PRIu32,
2042 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2043 return SendErrorResponse(0x47);
2046 // The dwarf expression are evaluate on host site
2047 // which may cause register size to change
2048 // Hence the reg_size may not be same as reg_info->bytes_size
2049 if ((reg_size != reg_info->byte_size) &&
2050 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2051 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2054 // Build the reginfos response.
2055 StreamGDBRemote response;
2057 RegisterValue reg_value(
2058 reg_bytes, reg_size,
2059 m_debugged_process_up->GetArchitecture().GetByteOrder());
2060 Status error = reg_context.WriteRegister(reg_info, reg_value);
2063 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2064 "requested register %" PRIu32 " (%s) failed: %s",
2065 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2066 return SendErrorResponse(0x32);
2069 return SendOKResponse();
2072 GDBRemoteCommunication::PacketResult
2073 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2074 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2076 // Fail if we don't have a current process.
2077 if (!m_debugged_process_up ||
2078 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2081 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2083 return SendErrorResponse(0x15);
2086 // Parse out which variant of $H is requested.
2087 packet.SetFilePos(strlen("H"));
2088 if (packet.GetBytesLeft() < 1) {
2090 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2091 "missing {g,c} variant",
2093 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2096 const char h_variant = packet.GetChar();
2097 switch (h_variant) {
2107 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2108 __FUNCTION__, h_variant);
2109 return SendIllFormedResponse(packet,
2110 "H variant unsupported, should be c or g");
2113 // Parse out the thread number.
2114 // FIXME return a parse success/fail value. All values are valid here.
2115 const lldb::tid_t tid =
2116 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2118 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2120 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2121 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2124 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2127 return SendErrorResponse(0x15);
2131 // Now switch the given thread type.
2132 switch (h_variant) {
2134 SetCurrentThreadID(tid);
2138 SetContinueThreadID(tid);
2142 assert(false && "unsupported $H variant - shouldn't get here");
2143 return SendIllFormedResponse(packet,
2144 "H variant unsupported, should be c or g");
2147 return SendOKResponse();
2150 GDBRemoteCommunication::PacketResult
2151 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2152 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2154 // Fail if we don't have a current process.
2155 if (!m_debugged_process_up ||
2156 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2159 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2161 return SendErrorResponse(0x15);
2164 packet.SetFilePos(::strlen("I"));
2167 size_t read = packet.GetHexBytesAvail(tmp);
2171 // write directly to stdin *this might block if stdin buffer is full*
2172 // TODO: enqueue this block in circular buffer and send window size to
2174 ConnectionStatus status;
2176 m_stdio_communication.Write(tmp, read, status, &error);
2178 return SendErrorResponse(0x15);
2182 return SendOKResponse();
2185 GDBRemoteCommunication::PacketResult
2186 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2187 StringExtractorGDBRemote &packet) {
2188 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2190 // Fail if we don't have a current process.
2191 if (!m_debugged_process_up ||
2192 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2193 LLDB_LOG(log, "failed, no process available");
2194 return SendErrorResponse(0x15);
2197 // Interrupt the process.
2198 Status error = m_debugged_process_up->Interrupt();
2200 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2202 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2205 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2207 // No response required from stop all.
2208 return PacketResult::Success;
2211 GDBRemoteCommunication::PacketResult
2212 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2213 StringExtractorGDBRemote &packet) {
2214 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2216 if (!m_debugged_process_up ||
2217 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2220 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2222 return SendErrorResponse(0x15);
2225 // Parse out the memory address.
2226 packet.SetFilePos(strlen("m"));
2227 if (packet.GetBytesLeft() < 1)
2228 return SendIllFormedResponse(packet, "Too short m packet");
2230 // Read the address. Punting on validation.
2231 // FIXME replace with Hex U64 read with no default value that fails on failed
2233 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2236 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2237 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2239 // Get # bytes to read.
2240 if (packet.GetBytesLeft() < 1)
2241 return SendIllFormedResponse(packet, "Length missing in m packet");
2243 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2244 if (byte_count == 0) {
2246 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2247 "zero-length packet",
2249 return SendOKResponse();
2252 // Allocate the response buffer.
2253 std::string buf(byte_count, '\0');
2255 return SendErrorResponse(0x78);
2257 // Retrieve the process memory.
2258 size_t bytes_read = 0;
2259 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2260 read_addr, &buf[0], byte_count, bytes_read);
2263 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2264 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2265 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2267 return SendErrorResponse(0x08);
2270 if (bytes_read == 0) {
2272 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2273 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2274 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2276 return SendErrorResponse(0x08);
2279 StreamGDBRemote response;
2280 packet.SetFilePos(0);
2281 char kind = packet.GetChar('?');
2283 response.PutEscapedBytes(buf.data(), byte_count);
2285 assert(kind == 'm');
2286 for (size_t i = 0; i < bytes_read; ++i)
2287 response.PutHex8(buf[i]);
2290 return SendPacketNoLock(response.GetString());
2293 GDBRemoteCommunication::PacketResult
2294 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2295 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2297 if (!m_debugged_process_up ||
2298 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2301 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2303 return SendErrorResponse(0x15);
2306 // Parse out the memory address.
2307 packet.SetFilePos(strlen("M"));
2308 if (packet.GetBytesLeft() < 1)
2309 return SendIllFormedResponse(packet, "Too short M packet");
2311 // Read the address. Punting on validation.
2312 // FIXME replace with Hex U64 read with no default value that fails on failed
2314 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2317 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2318 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2320 // Get # bytes to read.
2321 if (packet.GetBytesLeft() < 1)
2322 return SendIllFormedResponse(packet, "Length missing in M packet");
2324 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2325 if (byte_count == 0) {
2326 LLDB_LOG(log, "nothing to write: zero-length packet");
2327 return PacketResult::Success;
2331 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2332 return SendIllFormedResponse(
2333 packet, "Comma sep missing in M packet after byte length");
2335 // Allocate the conversion buffer.
2336 std::vector<uint8_t> buf(byte_count, 0);
2338 return SendErrorResponse(0x78);
2340 // Convert the hex memory write contents to bytes.
2341 StreamGDBRemote response;
2342 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2343 if (convert_count != byte_count) {
2345 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2347 m_debugged_process_up->GetID(), write_addr, byte_count,
2349 return SendIllFormedResponse(packet, "M content byte length specified did "
2350 "not match hex-encoded content "
2354 // Write the process memory.
2355 size_t bytes_written = 0;
2356 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2357 byte_count, bytes_written);
2359 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2360 m_debugged_process_up->GetID(), write_addr, error);
2361 return SendErrorResponse(0x09);
2364 if (bytes_written == 0) {
2365 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2366 m_debugged_process_up->GetID(), write_addr, byte_count);
2367 return SendErrorResponse(0x09);
2370 return SendOKResponse();
2373 GDBRemoteCommunication::PacketResult
2374 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2375 StringExtractorGDBRemote &packet) {
2376 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2378 // Currently only the NativeProcessProtocol knows if it can handle a
2379 // qMemoryRegionInfoSupported
2380 // request, but we're not guaranteed to be attached to a process. For now
2382 // client only asks this when a process is being debugged.
2384 // Ensure we have a process running; otherwise, we can't figure this out
2385 // since we won't have a NativeProcessProtocol.
2386 if (!m_debugged_process_up ||
2387 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2390 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2392 return SendErrorResponse(0x15);
2395 // Test if we can get any region back when asking for the region around NULL.
2396 MemoryRegionInfo region_info;
2397 const Status error =
2398 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2400 // We don't support memory region info collection for this
2401 // NativeProcessProtocol.
2402 return SendUnimplementedResponse("");
2405 return SendOKResponse();
2408 GDBRemoteCommunication::PacketResult
2409 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2410 StringExtractorGDBRemote &packet) {
2411 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2413 // Ensure we have a process.
2414 if (!m_debugged_process_up ||
2415 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2418 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2420 return SendErrorResponse(0x15);
2423 // Parse out the memory address.
2424 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2425 if (packet.GetBytesLeft() < 1)
2426 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2428 // Read the address. Punting on validation.
2429 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2431 StreamGDBRemote response;
2433 // Get the memory region info for the target address.
2434 MemoryRegionInfo region_info;
2435 const Status error =
2436 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2438 // Return the error message.
2440 response.PutCString("error:");
2441 response.PutCStringAsRawHex8(error.AsCString());
2442 response.PutChar(';');
2444 // Range start and size.
2445 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2446 region_info.GetRange().GetRangeBase(),
2447 region_info.GetRange().GetByteSize());
2450 if (region_info.GetReadable() || region_info.GetWritable() ||
2451 region_info.GetExecutable()) {
2452 // Write permissions info.
2453 response.PutCString("permissions:");
2455 if (region_info.GetReadable())
2456 response.PutChar('r');
2457 if (region_info.GetWritable())
2458 response.PutChar('w');
2459 if (region_info.GetExecutable())
2460 response.PutChar('x');
2462 response.PutChar(';');
2466 ConstString name = region_info.GetName();
2468 response.PutCString("name:");
2469 response.PutCStringAsRawHex8(name.AsCString());
2470 response.PutChar(';');
2474 return SendPacketNoLock(response.GetString());
2477 GDBRemoteCommunication::PacketResult
2478 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2479 // Ensure we have a process.
2480 if (!m_debugged_process_up ||
2481 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2482 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2483 LLDB_LOG(log, "failed, no process available");
2484 return SendErrorResponse(0x15);
2487 // Parse out software or hardware breakpoint or watchpoint requested.
2488 packet.SetFilePos(strlen("Z"));
2489 if (packet.GetBytesLeft() < 1)
2490 return SendIllFormedResponse(
2491 packet, "Too short Z packet, missing software/hardware specifier");
2493 bool want_breakpoint = true;
2494 bool want_hardware = false;
2495 uint32_t watch_flags = 0;
2497 const GDBStoppointType stoppoint_type =
2498 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2499 switch (stoppoint_type) {
2500 case eBreakpointSoftware:
2501 want_hardware = false;
2502 want_breakpoint = true;
2504 case eBreakpointHardware:
2505 want_hardware = true;
2506 want_breakpoint = true;
2508 case eWatchpointWrite:
2510 want_hardware = true;
2511 want_breakpoint = false;
2513 case eWatchpointRead:
2515 want_hardware = true;
2516 want_breakpoint = false;
2518 case eWatchpointReadWrite:
2520 want_hardware = true;
2521 want_breakpoint = false;
2523 case eStoppointInvalid:
2524 return SendIllFormedResponse(
2525 packet, "Z packet had invalid software/hardware specifier");
2528 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2529 return SendIllFormedResponse(
2530 packet, "Malformed Z packet, expecting comma after stoppoint type");
2532 // Parse out the stoppoint address.
2533 if (packet.GetBytesLeft() < 1)
2534 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2535 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2537 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2538 return SendIllFormedResponse(
2539 packet, "Malformed Z packet, expecting comma after address");
2541 // Parse out the stoppoint size (i.e. size hint for opcode size).
2542 const uint32_t size =
2543 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2544 if (size == std::numeric_limits<uint32_t>::max())
2545 return SendIllFormedResponse(
2546 packet, "Malformed Z packet, failed to parse size argument");
2548 if (want_breakpoint) {
2549 // Try to set the breakpoint.
2550 const Status error =
2551 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2552 if (error.Success())
2553 return SendOKResponse();
2554 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2555 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2556 m_debugged_process_up->GetID(), error);
2557 return SendErrorResponse(0x09);
2559 // Try to set the watchpoint.
2560 const Status error = m_debugged_process_up->SetWatchpoint(
2561 addr, size, watch_flags, want_hardware);
2562 if (error.Success())
2563 return SendOKResponse();
2564 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2565 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2566 m_debugged_process_up->GetID(), error);
2567 return SendErrorResponse(0x09);
2571 GDBRemoteCommunication::PacketResult
2572 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2573 // Ensure we have a process.
2574 if (!m_debugged_process_up ||
2575 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2576 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2577 LLDB_LOG(log, "failed, no process available");
2578 return SendErrorResponse(0x15);
2581 // Parse out software or hardware breakpoint or watchpoint requested.
2582 packet.SetFilePos(strlen("z"));
2583 if (packet.GetBytesLeft() < 1)
2584 return SendIllFormedResponse(
2585 packet, "Too short z packet, missing software/hardware specifier");
2587 bool want_breakpoint = true;
2588 bool want_hardware = false;
2590 const GDBStoppointType stoppoint_type =
2591 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2592 switch (stoppoint_type) {
2593 case eBreakpointHardware:
2594 want_breakpoint = true;
2595 want_hardware = true;
2597 case eBreakpointSoftware:
2598 want_breakpoint = true;
2600 case eWatchpointWrite:
2601 want_breakpoint = false;
2603 case eWatchpointRead:
2604 want_breakpoint = false;
2606 case eWatchpointReadWrite:
2607 want_breakpoint = false;
2610 return SendIllFormedResponse(
2611 packet, "z packet had invalid software/hardware specifier");
2614 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2615 return SendIllFormedResponse(
2616 packet, "Malformed z packet, expecting comma after stoppoint type");
2618 // Parse out the stoppoint address.
2619 if (packet.GetBytesLeft() < 1)
2620 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2621 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2623 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2624 return SendIllFormedResponse(
2625 packet, "Malformed z packet, expecting comma after address");
2628 // Parse out the stoppoint size (i.e. size hint for opcode size).
2629 const uint32_t size = packet.GetHexMaxU32 (false,
2630 std::numeric_limits<uint32_t>::max ());
2631 if (size == std::numeric_limits<uint32_t>::max ())
2632 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2636 if (want_breakpoint) {
2637 // Try to clear the breakpoint.
2638 const Status error =
2639 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2640 if (error.Success())
2641 return SendOKResponse();
2642 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2643 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2644 m_debugged_process_up->GetID(), error);
2645 return SendErrorResponse(0x09);
2647 // Try to clear the watchpoint.
2648 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2649 if (error.Success())
2650 return SendOKResponse();
2651 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2652 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2653 m_debugged_process_up->GetID(), error);
2654 return SendErrorResponse(0x09);
2658 GDBRemoteCommunication::PacketResult
2659 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2660 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2662 // Ensure we have a process.
2663 if (!m_debugged_process_up ||
2664 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2667 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2669 return SendErrorResponse(0x32);
2672 // We first try to use a continue thread id. If any one or any all set, use
2673 // the current thread.
2674 // Bail out if we don't have a thread id.
2675 lldb::tid_t tid = GetContinueThreadID();
2676 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2677 tid = GetCurrentThreadID();
2678 if (tid == LLDB_INVALID_THREAD_ID)
2679 return SendErrorResponse(0x33);
2681 // Double check that we have such a thread.
2682 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2683 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2685 return SendErrorResponse(0x33);
2687 // Create the step action for the given thread.
2688 ResumeAction action = {tid, eStateStepping, 0};
2690 // Setup the actions list.
2691 ResumeActionList actions;
2692 actions.Append(action);
2694 // All other threads stop while we're single stepping a thread.
2695 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2696 Status error = m_debugged_process_up->Resume(actions);
2699 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2700 " tid %" PRIu64 " Resume() failed with error: %s",
2701 __FUNCTION__, m_debugged_process_up->GetID(), tid,
2703 return SendErrorResponse(0x49);
2706 // No response here - the stop or exit will come from the resulting action.
2707 return PacketResult::Success;
2710 GDBRemoteCommunication::PacketResult
2711 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2712 StringExtractorGDBRemote &packet) {
2713 // *BSD impls should be able to do this too.
2714 #if defined(__linux__) || defined(__NetBSD__)
2715 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2717 // Parse out the offset.
2718 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2719 if (packet.GetBytesLeft() < 1)
2720 return SendIllFormedResponse(packet,
2721 "qXfer:auxv:read:: packet missing offset");
2723 const uint64_t auxv_offset =
2724 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2725 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2726 return SendIllFormedResponse(packet,
2727 "qXfer:auxv:read:: packet missing offset");
2730 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2731 return SendIllFormedResponse(
2732 packet, "qXfer:auxv:read:: packet missing comma after offset");
2734 // Parse out the length.
2735 const uint64_t auxv_length =
2736 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2737 if (auxv_length == std::numeric_limits<uint64_t>::max())
2738 return SendIllFormedResponse(packet,
2739 "qXfer:auxv:read:: packet missing length");
2741 // Grab the auxv data if we need it.
2742 if (!m_active_auxv_buffer_up) {
2743 // Make sure we have a valid process.
2744 if (!m_debugged_process_up ||
2745 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2748 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2750 return SendErrorResponse(0x10);
2753 // Grab the auxv data.
2754 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2755 if (!buffer_or_error) {
2756 std::error_code ec = buffer_or_error.getError();
2757 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2758 return SendErrorResponse(ec.value());
2760 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2763 StreamGDBRemote response;
2764 bool done_with_buffer = false;
2766 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2767 if (auxv_offset >= buffer.size()) {
2768 // We have nothing left to send. Mark the buffer as complete.
2769 response.PutChar('l');
2770 done_with_buffer = true;
2772 // Figure out how many bytes are available starting at the given offset.
2773 buffer = buffer.drop_front(auxv_offset);
2775 // Mark the response type according to whether we're reading the remainder
2776 // of the auxv data.
2777 if (auxv_length >= buffer.size()) {
2778 // There will be nothing left to read after this
2779 response.PutChar('l');
2780 done_with_buffer = true;
2782 // There will still be bytes to read after this request.
2783 response.PutChar('m');
2784 buffer = buffer.take_front(auxv_length);
2787 // Now write the data in encoded binary form.
2788 response.PutEscapedBytes(buffer.data(), buffer.size());
2791 if (done_with_buffer)
2792 m_active_auxv_buffer_up.reset();
2794 return SendPacketNoLock(response.GetString());
2796 return SendUnimplementedResponse("not implemented on this platform");
2800 GDBRemoteCommunication::PacketResult
2801 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2802 StringExtractorGDBRemote &packet) {
2803 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2805 // Move past packet name.
2806 packet.SetFilePos(strlen("QSaveRegisterState"));
2808 // Get the thread to use.
2809 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2811 if (m_thread_suffix_supported)
2812 return SendIllFormedResponse(
2813 packet, "No thread specified in QSaveRegisterState packet");
2815 return SendIllFormedResponse(packet,
2816 "No thread was is set with the Hg packet");
2819 // Grab the register context for the thread.
2820 NativeRegisterContext& reg_context = thread->GetRegisterContext();
2822 // Save registers to a buffer.
2823 DataBufferSP register_data_sp;
2824 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2826 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2827 m_debugged_process_up->GetID(), error);
2828 return SendErrorResponse(0x75);
2831 // Allocate a new save id.
2832 const uint32_t save_id = GetNextSavedRegistersID();
2833 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2834 "GetNextRegisterSaveID() returned an existing register save id");
2836 // Save the register data buffer under the save id.
2838 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2839 m_saved_registers_map[save_id] = register_data_sp;
2842 // Write the response.
2843 StreamGDBRemote response;
2844 response.Printf("%" PRIu32, save_id);
2845 return SendPacketNoLock(response.GetString());
2848 GDBRemoteCommunication::PacketResult
2849 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2850 StringExtractorGDBRemote &packet) {
2851 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2853 // Parse out save id.
2854 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2855 if (packet.GetBytesLeft() < 1)
2856 return SendIllFormedResponse(
2857 packet, "QRestoreRegisterState packet missing register save id");
2859 const uint32_t save_id = packet.GetU32(0);
2861 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2862 "expecting decimal uint32_t");
2863 return SendErrorResponse(0x76);
2866 // Get the thread to use.
2867 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2869 if (m_thread_suffix_supported)
2870 return SendIllFormedResponse(
2871 packet, "No thread specified in QRestoreRegisterState packet");
2873 return SendIllFormedResponse(packet,
2874 "No thread was is set with the Hg packet");
2877 // Grab the register context for the thread.
2878 NativeRegisterContext ®_context = thread->GetRegisterContext();
2880 // Retrieve register state buffer, then remove from the list.
2881 DataBufferSP register_data_sp;
2883 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2885 // Find the register set buffer for the given save id.
2886 auto it = m_saved_registers_map.find(save_id);
2887 if (it == m_saved_registers_map.end()) {
2889 "pid {0} does not have a register set save buffer for id {1}",
2890 m_debugged_process_up->GetID(), save_id);
2891 return SendErrorResponse(0x77);
2893 register_data_sp = it->second;
2895 // Remove it from the map.
2896 m_saved_registers_map.erase(it);
2899 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
2901 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2902 m_debugged_process_up->GetID(), error);
2903 return SendErrorResponse(0x77);
2906 return SendOKResponse();
2909 GDBRemoteCommunication::PacketResult
2910 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2911 StringExtractorGDBRemote &packet) {
2912 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2914 // Consume the ';' after vAttach.
2915 packet.SetFilePos(strlen("vAttach"));
2916 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2917 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2919 // Grab the PID to which we will attach (assume hex encoding).
2920 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2921 if (pid == LLDB_INVALID_PROCESS_ID)
2922 return SendIllFormedResponse(packet,
2923 "vAttach failed to parse the process id");
2925 // Attempt to attach.
2927 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2931 Status error = AttachToProcess(pid);
2935 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2936 "pid %" PRIu64 ": %s\n",
2937 __FUNCTION__, pid, error.AsCString());
2938 return SendErrorResponse(0x01);
2941 // Notify we attached by sending a stop packet.
2942 return SendStopReasonForState(m_debugged_process_up->GetState());
2945 GDBRemoteCommunication::PacketResult
2946 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2947 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2949 StopSTDIOForwarding();
2951 // Fail if we don't have a current process.
2952 if (!m_debugged_process_up ||
2953 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2956 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2958 return SendErrorResponse(0x15);
2961 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2963 // Consume the ';' after D.
2964 packet.SetFilePos(1);
2965 if (packet.GetBytesLeft()) {
2966 if (packet.GetChar() != ';')
2967 return SendIllFormedResponse(packet, "D missing expected ';'");
2969 // Grab the PID from which we will detach (assume hex encoding).
2970 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2971 if (pid == LLDB_INVALID_PROCESS_ID)
2972 return SendIllFormedResponse(packet, "D failed to parse the process id");
2975 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
2976 return SendIllFormedResponse(packet, "Invalid pid");
2979 const Status error = m_debugged_process_up->Detach();
2982 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2983 "pid %" PRIu64 ": %s\n",
2984 __FUNCTION__, m_debugged_process_up->GetID(),
2986 return SendErrorResponse(0x01);
2989 return SendOKResponse();
2992 GDBRemoteCommunication::PacketResult
2993 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2994 StringExtractorGDBRemote &packet) {
2995 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2997 packet.SetFilePos(strlen("qThreadStopInfo"));
2998 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2999 if (tid == LLDB_INVALID_THREAD_ID) {
3001 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3002 "parse thread id from request \"%s\"",
3003 __FUNCTION__, packet.GetStringRef().c_str());
3004 return SendErrorResponse(0x15);
3006 return SendStopReplyPacketForThread(tid);
3009 GDBRemoteCommunication::PacketResult
3010 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3011 StringExtractorGDBRemote &) {
3012 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3014 // Ensure we have a debugged process.
3015 if (!m_debugged_process_up ||
3016 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3017 return SendErrorResponse(50);
3018 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3020 StreamString response;
3021 const bool threads_with_valid_stop_info_only = false;
3022 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3023 *m_debugged_process_up, threads_with_valid_stop_info_only);
3024 if (!threads_array_sp) {
3025 LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3026 m_debugged_process_up->GetID());
3027 return SendErrorResponse(52);
3030 threads_array_sp->Write(response);
3031 StreamGDBRemote escaped_response;
3032 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3033 return SendPacketNoLock(escaped_response.GetString());
3036 GDBRemoteCommunication::PacketResult
3037 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3038 StringExtractorGDBRemote &packet) {
3039 // Fail if we don't have a current process.
3040 if (!m_debugged_process_up ||
3041 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3042 return SendErrorResponse(68);
3044 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3045 if (packet.GetBytesLeft() == 0)
3046 return SendOKResponse();
3047 if (packet.GetChar() != ':')
3048 return SendErrorResponse(67);
3050 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3052 StreamGDBRemote response;
3053 if (hw_debug_cap == llvm::None)
3054 response.Printf("num:0;");
3056 response.Printf("num:%d;", hw_debug_cap->second);
3058 return SendPacketNoLock(response.GetString());
3061 GDBRemoteCommunication::PacketResult
3062 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3063 StringExtractorGDBRemote &packet) {
3064 // Fail if we don't have a current process.
3065 if (!m_debugged_process_up ||
3066 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3067 return SendErrorResponse(67);
3069 packet.SetFilePos(strlen("qFileLoadAddress:"));
3070 if (packet.GetBytesLeft() == 0)
3071 return SendErrorResponse(68);
3073 std::string file_name;
3074 packet.GetHexByteString(file_name);
3076 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3078 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3080 return SendErrorResponse(69);
3082 if (file_load_address == LLDB_INVALID_ADDRESS)
3083 return SendErrorResponse(1); // File not loaded
3085 StreamGDBRemote response;
3086 response.PutHex64(file_load_address);
3087 return SendPacketNoLock(response.GetString());
3090 GDBRemoteCommunication::PacketResult
3091 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3092 StringExtractorGDBRemote &packet) {
3093 std::vector<int> signals;
3094 packet.SetFilePos(strlen("QPassSignals:"));
3096 // Read sequence of hex signal numbers divided by a semicolon and
3097 // optionally spaces.
3098 while (packet.GetBytesLeft() > 0) {
3099 int signal = packet.GetS32(-1, 16);
3101 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3102 signals.push_back(signal);
3104 packet.SkipSpaces();
3105 char separator = packet.GetChar();
3106 if (separator == '\0')
3107 break; // End of string
3108 if (separator != ';')
3109 return SendIllFormedResponse(packet, "Invalid separator,"
3110 " expected semicolon.");
3113 // Fail if we don't have a current process.
3114 if (!m_debugged_process_up)
3115 return SendErrorResponse(68);
3117 Status error = m_debugged_process_up->IgnoreSignals(signals);
3119 return SendErrorResponse(69);
3121 return SendOKResponse();
3124 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3125 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3127 // Tell the stdio connection to shut down.
3128 if (m_stdio_communication.IsConnected()) {
3129 auto connection = m_stdio_communication.GetConnection();
3132 connection->Disconnect(&error);
3134 if (error.Success()) {
3136 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3137 "terminal stdio - SUCCESS",
3141 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3142 "terminal stdio - FAIL: %s",
3143 __FUNCTION__, error.AsCString());
3149 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3150 StringExtractorGDBRemote &packet) {
3151 // We have no thread if we don't have a process.
3152 if (!m_debugged_process_up ||
3153 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3156 // If the client hasn't asked for thread suffix support, there will not be a
3158 // Use the current thread in that case.
3159 if (!m_thread_suffix_supported) {
3160 const lldb::tid_t current_tid = GetCurrentThreadID();
3161 if (current_tid == LLDB_INVALID_THREAD_ID)
3163 else if (current_tid == 0) {
3165 return m_debugged_process_up->GetThreadAtIndex(0);
3167 return m_debugged_process_up->GetThreadByID(current_tid);
3170 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3172 // Parse out the ';'.
3173 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3175 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3176 "error: expected ';' prior to start of thread suffix: packet "
3178 __FUNCTION__, packet.GetStringRef().c_str());
3182 if (!packet.GetBytesLeft())
3185 // Parse out thread: portion.
3186 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3188 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3189 "error: expected 'thread:' but not found, packet contents = "
3191 __FUNCTION__, packet.GetStringRef().c_str());
3194 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3195 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3197 return m_debugged_process_up->GetThreadByID(tid);
3202 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3203 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3204 // Use whatever the debug process says is the current thread id
3205 // since the protocol either didn't specify or specified we want
3206 // any/all threads marked as the current thread.
3207 if (!m_debugged_process_up)
3208 return LLDB_INVALID_THREAD_ID;
3209 return m_debugged_process_up->GetCurrentThreadID();
3211 // Use the specific current thread id set by the gdb remote protocol.
3212 return m_current_tid;
3215 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3216 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3217 return m_next_saved_registers_id++;
3220 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3221 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3223 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3224 m_active_auxv_buffer_up.reset();
3228 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3229 const ArchSpec &arch) {
3230 if (m_debugged_process_up) {
3232 if (m_debugged_process_up
3233 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3235 if (file_spec.Exists())
3240 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);