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/Target/FileAction.h"
37 #include "lldb/Target/MemoryRegionInfo.h"
38 #include "lldb/Utility/Args.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 "lldb/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 as
240 // needed. llgs local-process debugging may specify PTY paths, which will
241 // make these file actions non-null process launch -i/e/o will also make
242 // these file actions non-null nullptr means that the traffic is expected to
243 // flow over gdb-remote protocol
244 if (should_forward_stdio) {
245 // nullptr means it's not redirected to file or pty (in case of LLGS local)
246 // at least one of stdio will be transferred pty<->gdb-remote we need to
247 // give the pty master handle to this object to read and/or write
249 "pid = {0}: setting up stdout/stderr redirection via $O "
250 "gdb-remote commands",
251 m_debugged_process_up->GetID());
253 // Setup stdout/stderr mapping from inferior to $O
254 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
255 if (terminal_fd >= 0) {
257 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
258 "inferior STDIO fd to %d",
259 __FUNCTION__, terminal_fd);
260 Status status = SetSTDIOFileDescriptor(terminal_fd);
265 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
266 "inferior STDIO since terminal fd reported as %d",
267 __FUNCTION__, terminal_fd);
271 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
272 "will communicate over client-provided file descriptors",
273 m_debugged_process_up->GetID());
276 printf("Launched '%s' as process %" PRIu64 "...\n",
277 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
278 m_debugged_process_up->GetID());
283 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
284 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
286 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
289 // Before we try to attach, make sure we aren't already monitoring something
291 if (m_debugged_process_up &&
292 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
293 return Status("cannot attach to process %" PRIu64
294 " when another process with pid %" PRIu64
295 " is being debugged.",
296 pid, m_debugged_process_up->GetID());
299 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
301 Status status(process_or.takeError());
302 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
306 m_debugged_process_up = std::move(*process_or);
308 // Setup stdout/stderr mapping from inferior.
309 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
310 if (terminal_fd >= 0) {
312 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
313 "inferior STDIO fd to %d",
314 __FUNCTION__, terminal_fd);
315 Status status = SetSTDIOFileDescriptor(terminal_fd);
320 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
321 "inferior STDIO since terminal fd reported as %d",
322 __FUNCTION__, terminal_fd);
325 printf("Attached to process %" PRIu64 "...\n", pid);
329 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
330 NativeProcessProtocol *process) {
331 assert(process && "process cannot be NULL");
332 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
334 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
335 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
336 __FUNCTION__, process->GetID(),
337 StateAsCString(process->GetState()));
341 GDBRemoteCommunication::PacketResult
342 GDBRemoteCommunicationServerLLGS::SendWResponse(
343 NativeProcessProtocol *process) {
344 assert(process && "process cannot be NULL");
345 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
347 // send W notification
348 auto wait_status = process->GetExitStatus();
350 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
353 StreamGDBRemote response;
354 response.PutChar('E');
355 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
356 return SendPacketNoLock(response.GetString());
359 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
362 StreamGDBRemote response;
363 response.Format("{0:g}", *wait_status);
364 return SendPacketNoLock(response.GetString());
367 static void AppendHexValue(StreamString &response, const uint8_t *buf,
368 uint32_t buf_size, bool swap) {
371 for (i = buf_size - 1; i >= 0; i--)
372 response.PutHex8(buf[i]);
374 for (i = 0; i < buf_size; i++)
375 response.PutHex8(buf[i]);
379 static void WriteRegisterValueInHexFixedWidth(
380 StreamString &response, NativeRegisterContext ®_ctx,
381 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
382 lldb::ByteOrder byte_order) {
383 RegisterValue reg_value;
385 Status error = reg_ctx.ReadRegister(®_info, reg_value);
387 reg_value_p = ®_value;
392 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
393 reg_value_p->GetByteSize(),
394 byte_order == lldb::eByteOrderLittle);
396 // Zero-out any unreadable values.
397 if (reg_info.byte_size > 0) {
398 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
399 AppendHexValue(response, zeros.data(), zeros.size(), false);
404 static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
405 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
407 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
409 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
411 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
412 // Expedite all registers in the first register set (i.e. should be GPRs)
413 // that are not contained in other registers.
414 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
417 for (const uint32_t *reg_num_p = reg_set_p->registers;
418 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
419 uint32_t reg_num = *reg_num_p;
421 // Expedite only a couple of registers until we figure out why sending
422 // registers is expensive.
423 static const uint32_t k_expedited_registers[] = {
424 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
425 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
427 for (const uint32_t *generic_reg_p = k_expedited_registers;
428 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
429 uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
430 eRegisterKindGeneric, *generic_reg_p);
431 if (reg_num == LLDB_INVALID_REGNUM)
432 continue; // Target does not support the given register.
435 const RegisterInfo *const reg_info_p =
436 reg_ctx.GetRegisterInfoAtIndex(reg_num);
437 if (reg_info_p == nullptr) {
440 "%s failed to get register info for register index %" PRIu32,
441 __FUNCTION__, reg_num);
445 if (reg_info_p->value_regs != nullptr)
446 continue; // Only expedite registers that are not contained in other
449 RegisterValue reg_value;
450 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
453 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
455 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
456 reg_num, error.AsCString());
461 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
462 ®_value, lldb::eByteOrderBig);
464 register_object_sp->SetObject(
465 llvm::to_string(reg_num),
466 std::make_shared<JSONString>(stream.GetString()));
469 return register_object_sp;
472 static const char *GetStopReasonString(StopReason stop_reason) {
473 switch (stop_reason) {
474 case eStopReasonTrace:
476 case eStopReasonBreakpoint:
478 case eStopReasonWatchpoint:
480 case eStopReasonSignal:
482 case eStopReasonException:
484 case eStopReasonExec:
486 case eStopReasonInstrumentation:
487 case eStopReasonInvalid:
488 case eStopReasonPlanComplete:
489 case eStopReasonThreadExiting:
490 case eStopReasonNone:
496 static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
498 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
500 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
502 // Ensure we can get info on the given thread.
503 uint32_t thread_idx = 0;
504 for (NativeThreadProtocol *thread;
505 (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
508 lldb::tid_t tid = thread->GetID();
510 // Grab the reason this thread stopped.
511 struct ThreadStopInfo tid_stop_info;
512 std::string description;
513 if (!thread->GetStopReason(tid_stop_info, description))
516 const int signum = tid_stop_info.details.signal.signo;
518 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
520 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
521 __FUNCTION__, process.GetID(), tid, signum,
522 tid_stop_info.reason, tid_stop_info.details.exception.type);
525 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
526 threads_array_sp->AppendObject(thread_obj_sp);
529 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread))
530 thread_obj_sp->SetObject("registers", registers_sp);
533 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
535 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
537 const std::string thread_name = thread->GetName();
538 if (!thread_name.empty())
539 thread_obj_sp->SetObject("name",
540 std::make_shared<JSONString>(thread_name));
542 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
543 thread_obj_sp->SetObject("reason",
544 std::make_shared<JSONString>(stop_reason_str));
546 if (!description.empty())
547 thread_obj_sp->SetObject("description",
548 std::make_shared<JSONString>(description));
550 if ((tid_stop_info.reason == eStopReasonException) &&
551 tid_stop_info.details.exception.type) {
552 thread_obj_sp->SetObject(
554 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
556 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
557 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
559 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
560 tid_stop_info.details.exception.data[i]));
562 thread_obj_sp->SetObject("medata", medata_array_sp);
565 // TODO: Expedite interesting regions of inferior memory
568 return threads_array_sp;
571 GDBRemoteCommunication::PacketResult
572 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
574 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
576 // Ensure we have a debugged process.
577 if (!m_debugged_process_up ||
578 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
579 return SendErrorResponse(50);
581 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
582 m_debugged_process_up->GetID(), tid);
584 // Ensure we can get info on the given thread.
585 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
587 return SendErrorResponse(51);
589 // Grab the reason this thread stopped.
590 struct ThreadStopInfo tid_stop_info;
591 std::string description;
592 if (!thread->GetStopReason(tid_stop_info, description))
593 return SendErrorResponse(52);
595 // FIXME implement register handling for exec'd inferiors.
596 // if (tid_stop_info.reason == eStopReasonExec) {
597 // const bool force = true;
598 // InitializeRegisters(force);
601 StreamString response;
602 // Output the T packet with the thread
603 response.PutChar('T');
604 int signum = tid_stop_info.details.signal.signo;
607 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
608 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
609 tid_stop_info.details.exception.type);
611 // Print the signal number.
612 response.PutHex8(signum & 0xff);
615 response.Printf("thread:%" PRIx64 ";", tid);
617 // Include the thread name if there is one.
618 const std::string thread_name = thread->GetName();
619 if (!thread_name.empty()) {
620 size_t thread_name_len = thread_name.length();
622 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
623 response.PutCString("name:");
624 response.PutCString(thread_name);
626 // The thread name contains special chars, send as hex bytes.
627 response.PutCString("hexname:");
628 response.PutCStringAsRawHex8(thread_name.c_str());
630 response.PutChar(';');
633 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
634 // send all thread IDs back in the "threads" key whose value is a list of hex
635 // thread IDs separated by commas:
636 // "threads:10a,10b,10c;"
637 // This will save the debugger from having to send a pair of qfThreadInfo and
638 // qsThreadInfo packets, but it also might take a lot of room in the stop
639 // reply packet, so it must be enabled only on systems where there are no
640 // limits on packet lengths.
641 if (m_list_threads_in_stop_reply) {
642 response.PutCString("threads:");
644 uint32_t thread_index = 0;
645 NativeThreadProtocol *listed_thread;
646 for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
647 listed_thread; ++thread_index,
648 listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
649 if (thread_index > 0)
650 response.PutChar(',');
651 response.Printf("%" PRIx64, listed_thread->GetID());
653 response.PutChar(';');
655 // Include JSON info that describes the stop reason for any threads that
656 // actually have stop reasons. We use the new "jstopinfo" key whose values
657 // is hex ascii JSON that contains the thread IDs thread stop info only for
658 // threads that have stop reasons. Only send this if we have more than one
659 // thread otherwise this packet has all the info it needs.
660 if (thread_index > 0) {
661 const bool threads_with_valid_stop_info_only = true;
662 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
663 *m_debugged_process_up, threads_with_valid_stop_info_only);
664 if (threads_info_sp) {
665 response.PutCString("jstopinfo:");
666 StreamString unescaped_response;
667 threads_info_sp->Write(unescaped_response);
668 response.PutCStringAsRawHex8(unescaped_response.GetData());
669 response.PutChar(';');
671 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
672 m_debugged_process_up->GetID());
676 response.PutCString("thread-pcs");
677 char delimiter = ':';
678 for (NativeThreadProtocol *thread;
679 (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
681 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
683 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
684 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
685 const RegisterInfo *const reg_info_p =
686 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
688 RegisterValue reg_value;
689 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
692 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
694 reg_info_p->name ? reg_info_p->name
695 : "<unnamed-register>",
696 reg_to_read, error.AsCString());
700 response.PutChar(delimiter);
702 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
703 ®_value, endian::InlHostByteOrder());
706 response.PutChar(';');
710 // Expedite registers.
713 // Grab the register context.
714 NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
715 // Expedite all registers in the first register set (i.e. should be GPRs)
716 // that are not contained in other registers.
717 const RegisterSet *reg_set_p;
718 if (reg_ctx.GetRegisterSetCount() > 0 &&
719 ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
721 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
722 "from set '%s' (registers set count: %zu)",
724 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
725 reg_set_p->num_registers);
727 for (const uint32_t *reg_num_p = reg_set_p->registers;
728 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
729 const RegisterInfo *const reg_info_p =
730 reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
731 if (reg_info_p == nullptr) {
733 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
734 "register info for register set '%s', register index "
737 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
739 } else if (reg_info_p->value_regs == nullptr) {
740 // Only expediate registers that are not contained in other registers.
741 RegisterValue reg_value;
742 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
743 if (error.Success()) {
744 response.Printf("%.02x:", *reg_num_p);
745 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
746 ®_value, lldb::eByteOrderBig);
747 response.PutChar(';');
750 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
751 "register '%s' index %" PRIu32 ": %s",
753 reg_info_p->name ? reg_info_p->name
754 : "<unnamed-register>",
755 *reg_num_p, error.AsCString());
761 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
762 if (reason_str != nullptr) {
763 response.Printf("reason:%s;", reason_str);
766 if (!description.empty()) {
767 // Description may contains special chars, send as hex bytes.
768 response.PutCString("description:");
769 response.PutCStringAsRawHex8(description.c_str());
770 response.PutChar(';');
771 } else if ((tid_stop_info.reason == eStopReasonException) &&
772 tid_stop_info.details.exception.type) {
773 response.PutCString("metype:");
774 response.PutHex64(tid_stop_info.details.exception.type);
775 response.PutCString(";mecount:");
776 response.PutHex32(tid_stop_info.details.exception.data_count);
777 response.PutChar(';');
779 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
780 response.PutCString("medata:");
781 response.PutHex64(tid_stop_info.details.exception.data[i]);
782 response.PutChar(';');
786 return SendPacketNoLock(response.GetString());
789 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
790 NativeProcessProtocol *process) {
791 assert(process && "process cannot be NULL");
793 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
795 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
797 PacketResult result = SendStopReasonForState(StateType::eStateExited);
798 if (result != PacketResult::Success) {
800 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
801 "notification for PID %" PRIu64 ", state: eStateExited",
802 __FUNCTION__, process->GetID());
805 // Close the pipe to the inferior terminal i/o if we launched it and set one
807 MaybeCloseInferiorTerminalConnection();
809 // We are ready to exit the debug monitor.
811 m_mainloop.RequestTermination();
814 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
815 NativeProcessProtocol *process) {
816 assert(process && "process cannot be NULL");
818 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
820 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
822 // Send the stop reason unless this is the stop after the launch or attach.
823 switch (m_inferior_prev_state) {
824 case eStateLaunching:
825 case eStateAttaching:
826 // Don't send anything per debugserver behavior.
829 // In all other cases, send the stop reason.
830 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
831 if (result != PacketResult::Success) {
833 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
834 "notification for PID %" PRIu64 ", state: eStateExited",
835 __FUNCTION__, process->GetID());
841 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
842 NativeProcessProtocol *process, lldb::StateType state) {
843 assert(process && "process cannot be NULL");
844 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
846 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
847 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
848 __FUNCTION__, process->GetID(), StateAsCString(state));
852 case StateType::eStateRunning:
853 StartSTDIOForwarding();
856 case StateType::eStateStopped:
857 // Make sure we get all of the pending stdout/stderr from the inferior and
858 // send it to the lldb host before we send the state change notification
860 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
861 // does not interfere with our protocol.
862 StopSTDIOForwarding();
863 HandleInferiorState_Stopped(process);
866 case StateType::eStateExited:
869 StopSTDIOForwarding();
870 HandleInferiorState_Exited(process);
875 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
876 "change for pid %" PRIu64 ", new state: %s",
877 __FUNCTION__, process->GetID(), StateAsCString(state));
882 // Remember the previous state reported to us.
883 m_inferior_prev_state = state;
886 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
887 ClearProcessSpecificData();
890 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
891 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
893 if (!m_handshake_completed) {
894 if (!HandshakeWithClient()) {
896 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
897 "client failed, exiting",
899 m_mainloop.RequestTermination();
902 m_handshake_completed = true;
905 bool interrupt = false;
909 const PacketResult result = GetPacketAndSendResponse(
910 std::chrono::microseconds(0), error, interrupt, done);
911 if (result == PacketResult::ErrorReplyTimeout)
912 break; // No more packets in the queue
914 if ((result != PacketResult::Success)) {
916 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
918 __FUNCTION__, error.AsCString());
919 m_mainloop.RequestTermination();
925 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
926 std::unique_ptr<Connection> &&connection) {
927 IOObjectSP read_object_sp = connection->GetReadObject();
928 GDBRemoteCommunicationServer::SetConnection(connection.release());
931 m_network_handle_up = m_mainloop.RegisterReadObject(
932 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
937 GDBRemoteCommunication::PacketResult
938 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
940 if ((buffer == nullptr) || (len == 0)) {
942 return PacketResult::Success;
945 StreamString response;
946 response.PutChar('O');
947 response.PutBytesAsRawHex8(buffer, len);
949 return SendPacketNoLock(response.GetString());
952 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
955 // Set up the reading/handling of process I/O
956 std::unique_ptr<ConnectionFileDescriptor> conn_up(
957 new ConnectionFileDescriptor(fd, true));
959 error.SetErrorString("failed to create ConnectionFileDescriptor");
963 m_stdio_communication.SetCloseOnEOF(false);
964 m_stdio_communication.SetConnection(conn_up.release());
965 if (!m_stdio_communication.IsConnected()) {
966 error.SetErrorString(
967 "failed to set connection for inferior I/O communication");
974 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
975 // Don't forward if not connected (e.g. when attaching).
976 if (!m_stdio_communication.IsConnected())
980 lldbassert(!m_stdio_handle_up);
981 m_stdio_handle_up = m_mainloop.RegisterReadObject(
982 m_stdio_communication.GetConnection()->GetReadObject(),
983 [this](MainLoopBase &) { SendProcessOutput(); }, error);
985 if (!m_stdio_handle_up) {
986 // Not much we can do about the failure. Log it and continue without
988 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
989 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
991 __FUNCTION__, error.AsCString());
995 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
996 m_stdio_handle_up.reset();
999 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1001 ConnectionStatus status;
1004 size_t bytes_read = m_stdio_communication.Read(
1005 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1007 case eConnectionStatusSuccess:
1008 SendONotification(buffer, bytes_read);
1010 case eConnectionStatusLostConnection:
1011 case eConnectionStatusEndOfFile:
1012 case eConnectionStatusError:
1013 case eConnectionStatusNoConnection:
1014 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1015 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1016 "forwarding as communication returned status %d (error: "
1018 __FUNCTION__, status, error.AsCString());
1019 m_stdio_handle_up.reset();
1022 case eConnectionStatusInterrupted:
1023 case eConnectionStatusTimedOut:
1029 GDBRemoteCommunication::PacketResult
1030 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1031 StringExtractorGDBRemote &packet) {
1032 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1033 // Fail if we don't have a current process.
1034 if (!m_debugged_process_up ||
1035 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1036 return SendErrorResponse(68);
1038 if (!packet.ConsumeFront("jTraceStart:"))
1039 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1041 TraceOptions options;
1042 uint64_t type = std::numeric_limits<uint64_t>::max();
1043 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1044 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1045 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1047 auto json_object = StructuredData::ParseJSON(packet.Peek());
1050 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1051 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1053 auto json_dict = json_object->GetAsDictionary();
1055 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1056 options.setMetaDataBufferSize(metabuffersize);
1058 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1059 options.setTraceBufferSize(buffersize);
1061 json_dict->GetValueForKeyAsInteger("type", type);
1062 options.setType(static_cast<lldb::TraceType>(type));
1064 json_dict->GetValueForKeyAsInteger("threadid", tid);
1065 options.setThreadID(tid);
1067 StructuredData::ObjectSP custom_params_sp =
1068 json_dict->GetValueForKey("params");
1069 if (custom_params_sp &&
1070 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1071 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1073 options.setTraceParams(
1074 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1076 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1077 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1078 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1080 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1084 lldb::user_id_t uid = LLDB_INVALID_UID;
1085 uid = m_debugged_process_up->StartTrace(options, error);
1086 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1088 return SendErrorResponse(error);
1090 StreamGDBRemote response;
1091 response.Printf("%" PRIx64, uid);
1092 return SendPacketNoLock(response.GetString());
1095 GDBRemoteCommunication::PacketResult
1096 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1097 StringExtractorGDBRemote &packet) {
1098 // Fail if we don't have a current process.
1099 if (!m_debugged_process_up ||
1100 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1101 return SendErrorResponse(68);
1103 if (!packet.ConsumeFront("jTraceStop:"))
1104 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1106 lldb::user_id_t uid = LLDB_INVALID_UID;
1107 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1109 auto json_object = StructuredData::ParseJSON(packet.Peek());
1112 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1113 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1115 auto json_dict = json_object->GetAsDictionary();
1117 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1118 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1120 json_dict->GetValueForKeyAsInteger("threadid", tid);
1122 Status error = m_debugged_process_up->StopTrace(uid, tid);
1125 return SendErrorResponse(error);
1127 return SendOKResponse();
1130 GDBRemoteCommunication::PacketResult
1131 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1132 StringExtractorGDBRemote &packet) {
1134 // Fail if we don't have a current process.
1135 if (!m_debugged_process_up ||
1136 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1137 return SendErrorResponse(68);
1139 if (!packet.ConsumeFront("jTraceConfigRead:"))
1140 return SendIllFormedResponse(packet,
1141 "jTraceConfigRead: Ill formed packet ");
1143 lldb::user_id_t uid = LLDB_INVALID_UID;
1144 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1146 auto json_object = StructuredData::ParseJSON(packet.Peek());
1149 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1150 return SendIllFormedResponse(packet,
1151 "jTraceConfigRead: Ill formed packet ");
1153 auto json_dict = json_object->GetAsDictionary();
1155 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1156 return SendIllFormedResponse(packet,
1157 "jTraceConfigRead: Ill formed packet ");
1159 json_dict->GetValueForKeyAsInteger("threadid", threadid);
1161 TraceOptions options;
1162 StreamGDBRemote response;
1164 options.setThreadID(threadid);
1165 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1168 return SendErrorResponse(error);
1170 StreamGDBRemote escaped_response;
1171 StructuredData::Dictionary json_packet;
1173 json_packet.AddIntegerItem("type", options.getType());
1174 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1175 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1177 StructuredData::DictionarySP custom_params = options.getTraceParams();
1179 json_packet.AddItem("params", custom_params);
1181 StreamString json_string;
1182 json_packet.Dump(json_string, false);
1183 escaped_response.PutEscapedBytes(json_string.GetData(),
1184 json_string.GetSize());
1185 return SendPacketNoLock(escaped_response.GetString());
1188 GDBRemoteCommunication::PacketResult
1189 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1190 StringExtractorGDBRemote &packet) {
1192 // Fail if we don't have a current process.
1193 if (!m_debugged_process_up ||
1194 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1195 return SendErrorResponse(68);
1197 enum PacketType { MetaData, BufferData };
1198 PacketType tracetype = MetaData;
1200 if (packet.ConsumeFront("jTraceBufferRead:"))
1201 tracetype = BufferData;
1202 else if (packet.ConsumeFront("jTraceMetaRead:"))
1203 tracetype = MetaData;
1205 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1208 lldb::user_id_t uid = LLDB_INVALID_UID;
1210 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1211 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1212 uint64_t offset = std::numeric_limits<uint64_t>::max();
1214 auto json_object = StructuredData::ParseJSON(packet.Peek());
1217 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1218 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1220 auto json_dict = json_object->GetAsDictionary();
1222 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1223 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1224 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1225 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1227 json_dict->GetValueForKeyAsInteger("threadid", tid);
1229 // Allocate the response buffer.
1230 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1232 return SendErrorResponse(0x78);
1234 StreamGDBRemote response;
1236 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1238 if (tracetype == BufferData)
1239 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1240 else if (tracetype == MetaData)
1241 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1244 return SendErrorResponse(error);
1247 response.PutHex8(i);
1249 StreamGDBRemote escaped_response;
1250 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1251 return SendPacketNoLock(escaped_response.GetString());
1254 GDBRemoteCommunication::PacketResult
1255 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1256 StringExtractorGDBRemote &packet) {
1257 // Fail if we don't have a current process.
1258 if (!m_debugged_process_up ||
1259 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1260 return SendErrorResponse(68);
1262 lldb::pid_t pid = m_debugged_process_up->GetID();
1264 if (pid == LLDB_INVALID_PROCESS_ID)
1265 return SendErrorResponse(1);
1267 ProcessInstanceInfo proc_info;
1268 if (!Host::GetProcessInfo(pid, proc_info))
1269 return SendErrorResponse(1);
1271 StreamString response;
1272 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1273 return SendPacketNoLock(response.GetString());
1276 GDBRemoteCommunication::PacketResult
1277 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1278 // Fail if we don't have a current process.
1279 if (!m_debugged_process_up ||
1280 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1281 return SendErrorResponse(68);
1283 // Make sure we set the current thread so g and p packets return the data the
1285 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1286 SetCurrentThreadID(tid);
1288 NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1290 return SendErrorResponse(69);
1292 StreamString response;
1293 response.Printf("QC%" PRIx64, thread->GetID());
1295 return SendPacketNoLock(response.GetString());
1298 GDBRemoteCommunication::PacketResult
1299 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1300 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1302 StopSTDIOForwarding();
1304 if (!m_debugged_process_up) {
1305 LLDB_LOG(log, "No debugged process found.");
1306 return PacketResult::Success;
1309 Status error = m_debugged_process_up->Kill();
1311 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1312 m_debugged_process_up->GetID(), error);
1314 // No OK response for kill packet.
1315 // return SendOKResponse ();
1316 return PacketResult::Success;
1319 GDBRemoteCommunication::PacketResult
1320 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1321 StringExtractorGDBRemote &packet) {
1322 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1323 if (packet.GetU32(0))
1324 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1326 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1327 return SendOKResponse();
1330 GDBRemoteCommunication::PacketResult
1331 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1332 StringExtractorGDBRemote &packet) {
1333 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1335 packet.GetHexByteString(path);
1336 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1337 return SendOKResponse();
1340 GDBRemoteCommunication::PacketResult
1341 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1342 StringExtractorGDBRemote &packet) {
1343 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1345 StreamString response;
1346 response.PutCStringAsRawHex8(working_dir.GetCString());
1347 return SendPacketNoLock(response.GetString());
1350 return SendErrorResponse(14);
1353 GDBRemoteCommunication::PacketResult
1354 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1355 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1357 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1359 // Ensure we have a native process.
1360 if (!m_debugged_process_up) {
1362 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1365 return SendErrorResponse(0x36);
1368 // Pull out the signal number.
1369 packet.SetFilePos(::strlen("C"));
1370 if (packet.GetBytesLeft() < 1) {
1371 // Shouldn't be using a C without a signal.
1372 return SendIllFormedResponse(packet, "C packet specified without signal.");
1374 const uint32_t signo =
1375 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1376 if (signo == std::numeric_limits<uint32_t>::max())
1377 return SendIllFormedResponse(packet, "failed to parse signal number");
1379 // Handle optional continue address.
1380 if (packet.GetBytesLeft() > 0) {
1381 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1382 if (*packet.Peek() == ';')
1383 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1385 return SendIllFormedResponse(
1386 packet, "unexpected content after $C{signal-number}");
1389 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1392 // We have two branches: what to do if a continue thread is specified (in
1393 // which case we target sending the signal to that thread), or when we don't
1394 // have a continue thread set (in which case we send a signal to the
1397 // TODO discuss with Greg Clayton, make sure this makes sense.
1399 lldb::tid_t signal_tid = GetContinueThreadID();
1400 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1401 // The resume action for the continue thread (or all threads if a continue
1402 // thread is not set).
1403 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1404 static_cast<int>(signo)};
1406 // Add the action for the continue thread (or all threads when the continue
1407 // thread isn't present).
1408 resume_actions.Append(action);
1410 // Send the signal to the process since we weren't targeting a specific
1411 // continue thread with the signal.
1412 error = m_debugged_process_up->Signal(signo);
1414 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1415 m_debugged_process_up->GetID(), error);
1417 return SendErrorResponse(0x52);
1421 // Resume the threads.
1422 error = m_debugged_process_up->Resume(resume_actions);
1424 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1425 m_debugged_process_up->GetID(), error);
1427 return SendErrorResponse(0x38);
1430 // Don't send an "OK" packet; response is the stopped/exited message.
1431 return PacketResult::Success;
1434 GDBRemoteCommunication::PacketResult
1435 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1436 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1438 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1440 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1442 // For now just support all continue.
1443 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1444 if (has_continue_address) {
1445 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1447 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1450 // Ensure we have a native process.
1451 if (!m_debugged_process_up) {
1453 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1456 return SendErrorResponse(0x36);
1459 // Build the ResumeActionList
1460 ResumeActionList actions(StateType::eStateRunning, 0);
1462 Status error = m_debugged_process_up->Resume(actions);
1464 LLDB_LOG(log, "c failed for process {0}: {1}",
1465 m_debugged_process_up->GetID(), error);
1466 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1469 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1470 // No response required from continue.
1471 return PacketResult::Success;
1474 GDBRemoteCommunication::PacketResult
1475 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1476 StringExtractorGDBRemote &packet) {
1477 StreamString response;
1478 response.Printf("vCont;c;C;s;S");
1480 return SendPacketNoLock(response.GetString());
1483 GDBRemoteCommunication::PacketResult
1484 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1485 StringExtractorGDBRemote &packet) {
1486 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1488 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1491 packet.SetFilePos(::strlen("vCont"));
1493 if (packet.GetBytesLeft() == 0) {
1495 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1498 return SendIllFormedResponse(packet, "Missing action from vCont package");
1501 // Check if this is all continue (no options or ";c").
1502 if (::strcmp(packet.Peek(), ";c") == 0) {
1503 // Move past the ';', then do a simple 'c'.
1504 packet.SetFilePos(packet.GetFilePos() + 1);
1505 return Handle_c(packet);
1506 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1507 // Move past the ';', then do a simple 's'.
1508 packet.SetFilePos(packet.GetFilePos() + 1);
1509 return Handle_s(packet);
1512 // Ensure we have a native process.
1513 if (!m_debugged_process_up) {
1514 LLDB_LOG(log, "no debugged process");
1515 return SendErrorResponse(0x36);
1518 ResumeActionList thread_actions;
1520 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1521 // Skip the semi-colon.
1524 // Build up the thread action.
1525 ResumeAction thread_action;
1526 thread_action.tid = LLDB_INVALID_THREAD_ID;
1527 thread_action.state = eStateInvalid;
1528 thread_action.signal = 0;
1530 const char action = packet.GetChar();
1533 thread_action.signal = packet.GetHexMaxU32(false, 0);
1534 if (thread_action.signal == 0)
1535 return SendIllFormedResponse(
1536 packet, "Could not parse signal in vCont packet C action");
1541 thread_action.state = eStateRunning;
1545 thread_action.signal = packet.GetHexMaxU32(false, 0);
1546 if (thread_action.signal == 0)
1547 return SendIllFormedResponse(
1548 packet, "Could not parse signal in vCont packet S action");
1553 thread_action.state = eStateStepping;
1557 return SendIllFormedResponse(packet, "Unsupported vCont action");
1561 // Parse out optional :{thread-id} value.
1562 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1563 // Consume the separator.
1566 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1567 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1568 return SendIllFormedResponse(
1569 packet, "Could not parse thread number in vCont packet");
1572 thread_actions.Append(thread_action);
1575 Status error = m_debugged_process_up->Resume(thread_actions);
1577 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1578 m_debugged_process_up->GetID(), error);
1579 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1582 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1583 // No response required from vCont.
1584 return PacketResult::Success;
1587 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1588 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1589 LLDB_LOG(log, "setting current thread id to {0}", tid);
1591 m_current_tid = tid;
1592 if (m_debugged_process_up)
1593 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1596 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1597 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1598 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1600 m_continue_tid = tid;
1603 GDBRemoteCommunication::PacketResult
1604 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1605 StringExtractorGDBRemote &packet) {
1606 // Handle the $? gdbremote command.
1608 // If no process, indicate error
1609 if (!m_debugged_process_up)
1610 return SendErrorResponse(02);
1612 return SendStopReasonForState(m_debugged_process_up->GetState());
1615 GDBRemoteCommunication::PacketResult
1616 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1617 lldb::StateType process_state) {
1618 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1620 switch (process_state) {
1621 case eStateAttaching:
1622 case eStateLaunching:
1624 case eStateStepping:
1625 case eStateDetached:
1626 // NOTE: gdb protocol doc looks like it should return $OK
1627 // when everything is running (i.e. no stopped result).
1628 return PacketResult::Success; // Ignore
1630 case eStateSuspended:
1632 case eStateCrashed: {
1633 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1634 // Make sure we set the current thread so g and p packets return the data
1635 // the gdb will expect.
1636 SetCurrentThreadID(tid);
1637 return SendStopReplyPacketForThread(tid);
1641 case eStateUnloaded:
1643 return SendWResponse(m_debugged_process_up.get());
1646 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1647 m_debugged_process_up->GetID(), process_state);
1651 return SendErrorResponse(0);
1654 GDBRemoteCommunication::PacketResult
1655 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1656 StringExtractorGDBRemote &packet) {
1657 // Fail if we don't have a current process.
1658 if (!m_debugged_process_up ||
1659 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1660 return SendErrorResponse(68);
1662 // Ensure we have a thread.
1663 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1665 return SendErrorResponse(69);
1667 // Get the register context for the first thread.
1668 NativeRegisterContext ®_context = thread->GetRegisterContext();
1670 // Parse out the register number from the request.
1671 packet.SetFilePos(strlen("qRegisterInfo"));
1672 const uint32_t reg_index =
1673 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1674 if (reg_index == std::numeric_limits<uint32_t>::max())
1675 return SendErrorResponse(69);
1677 // Return the end of registers response if we've iterated one past the end of
1678 // the register set.
1679 if (reg_index >= reg_context.GetUserRegisterCount())
1680 return SendErrorResponse(69);
1682 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1684 return SendErrorResponse(69);
1686 // Build the reginfos response.
1687 StreamGDBRemote response;
1689 response.PutCString("name:");
1690 response.PutCString(reg_info->name);
1691 response.PutChar(';');
1693 if (reg_info->alt_name && reg_info->alt_name[0]) {
1694 response.PutCString("alt-name:");
1695 response.PutCString(reg_info->alt_name);
1696 response.PutChar(';');
1699 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1700 reg_info->byte_size * 8, reg_info->byte_offset);
1702 switch (reg_info->encoding) {
1704 response.PutCString("encoding:uint;");
1707 response.PutCString("encoding:sint;");
1709 case eEncodingIEEE754:
1710 response.PutCString("encoding:ieee754;");
1712 case eEncodingVector:
1713 response.PutCString("encoding:vector;");
1719 switch (reg_info->format) {
1721 response.PutCString("format:binary;");
1723 case eFormatDecimal:
1724 response.PutCString("format:decimal;");
1727 response.PutCString("format:hex;");
1730 response.PutCString("format:float;");
1732 case eFormatVectorOfSInt8:
1733 response.PutCString("format:vector-sint8;");
1735 case eFormatVectorOfUInt8:
1736 response.PutCString("format:vector-uint8;");
1738 case eFormatVectorOfSInt16:
1739 response.PutCString("format:vector-sint16;");
1741 case eFormatVectorOfUInt16:
1742 response.PutCString("format:vector-uint16;");
1744 case eFormatVectorOfSInt32:
1745 response.PutCString("format:vector-sint32;");
1747 case eFormatVectorOfUInt32:
1748 response.PutCString("format:vector-uint32;");
1750 case eFormatVectorOfFloat32:
1751 response.PutCString("format:vector-float32;");
1753 case eFormatVectorOfUInt64:
1754 response.PutCString("format:vector-uint64;");
1756 case eFormatVectorOfUInt128:
1757 response.PutCString("format:vector-uint128;");
1763 const char *const register_set_name =
1764 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1765 if (register_set_name) {
1766 response.PutCString("set:");
1767 response.PutCString(register_set_name);
1768 response.PutChar(';');
1771 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1772 LLDB_INVALID_REGNUM)
1773 response.Printf("ehframe:%" PRIu32 ";",
1774 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1776 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1777 response.Printf("dwarf:%" PRIu32 ";",
1778 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1780 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1781 case LLDB_REGNUM_GENERIC_PC:
1782 response.PutCString("generic:pc;");
1784 case LLDB_REGNUM_GENERIC_SP:
1785 response.PutCString("generic:sp;");
1787 case LLDB_REGNUM_GENERIC_FP:
1788 response.PutCString("generic:fp;");
1790 case LLDB_REGNUM_GENERIC_RA:
1791 response.PutCString("generic:ra;");
1793 case LLDB_REGNUM_GENERIC_FLAGS:
1794 response.PutCString("generic:flags;");
1796 case LLDB_REGNUM_GENERIC_ARG1:
1797 response.PutCString("generic:arg1;");
1799 case LLDB_REGNUM_GENERIC_ARG2:
1800 response.PutCString("generic:arg2;");
1802 case LLDB_REGNUM_GENERIC_ARG3:
1803 response.PutCString("generic:arg3;");
1805 case LLDB_REGNUM_GENERIC_ARG4:
1806 response.PutCString("generic:arg4;");
1808 case LLDB_REGNUM_GENERIC_ARG5:
1809 response.PutCString("generic:arg5;");
1811 case LLDB_REGNUM_GENERIC_ARG6:
1812 response.PutCString("generic:arg6;");
1814 case LLDB_REGNUM_GENERIC_ARG7:
1815 response.PutCString("generic:arg7;");
1817 case LLDB_REGNUM_GENERIC_ARG8:
1818 response.PutCString("generic:arg8;");
1824 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1825 response.PutCString("container-regs:");
1827 for (const uint32_t *reg_num = reg_info->value_regs;
1828 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1830 response.PutChar(',');
1831 response.Printf("%" PRIx32, *reg_num);
1833 response.PutChar(';');
1836 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1837 response.PutCString("invalidate-regs:");
1839 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1840 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1842 response.PutChar(',');
1843 response.Printf("%" PRIx32, *reg_num);
1845 response.PutChar(';');
1848 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1849 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1850 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1851 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1852 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1853 response.PutChar(';');
1855 return SendPacketNoLock(response.GetString());
1858 GDBRemoteCommunication::PacketResult
1859 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1860 StringExtractorGDBRemote &packet) {
1861 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1863 // Fail if we don't have a current process.
1864 if (!m_debugged_process_up ||
1865 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1866 LLDB_LOG(log, "no process ({0}), returning OK",
1867 m_debugged_process_up ? "invalid process id"
1868 : "null m_debugged_process_up");
1869 return SendOKResponse();
1872 StreamGDBRemote response;
1873 response.PutChar('m');
1875 LLDB_LOG(log, "starting thread iteration");
1876 NativeThreadProtocol *thread;
1877 uint32_t thread_index;
1878 for (thread_index = 0,
1879 thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1880 thread; ++thread_index,
1881 thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1882 LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1884 if (thread_index > 0)
1885 response.PutChar(',');
1886 response.Printf("%" PRIx64, thread->GetID());
1889 LLDB_LOG(log, "finished thread iteration");
1890 return SendPacketNoLock(response.GetString());
1893 GDBRemoteCommunication::PacketResult
1894 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1895 StringExtractorGDBRemote &packet) {
1896 // FIXME for now we return the full thread list in the initial packet and
1897 // always do nothing here.
1898 return SendPacketNoLock("l");
1901 GDBRemoteCommunication::PacketResult
1902 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1903 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1905 // Parse out the register number from the request.
1906 packet.SetFilePos(strlen("p"));
1907 const uint32_t reg_index =
1908 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1909 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1911 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1912 "parse register number from request \"%s\"",
1913 __FUNCTION__, packet.GetStringRef().c_str());
1914 return SendErrorResponse(0x15);
1917 // Get the thread to use.
1918 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1920 LLDB_LOG(log, "failed, no thread available");
1921 return SendErrorResponse(0x15);
1924 // Get the thread's register context.
1925 NativeRegisterContext ®_context = thread->GetRegisterContext();
1927 // Return the end of registers response if we've iterated one past the end of
1928 // the register set.
1929 if (reg_index >= reg_context.GetUserRegisterCount()) {
1931 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1932 "register %" PRIu32 " beyond register count %" PRIu32,
1933 __FUNCTION__, reg_index,
1934 reg_context.GetUserRegisterCount());
1935 return SendErrorResponse(0x15);
1938 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1941 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1942 "register %" PRIu32 " returned NULL",
1943 __FUNCTION__, reg_index);
1944 return SendErrorResponse(0x15);
1947 // Build the reginfos response.
1948 StreamGDBRemote response;
1950 // Retrieve the value
1951 RegisterValue reg_value;
1952 Status error = reg_context.ReadRegister(reg_info, reg_value);
1955 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1956 "requested register %" PRIu32 " (%s) failed: %s",
1957 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1958 return SendErrorResponse(0x15);
1961 const uint8_t *const data =
1962 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1965 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1966 "bytes from requested register %" PRIu32,
1967 __FUNCTION__, reg_index);
1968 return SendErrorResponse(0x15);
1971 // FIXME flip as needed to get data in big/little endian format for this host.
1972 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1973 response.PutHex8(data[i]);
1975 return SendPacketNoLock(response.GetString());
1978 GDBRemoteCommunication::PacketResult
1979 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1980 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1982 // Ensure there is more content.
1983 if (packet.GetBytesLeft() < 1)
1984 return SendIllFormedResponse(packet, "Empty P packet");
1986 // Parse out the register number from the request.
1987 packet.SetFilePos(strlen("P"));
1988 const uint32_t reg_index =
1989 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1990 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1992 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1993 "parse register number from request \"%s\"",
1994 __FUNCTION__, packet.GetStringRef().c_str());
1995 return SendErrorResponse(0x29);
1998 // Note debugserver would send an E30 here.
1999 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2000 return SendIllFormedResponse(
2001 packet, "P packet missing '=' char after register number");
2003 // Parse out the value.
2004 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2005 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2007 // Get the thread to use.
2008 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2011 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2012 "available (thread index 0)",
2014 return SendErrorResponse(0x28);
2017 // Get the thread's register context.
2018 NativeRegisterContext ®_context = thread->GetRegisterContext();
2019 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2022 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2023 "register %" PRIu32 " returned NULL",
2024 __FUNCTION__, reg_index);
2025 return SendErrorResponse(0x48);
2028 // Return the end of registers response if we've iterated one past the end of
2029 // the register set.
2030 if (reg_index >= reg_context.GetUserRegisterCount()) {
2032 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2033 "register %" PRIu32 " beyond register count %" PRIu32,
2034 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2035 return SendErrorResponse(0x47);
2038 // The dwarf expression are evaluate on host site which may cause register
2039 // size to change Hence the reg_size may not be same as reg_info->bytes_size
2040 if ((reg_size != reg_info->byte_size) &&
2041 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2042 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2045 // Build the reginfos response.
2046 StreamGDBRemote response;
2048 RegisterValue reg_value(
2049 reg_bytes, reg_size,
2050 m_debugged_process_up->GetArchitecture().GetByteOrder());
2051 Status error = reg_context.WriteRegister(reg_info, reg_value);
2054 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2055 "requested register %" PRIu32 " (%s) failed: %s",
2056 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2057 return SendErrorResponse(0x32);
2060 return SendOKResponse();
2063 GDBRemoteCommunication::PacketResult
2064 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2065 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2067 // Fail if we don't have a current process.
2068 if (!m_debugged_process_up ||
2069 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2072 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2074 return SendErrorResponse(0x15);
2077 // Parse out which variant of $H is requested.
2078 packet.SetFilePos(strlen("H"));
2079 if (packet.GetBytesLeft() < 1) {
2081 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2082 "missing {g,c} variant",
2084 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2087 const char h_variant = packet.GetChar();
2088 switch (h_variant) {
2098 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2099 __FUNCTION__, h_variant);
2100 return SendIllFormedResponse(packet,
2101 "H variant unsupported, should be c or g");
2104 // Parse out the thread number.
2105 // FIXME return a parse success/fail value. All values are valid here.
2106 const lldb::tid_t tid =
2107 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2109 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2111 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2112 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2115 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2118 return SendErrorResponse(0x15);
2122 // Now switch the given thread type.
2123 switch (h_variant) {
2125 SetCurrentThreadID(tid);
2129 SetContinueThreadID(tid);
2133 assert(false && "unsupported $H variant - shouldn't get here");
2134 return SendIllFormedResponse(packet,
2135 "H variant unsupported, should be c or g");
2138 return SendOKResponse();
2141 GDBRemoteCommunication::PacketResult
2142 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2143 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2145 // Fail if we don't have a current process.
2146 if (!m_debugged_process_up ||
2147 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2150 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2152 return SendErrorResponse(0x15);
2155 packet.SetFilePos(::strlen("I"));
2158 size_t read = packet.GetHexBytesAvail(tmp);
2162 // write directly to stdin *this might block if stdin buffer is full*
2163 // TODO: enqueue this block in circular buffer and send window size to
2165 ConnectionStatus status;
2167 m_stdio_communication.Write(tmp, read, status, &error);
2169 return SendErrorResponse(0x15);
2173 return SendOKResponse();
2176 GDBRemoteCommunication::PacketResult
2177 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2178 StringExtractorGDBRemote &packet) {
2179 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2181 // Fail if we don't have a current process.
2182 if (!m_debugged_process_up ||
2183 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2184 LLDB_LOG(log, "failed, no process available");
2185 return SendErrorResponse(0x15);
2188 // Interrupt the process.
2189 Status error = m_debugged_process_up->Interrupt();
2191 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2193 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2196 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2198 // No response required from stop all.
2199 return PacketResult::Success;
2202 GDBRemoteCommunication::PacketResult
2203 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2204 StringExtractorGDBRemote &packet) {
2205 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2207 if (!m_debugged_process_up ||
2208 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2211 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2213 return SendErrorResponse(0x15);
2216 // Parse out the memory address.
2217 packet.SetFilePos(strlen("m"));
2218 if (packet.GetBytesLeft() < 1)
2219 return SendIllFormedResponse(packet, "Too short m packet");
2221 // Read the address. Punting on validation.
2222 // FIXME replace with Hex U64 read with no default value that fails on failed
2224 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2227 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2228 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2230 // Get # bytes to read.
2231 if (packet.GetBytesLeft() < 1)
2232 return SendIllFormedResponse(packet, "Length missing in m packet");
2234 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2235 if (byte_count == 0) {
2237 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2238 "zero-length packet",
2240 return SendOKResponse();
2243 // Allocate the response buffer.
2244 std::string buf(byte_count, '\0');
2246 return SendErrorResponse(0x78);
2248 // Retrieve the process memory.
2249 size_t bytes_read = 0;
2250 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2251 read_addr, &buf[0], byte_count, bytes_read);
2254 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2255 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2256 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2258 return SendErrorResponse(0x08);
2261 if (bytes_read == 0) {
2263 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2264 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2265 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2267 return SendErrorResponse(0x08);
2270 StreamGDBRemote response;
2271 packet.SetFilePos(0);
2272 char kind = packet.GetChar('?');
2274 response.PutEscapedBytes(buf.data(), byte_count);
2276 assert(kind == 'm');
2277 for (size_t i = 0; i < bytes_read; ++i)
2278 response.PutHex8(buf[i]);
2281 return SendPacketNoLock(response.GetString());
2284 GDBRemoteCommunication::PacketResult
2285 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2286 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2288 if (!m_debugged_process_up ||
2289 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2292 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2294 return SendErrorResponse(0x15);
2297 // Parse out the memory address.
2298 packet.SetFilePos(strlen("M"));
2299 if (packet.GetBytesLeft() < 1)
2300 return SendIllFormedResponse(packet, "Too short M packet");
2302 // Read the address. Punting on validation.
2303 // FIXME replace with Hex U64 read with no default value that fails on failed
2305 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2308 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2309 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2311 // Get # bytes to read.
2312 if (packet.GetBytesLeft() < 1)
2313 return SendIllFormedResponse(packet, "Length missing in M packet");
2315 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2316 if (byte_count == 0) {
2317 LLDB_LOG(log, "nothing to write: zero-length packet");
2318 return PacketResult::Success;
2322 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2323 return SendIllFormedResponse(
2324 packet, "Comma sep missing in M packet after byte length");
2326 // Allocate the conversion buffer.
2327 std::vector<uint8_t> buf(byte_count, 0);
2329 return SendErrorResponse(0x78);
2331 // Convert the hex memory write contents to bytes.
2332 StreamGDBRemote response;
2333 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2334 if (convert_count != byte_count) {
2336 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2338 m_debugged_process_up->GetID(), write_addr, byte_count,
2340 return SendIllFormedResponse(packet, "M content byte length specified did "
2341 "not match hex-encoded content "
2345 // Write the process memory.
2346 size_t bytes_written = 0;
2347 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2348 byte_count, bytes_written);
2350 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2351 m_debugged_process_up->GetID(), write_addr, error);
2352 return SendErrorResponse(0x09);
2355 if (bytes_written == 0) {
2356 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2357 m_debugged_process_up->GetID(), write_addr, byte_count);
2358 return SendErrorResponse(0x09);
2361 return SendOKResponse();
2364 GDBRemoteCommunication::PacketResult
2365 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2366 StringExtractorGDBRemote &packet) {
2367 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2369 // Currently only the NativeProcessProtocol knows if it can handle a
2370 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2371 // attached to a process. For now we'll assume the client only asks this
2372 // when a process is being debugged.
2374 // Ensure we have a process running; otherwise, we can't figure this out
2375 // since we won't have a NativeProcessProtocol.
2376 if (!m_debugged_process_up ||
2377 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2380 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2382 return SendErrorResponse(0x15);
2385 // Test if we can get any region back when asking for the region around NULL.
2386 MemoryRegionInfo region_info;
2387 const Status error =
2388 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2390 // We don't support memory region info collection for this
2391 // NativeProcessProtocol.
2392 return SendUnimplementedResponse("");
2395 return SendOKResponse();
2398 GDBRemoteCommunication::PacketResult
2399 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2400 StringExtractorGDBRemote &packet) {
2401 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2403 // Ensure we have a process.
2404 if (!m_debugged_process_up ||
2405 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2408 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2410 return SendErrorResponse(0x15);
2413 // Parse out the memory address.
2414 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2415 if (packet.GetBytesLeft() < 1)
2416 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2418 // Read the address. Punting on validation.
2419 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2421 StreamGDBRemote response;
2423 // Get the memory region info for the target address.
2424 MemoryRegionInfo region_info;
2425 const Status error =
2426 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2428 // Return the error message.
2430 response.PutCString("error:");
2431 response.PutCStringAsRawHex8(error.AsCString());
2432 response.PutChar(';');
2434 // Range start and size.
2435 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2436 region_info.GetRange().GetRangeBase(),
2437 region_info.GetRange().GetByteSize());
2440 if (region_info.GetReadable() || region_info.GetWritable() ||
2441 region_info.GetExecutable()) {
2442 // Write permissions info.
2443 response.PutCString("permissions:");
2445 if (region_info.GetReadable())
2446 response.PutChar('r');
2447 if (region_info.GetWritable())
2448 response.PutChar('w');
2449 if (region_info.GetExecutable())
2450 response.PutChar('x');
2452 response.PutChar(';');
2456 ConstString name = region_info.GetName();
2458 response.PutCString("name:");
2459 response.PutCStringAsRawHex8(name.AsCString());
2460 response.PutChar(';');
2464 return SendPacketNoLock(response.GetString());
2467 GDBRemoteCommunication::PacketResult
2468 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2469 // Ensure we have a process.
2470 if (!m_debugged_process_up ||
2471 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2472 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2473 LLDB_LOG(log, "failed, no process available");
2474 return SendErrorResponse(0x15);
2477 // Parse out software or hardware breakpoint or watchpoint requested.
2478 packet.SetFilePos(strlen("Z"));
2479 if (packet.GetBytesLeft() < 1)
2480 return SendIllFormedResponse(
2481 packet, "Too short Z packet, missing software/hardware specifier");
2483 bool want_breakpoint = true;
2484 bool want_hardware = false;
2485 uint32_t watch_flags = 0;
2487 const GDBStoppointType stoppoint_type =
2488 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2489 switch (stoppoint_type) {
2490 case eBreakpointSoftware:
2491 want_hardware = false;
2492 want_breakpoint = true;
2494 case eBreakpointHardware:
2495 want_hardware = true;
2496 want_breakpoint = true;
2498 case eWatchpointWrite:
2500 want_hardware = true;
2501 want_breakpoint = false;
2503 case eWatchpointRead:
2505 want_hardware = true;
2506 want_breakpoint = false;
2508 case eWatchpointReadWrite:
2510 want_hardware = true;
2511 want_breakpoint = false;
2513 case eStoppointInvalid:
2514 return SendIllFormedResponse(
2515 packet, "Z packet had invalid software/hardware specifier");
2518 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2519 return SendIllFormedResponse(
2520 packet, "Malformed Z packet, expecting comma after stoppoint type");
2522 // Parse out the stoppoint address.
2523 if (packet.GetBytesLeft() < 1)
2524 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2525 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2527 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2528 return SendIllFormedResponse(
2529 packet, "Malformed Z packet, expecting comma after address");
2531 // Parse out the stoppoint size (i.e. size hint for opcode size).
2532 const uint32_t size =
2533 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2534 if (size == std::numeric_limits<uint32_t>::max())
2535 return SendIllFormedResponse(
2536 packet, "Malformed Z packet, failed to parse size argument");
2538 if (want_breakpoint) {
2539 // Try to set the breakpoint.
2540 const Status error =
2541 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2542 if (error.Success())
2543 return SendOKResponse();
2544 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2545 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2546 m_debugged_process_up->GetID(), error);
2547 return SendErrorResponse(0x09);
2549 // Try to set the watchpoint.
2550 const Status error = m_debugged_process_up->SetWatchpoint(
2551 addr, size, watch_flags, want_hardware);
2552 if (error.Success())
2553 return SendOKResponse();
2554 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2555 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2556 m_debugged_process_up->GetID(), error);
2557 return SendErrorResponse(0x09);
2561 GDBRemoteCommunication::PacketResult
2562 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2563 // Ensure we have a process.
2564 if (!m_debugged_process_up ||
2565 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2566 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2567 LLDB_LOG(log, "failed, no process available");
2568 return SendErrorResponse(0x15);
2571 // Parse out software or hardware breakpoint or watchpoint requested.
2572 packet.SetFilePos(strlen("z"));
2573 if (packet.GetBytesLeft() < 1)
2574 return SendIllFormedResponse(
2575 packet, "Too short z packet, missing software/hardware specifier");
2577 bool want_breakpoint = true;
2578 bool want_hardware = false;
2580 const GDBStoppointType stoppoint_type =
2581 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2582 switch (stoppoint_type) {
2583 case eBreakpointHardware:
2584 want_breakpoint = true;
2585 want_hardware = true;
2587 case eBreakpointSoftware:
2588 want_breakpoint = true;
2590 case eWatchpointWrite:
2591 want_breakpoint = false;
2593 case eWatchpointRead:
2594 want_breakpoint = false;
2596 case eWatchpointReadWrite:
2597 want_breakpoint = false;
2600 return SendIllFormedResponse(
2601 packet, "z packet had invalid software/hardware specifier");
2604 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2605 return SendIllFormedResponse(
2606 packet, "Malformed z packet, expecting comma after stoppoint type");
2608 // Parse out the stoppoint address.
2609 if (packet.GetBytesLeft() < 1)
2610 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2611 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2613 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2614 return SendIllFormedResponse(
2615 packet, "Malformed z packet, expecting comma after address");
2618 // Parse out the stoppoint size (i.e. size hint for opcode size).
2619 const uint32_t size = packet.GetHexMaxU32 (false,
2620 std::numeric_limits<uint32_t>::max ());
2621 if (size == std::numeric_limits<uint32_t>::max ())
2622 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2626 if (want_breakpoint) {
2627 // Try to clear the breakpoint.
2628 const Status error =
2629 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2630 if (error.Success())
2631 return SendOKResponse();
2632 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2633 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2634 m_debugged_process_up->GetID(), error);
2635 return SendErrorResponse(0x09);
2637 // Try to clear the watchpoint.
2638 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2639 if (error.Success())
2640 return SendOKResponse();
2641 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2642 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2643 m_debugged_process_up->GetID(), error);
2644 return SendErrorResponse(0x09);
2648 GDBRemoteCommunication::PacketResult
2649 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2652 // Ensure we have a process.
2653 if (!m_debugged_process_up ||
2654 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2657 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2659 return SendErrorResponse(0x32);
2662 // We first try to use a continue thread id. If any one or any all set, use
2663 // the current thread. Bail out if we don't have a thread id.
2664 lldb::tid_t tid = GetContinueThreadID();
2665 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2666 tid = GetCurrentThreadID();
2667 if (tid == LLDB_INVALID_THREAD_ID)
2668 return SendErrorResponse(0x33);
2670 // Double check that we have such a thread.
2671 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2672 NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2674 return SendErrorResponse(0x33);
2676 // Create the step action for the given thread.
2677 ResumeAction action = {tid, eStateStepping, 0};
2679 // Setup the actions list.
2680 ResumeActionList actions;
2681 actions.Append(action);
2683 // All other threads stop while we're single stepping a thread.
2684 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2685 Status error = m_debugged_process_up->Resume(actions);
2688 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2689 " tid %" PRIu64 " Resume() failed with error: %s",
2690 __FUNCTION__, m_debugged_process_up->GetID(), tid,
2692 return SendErrorResponse(0x49);
2695 // No response here - the stop or exit will come from the resulting action.
2696 return PacketResult::Success;
2699 GDBRemoteCommunication::PacketResult
2700 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2701 StringExtractorGDBRemote &packet) {
2702 // *BSD impls should be able to do this too.
2703 #if defined(__linux__) || defined(__NetBSD__)
2704 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2706 // Parse out the offset.
2707 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2708 if (packet.GetBytesLeft() < 1)
2709 return SendIllFormedResponse(packet,
2710 "qXfer:auxv:read:: packet missing offset");
2712 const uint64_t auxv_offset =
2713 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2714 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2715 return SendIllFormedResponse(packet,
2716 "qXfer:auxv:read:: packet missing offset");
2719 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2720 return SendIllFormedResponse(
2721 packet, "qXfer:auxv:read:: packet missing comma after offset");
2723 // Parse out the length.
2724 const uint64_t auxv_length =
2725 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2726 if (auxv_length == std::numeric_limits<uint64_t>::max())
2727 return SendIllFormedResponse(packet,
2728 "qXfer:auxv:read:: packet missing length");
2730 // Grab the auxv data if we need it.
2731 if (!m_active_auxv_buffer_up) {
2732 // Make sure we have a valid process.
2733 if (!m_debugged_process_up ||
2734 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2737 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2739 return SendErrorResponse(0x10);
2742 // Grab the auxv data.
2743 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2744 if (!buffer_or_error) {
2745 std::error_code ec = buffer_or_error.getError();
2746 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2747 return SendErrorResponse(ec.value());
2749 m_active_auxv_buffer_up = std::move(*buffer_or_error);
2752 StreamGDBRemote response;
2753 bool done_with_buffer = false;
2755 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2756 if (auxv_offset >= buffer.size()) {
2757 // We have nothing left to send. Mark the buffer as complete.
2758 response.PutChar('l');
2759 done_with_buffer = true;
2761 // Figure out how many bytes are available starting at the given offset.
2762 buffer = buffer.drop_front(auxv_offset);
2764 // Mark the response type according to whether we're reading the remainder
2765 // of the auxv data.
2766 if (auxv_length >= buffer.size()) {
2767 // There will be nothing left to read after this
2768 response.PutChar('l');
2769 done_with_buffer = true;
2771 // There will still be bytes to read after this request.
2772 response.PutChar('m');
2773 buffer = buffer.take_front(auxv_length);
2776 // Now write the data in encoded binary form.
2777 response.PutEscapedBytes(buffer.data(), buffer.size());
2780 if (done_with_buffer)
2781 m_active_auxv_buffer_up.reset();
2783 return SendPacketNoLock(response.GetString());
2785 return SendUnimplementedResponse("not implemented on this platform");
2789 GDBRemoteCommunication::PacketResult
2790 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2791 StringExtractorGDBRemote &packet) {
2792 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2794 // Move past packet name.
2795 packet.SetFilePos(strlen("QSaveRegisterState"));
2797 // Get the thread to use.
2798 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2800 if (m_thread_suffix_supported)
2801 return SendIllFormedResponse(
2802 packet, "No thread specified in QSaveRegisterState packet");
2804 return SendIllFormedResponse(packet,
2805 "No thread was is set with the Hg packet");
2808 // Grab the register context for the thread.
2809 NativeRegisterContext& reg_context = thread->GetRegisterContext();
2811 // Save registers to a buffer.
2812 DataBufferSP register_data_sp;
2813 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2815 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2816 m_debugged_process_up->GetID(), error);
2817 return SendErrorResponse(0x75);
2820 // Allocate a new save id.
2821 const uint32_t save_id = GetNextSavedRegistersID();
2822 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2823 "GetNextRegisterSaveID() returned an existing register save id");
2825 // Save the register data buffer under the save id.
2827 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2828 m_saved_registers_map[save_id] = register_data_sp;
2831 // Write the response.
2832 StreamGDBRemote response;
2833 response.Printf("%" PRIu32, save_id);
2834 return SendPacketNoLock(response.GetString());
2837 GDBRemoteCommunication::PacketResult
2838 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2839 StringExtractorGDBRemote &packet) {
2840 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2842 // Parse out save id.
2843 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2844 if (packet.GetBytesLeft() < 1)
2845 return SendIllFormedResponse(
2846 packet, "QRestoreRegisterState packet missing register save id");
2848 const uint32_t save_id = packet.GetU32(0);
2850 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2851 "expecting decimal uint32_t");
2852 return SendErrorResponse(0x76);
2855 // Get the thread to use.
2856 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2858 if (m_thread_suffix_supported)
2859 return SendIllFormedResponse(
2860 packet, "No thread specified in QRestoreRegisterState packet");
2862 return SendIllFormedResponse(packet,
2863 "No thread was is set with the Hg packet");
2866 // Grab the register context for the thread.
2867 NativeRegisterContext ®_context = thread->GetRegisterContext();
2869 // Retrieve register state buffer, then remove from the list.
2870 DataBufferSP register_data_sp;
2872 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2874 // Find the register set buffer for the given save id.
2875 auto it = m_saved_registers_map.find(save_id);
2876 if (it == m_saved_registers_map.end()) {
2878 "pid {0} does not have a register set save buffer for id {1}",
2879 m_debugged_process_up->GetID(), save_id);
2880 return SendErrorResponse(0x77);
2882 register_data_sp = it->second;
2884 // Remove it from the map.
2885 m_saved_registers_map.erase(it);
2888 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
2890 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2891 m_debugged_process_up->GetID(), error);
2892 return SendErrorResponse(0x77);
2895 return SendOKResponse();
2898 GDBRemoteCommunication::PacketResult
2899 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2900 StringExtractorGDBRemote &packet) {
2901 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2903 // Consume the ';' after vAttach.
2904 packet.SetFilePos(strlen("vAttach"));
2905 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2906 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2908 // Grab the PID to which we will attach (assume hex encoding).
2909 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2910 if (pid == LLDB_INVALID_PROCESS_ID)
2911 return SendIllFormedResponse(packet,
2912 "vAttach failed to parse the process id");
2914 // Attempt to attach.
2916 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2920 Status error = AttachToProcess(pid);
2924 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2925 "pid %" PRIu64 ": %s\n",
2926 __FUNCTION__, pid, error.AsCString());
2927 return SendErrorResponse(error);
2930 // Notify we attached by sending a stop packet.
2931 return SendStopReasonForState(m_debugged_process_up->GetState());
2934 GDBRemoteCommunication::PacketResult
2935 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2936 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2938 StopSTDIOForwarding();
2940 // Fail if we don't have a current process.
2941 if (!m_debugged_process_up ||
2942 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2945 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2947 return SendErrorResponse(0x15);
2950 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2952 // Consume the ';' after D.
2953 packet.SetFilePos(1);
2954 if (packet.GetBytesLeft()) {
2955 if (packet.GetChar() != ';')
2956 return SendIllFormedResponse(packet, "D missing expected ';'");
2958 // Grab the PID from which we will detach (assume hex encoding).
2959 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2960 if (pid == LLDB_INVALID_PROCESS_ID)
2961 return SendIllFormedResponse(packet, "D failed to parse the process id");
2964 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
2965 return SendIllFormedResponse(packet, "Invalid pid");
2968 const Status error = m_debugged_process_up->Detach();
2971 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2972 "pid %" PRIu64 ": %s\n",
2973 __FUNCTION__, m_debugged_process_up->GetID(),
2975 return SendErrorResponse(0x01);
2978 return SendOKResponse();
2981 GDBRemoteCommunication::PacketResult
2982 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2983 StringExtractorGDBRemote &packet) {
2984 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2986 packet.SetFilePos(strlen("qThreadStopInfo"));
2987 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2988 if (tid == LLDB_INVALID_THREAD_ID) {
2990 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2991 "parse thread id from request \"%s\"",
2992 __FUNCTION__, packet.GetStringRef().c_str());
2993 return SendErrorResponse(0x15);
2995 return SendStopReplyPacketForThread(tid);
2998 GDBRemoteCommunication::PacketResult
2999 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3000 StringExtractorGDBRemote &) {
3001 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3003 // Ensure we have a debugged process.
3004 if (!m_debugged_process_up ||
3005 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3006 return SendErrorResponse(50);
3007 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3009 StreamString response;
3010 const bool threads_with_valid_stop_info_only = false;
3011 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3012 *m_debugged_process_up, threads_with_valid_stop_info_only);
3013 if (!threads_array_sp) {
3014 LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3015 m_debugged_process_up->GetID());
3016 return SendErrorResponse(52);
3019 threads_array_sp->Write(response);
3020 StreamGDBRemote escaped_response;
3021 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3022 return SendPacketNoLock(escaped_response.GetString());
3025 GDBRemoteCommunication::PacketResult
3026 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3027 StringExtractorGDBRemote &packet) {
3028 // Fail if we don't have a current process.
3029 if (!m_debugged_process_up ||
3030 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3031 return SendErrorResponse(68);
3033 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3034 if (packet.GetBytesLeft() == 0)
3035 return SendOKResponse();
3036 if (packet.GetChar() != ':')
3037 return SendErrorResponse(67);
3039 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3041 StreamGDBRemote response;
3042 if (hw_debug_cap == llvm::None)
3043 response.Printf("num:0;");
3045 response.Printf("num:%d;", hw_debug_cap->second);
3047 return SendPacketNoLock(response.GetString());
3050 GDBRemoteCommunication::PacketResult
3051 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3052 StringExtractorGDBRemote &packet) {
3053 // Fail if we don't have a current process.
3054 if (!m_debugged_process_up ||
3055 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3056 return SendErrorResponse(67);
3058 packet.SetFilePos(strlen("qFileLoadAddress:"));
3059 if (packet.GetBytesLeft() == 0)
3060 return SendErrorResponse(68);
3062 std::string file_name;
3063 packet.GetHexByteString(file_name);
3065 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3067 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3069 return SendErrorResponse(69);
3071 if (file_load_address == LLDB_INVALID_ADDRESS)
3072 return SendErrorResponse(1); // File not loaded
3074 StreamGDBRemote response;
3075 response.PutHex64(file_load_address);
3076 return SendPacketNoLock(response.GetString());
3079 GDBRemoteCommunication::PacketResult
3080 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3081 StringExtractorGDBRemote &packet) {
3082 std::vector<int> signals;
3083 packet.SetFilePos(strlen("QPassSignals:"));
3085 // Read sequence of hex signal numbers divided by a semicolon and optionally
3087 while (packet.GetBytesLeft() > 0) {
3088 int signal = packet.GetS32(-1, 16);
3090 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3091 signals.push_back(signal);
3093 packet.SkipSpaces();
3094 char separator = packet.GetChar();
3095 if (separator == '\0')
3096 break; // End of string
3097 if (separator != ';')
3098 return SendIllFormedResponse(packet, "Invalid separator,"
3099 " expected semicolon.");
3102 // Fail if we don't have a current process.
3103 if (!m_debugged_process_up)
3104 return SendErrorResponse(68);
3106 Status error = m_debugged_process_up->IgnoreSignals(signals);
3108 return SendErrorResponse(69);
3110 return SendOKResponse();
3113 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3114 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3116 // Tell the stdio connection to shut down.
3117 if (m_stdio_communication.IsConnected()) {
3118 auto connection = m_stdio_communication.GetConnection();
3121 connection->Disconnect(&error);
3123 if (error.Success()) {
3125 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3126 "terminal stdio - SUCCESS",
3130 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3131 "terminal stdio - FAIL: %s",
3132 __FUNCTION__, error.AsCString());
3138 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3139 StringExtractorGDBRemote &packet) {
3140 // We have no thread if we don't have a process.
3141 if (!m_debugged_process_up ||
3142 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3145 // If the client hasn't asked for thread suffix support, there will not be a
3146 // thread suffix. Use the current thread in that case.
3147 if (!m_thread_suffix_supported) {
3148 const lldb::tid_t current_tid = GetCurrentThreadID();
3149 if (current_tid == LLDB_INVALID_THREAD_ID)
3151 else if (current_tid == 0) {
3153 return m_debugged_process_up->GetThreadAtIndex(0);
3155 return m_debugged_process_up->GetThreadByID(current_tid);
3158 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3160 // Parse out the ';'.
3161 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3163 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3164 "error: expected ';' prior to start of thread suffix: packet "
3166 __FUNCTION__, packet.GetStringRef().c_str());
3170 if (!packet.GetBytesLeft())
3173 // Parse out thread: portion.
3174 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3176 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3177 "error: expected 'thread:' but not found, packet contents = "
3179 __FUNCTION__, packet.GetStringRef().c_str());
3182 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3183 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3185 return m_debugged_process_up->GetThreadByID(tid);
3190 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3191 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3192 // Use whatever the debug process says is the current thread id since the
3193 // protocol either didn't specify or specified we want any/all threads
3194 // marked as the current thread.
3195 if (!m_debugged_process_up)
3196 return LLDB_INVALID_THREAD_ID;
3197 return m_debugged_process_up->GetCurrentThreadID();
3199 // Use the specific current thread id set by the gdb remote protocol.
3200 return m_current_tid;
3203 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3204 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3205 return m_next_saved_registers_id++;
3208 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3209 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3211 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3212 m_active_auxv_buffer_up.reset();
3216 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3217 const ArchSpec &arch) {
3218 if (m_debugged_process_up) {
3220 if (m_debugged_process_up
3221 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3223 if (file_spec.Exists())
3228 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);