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/Core/StreamGDBRemote.h"
23 // Other libraries and framework includes
24 #include "llvm/ADT/Triple.h"
25 #include "lldb/Interpreter/Args.h"
26 #include "lldb/Core/DataBuffer.h"
27 #include "lldb/Core/Log.h"
28 #include "lldb/Core/RegisterValue.h"
29 #include "lldb/Core/State.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Host/ConnectionFileDescriptor.h"
32 #include "lldb/Host/Debug.h"
33 #include "lldb/Host/Endian.h"
34 #include "lldb/Host/File.h"
35 #include "lldb/Host/FileSystem.h"
36 #include "lldb/Host/Host.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Host/StringConvert.h"
39 #include "lldb/Host/TimeValue.h"
40 #include "lldb/Target/FileAction.h"
41 #include "lldb/Target/MemoryRegionInfo.h"
42 #include "lldb/Host/common/NativeRegisterContext.h"
43 #include "lldb/Host/common/NativeProcessProtocol.h"
44 #include "lldb/Host/common/NativeThreadProtocol.h"
45 #include "lldb/Utility/JSON.h"
46 #include "lldb/Utility/LLDBAssert.h"
49 #include "Utility/StringExtractorGDBRemote.h"
50 #include "Utility/UriParser.h"
51 #include "ProcessGDBRemote.h"
52 #include "ProcessGDBRemoteLog.h"
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
65 enum GDBRemoteServerError
67 // Set to the first unused error number in literal form below
69 eErrorNoProcess = eErrorFirst,
75 //----------------------------------------------------------------------
76 // GDBRemoteCommunicationServerLLGS constructor
77 //----------------------------------------------------------------------
78 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(MainLoop &mainloop)
79 : GDBRemoteCommunicationServerCommon("gdb-remote.server", "gdb-remote.server.rx_packet"),
81 m_current_tid(LLDB_INVALID_THREAD_ID),
82 m_continue_tid(LLDB_INVALID_THREAD_ID),
83 m_debugged_process_mutex(),
84 m_debugged_process_sp(),
85 m_stdio_communication("process.stdio"),
86 m_inferior_prev_state(StateType::eStateInvalid),
87 m_active_auxv_buffer_sp(),
88 m_saved_registers_mutex(),
89 m_saved_registers_map(),
90 m_next_saved_registers_id(1),
91 m_handshake_completed(false)
93 RegisterPacketHandlers();
97 GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
99 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
100 &GDBRemoteCommunicationServerLLGS::Handle_C);
101 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
102 &GDBRemoteCommunicationServerLLGS::Handle_c);
103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
104 &GDBRemoteCommunicationServerLLGS::Handle_D);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
106 &GDBRemoteCommunicationServerLLGS::Handle_H);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
108 &GDBRemoteCommunicationServerLLGS::Handle_I);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
110 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
112 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
113 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
114 &GDBRemoteCommunicationServerLLGS::Handle_M);
115 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
116 &GDBRemoteCommunicationServerLLGS::Handle_p);
117 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
118 &GDBRemoteCommunicationServerLLGS::Handle_P);
119 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
120 &GDBRemoteCommunicationServerLLGS::Handle_qC);
121 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
122 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
123 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
124 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
125 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
126 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
127 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
128 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
129 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
130 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
131 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
132 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
133 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
134 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
135 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
137 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
138 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
139 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
140 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
141 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
143 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
144 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
145 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
146 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
147 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
149 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
151 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
152 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
153 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
154 &GDBRemoteCommunicationServerLLGS::Handle_s);
155 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
156 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
158 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
159 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
160 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
162 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
163 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_x,
164 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
165 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
166 &GDBRemoteCommunicationServerLLGS::Handle_Z);
167 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
168 &GDBRemoteCommunicationServerLLGS::Handle_z);
170 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
171 [this](StringExtractorGDBRemote packet,
177 return this->Handle_k (packet);
182 GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
184 if ((argc < 1) || !args || !args[0] || !args[0][0])
185 return Error ("%s: no process command line specified to launch", __FUNCTION__);
187 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
192 GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
194 m_process_launch_info.GetFlags ().Set (launch_flags);
199 GDBRemoteCommunicationServerLLGS::LaunchProcess ()
201 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
203 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
204 return Error ("%s: no process command line specified to launch", __FUNCTION__);
208 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
209 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
210 error = NativeProcessProtocol::Launch(
211 m_process_launch_info,
214 m_debugged_process_sp);
217 if (!error.Success ())
219 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
223 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
225 // llgs local-process debugging may specify PTY paths, which will make these
226 // file actions non-null
227 // process launch -i/e/o will also make these file actions non-null
228 // nullptr means that the traffic is expected to flow over gdb-remote protocol
230 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
231 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
232 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
235 // nullptr means it's not redirected to file or pty (in case of LLGS local)
236 // at least one of stdio will be transferred pty<->gdb-remote
237 // we need to give the pty master handle to this object to read and/or write
239 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
241 // Setup stdout/stderr mapping from inferior to $O
242 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
243 if (terminal_fd >= 0)
246 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
247 error = SetSTDIOFileDescriptor (terminal_fd);
254 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
260 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
263 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
269 GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
273 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
275 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
277 // Before we try to attach, make sure we aren't already monitoring something else.
278 if (m_debugged_process_sp && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
279 return Error("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, m_debugged_process_sp->GetID());
282 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
283 if (!error.Success ())
285 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
289 // Setup stdout/stderr mapping from inferior.
290 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
291 if (terminal_fd >= 0)
294 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
295 error = SetSTDIOFileDescriptor (terminal_fd);
302 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
305 printf ("Attached to process %" PRIu64 "...\n", pid);
311 GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
313 assert (process && "process cannot be NULL");
314 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
317 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
320 StateAsCString (process->GetState ()));
324 GDBRemoteCommunication::PacketResult
325 GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
327 assert (process && "process cannot be NULL");
328 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
330 // send W notification
331 ExitType exit_type = ExitType::eExitTypeInvalid;
333 std::string exit_description;
335 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
339 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
341 StreamGDBRemote response;
342 response.PutChar ('E');
343 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
344 return SendPacketNoLock(response.GetData(), response.GetSize());
349 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
351 StreamGDBRemote response;
353 char return_type_code;
356 case ExitType::eExitTypeExit:
357 return_type_code = 'W';
359 case ExitType::eExitTypeSignal:
360 return_type_code = 'X';
362 case ExitType::eExitTypeStop:
363 return_type_code = 'S';
365 case ExitType::eExitTypeInvalid:
366 return_type_code = 'E';
369 response.PutChar (return_type_code);
371 // POSIX exit status limited to unsigned 8 bits.
372 response.PutHex8 (return_code);
374 return SendPacketNoLock(response.GetData(), response.GetSize());
379 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
384 for (i = buf_size-1; i >= 0; i--)
385 response.PutHex8 (buf[i]);
389 for (i = 0; i < buf_size; i++)
390 response.PutHex8 (buf[i]);
395 WriteRegisterValueInHexFixedWidth (StreamString &response,
396 NativeRegisterContextSP ®_ctx_sp,
397 const RegisterInfo ®_info,
398 const RegisterValue *reg_value_p)
400 RegisterValue reg_value;
403 Error error = reg_ctx_sp->ReadRegister (®_info, reg_value);
404 if (error.Success ())
405 reg_value_p = ®_value;
411 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
415 // Zero-out any unreadable values.
416 if (reg_info.byte_size > 0)
418 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
419 AppendHexValue (response, zeros.data(), zeros.size(), false);
424 static JSONObject::SP
425 GetRegistersAsJSON(NativeThreadProtocol &thread, bool abridged)
427 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
429 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
433 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
435 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
436 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
437 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
440 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
442 uint32_t reg_num = *reg_num_p;
444 // Expedite only a couple of registers until we figure out why sending registers is
446 static const uint32_t k_expedited_registers[] = {
447 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM
449 static const uint32_t k_abridged_expedited_registers[] = {
450 LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM
453 for (const uint32_t *generic_reg_p = abridged ? k_abridged_expedited_registers : k_expedited_registers;
454 *generic_reg_p != LLDB_INVALID_REGNUM;
457 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, *generic_reg_p);
458 if (reg_num == LLDB_INVALID_REGNUM)
459 continue; // Target does not support the given register.
462 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
463 if (reg_info_p == nullptr)
466 log->Printf("%s failed to get register info for register index %" PRIu32,
467 __FUNCTION__, reg_num);
471 if (reg_info_p->value_regs != nullptr)
472 continue; // Only expedite registers that are not contained in other registers.
474 RegisterValue reg_value;
475 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
479 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
480 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
486 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, ®_value);
488 register_object_sp->SetObject(std::to_string(reg_num),
489 std::make_shared<JSONString>(stream.GetString()));
492 return register_object_sp;
496 GetStopReasonString(StopReason stop_reason)
500 case eStopReasonTrace:
502 case eStopReasonBreakpoint:
504 case eStopReasonWatchpoint:
506 case eStopReasonSignal:
508 case eStopReasonException:
510 case eStopReasonExec:
512 case eStopReasonInstrumentation:
513 case eStopReasonInvalid:
514 case eStopReasonPlanComplete:
515 case eStopReasonThreadExiting:
516 case eStopReasonNone:
523 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged)
525 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
527 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
529 // Ensure we can get info on the given thread.
530 uint32_t thread_idx = 0;
531 for ( NativeThreadProtocolSP thread_sp;
532 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
536 lldb::tid_t tid = thread_sp->GetID();
538 // Grab the reason this thread stopped.
539 struct ThreadStopInfo tid_stop_info;
540 std::string description;
541 if (!thread_sp->GetStopReason (tid_stop_info, description))
544 const int signum = tid_stop_info.details.signal.signo;
547 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
552 tid_stop_info.reason,
553 tid_stop_info.details.exception.type);
556 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
557 threads_array_sp->AppendObject(thread_obj_sp);
559 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp, abridged))
560 thread_obj_sp->SetObject("registers", registers_sp);
562 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
564 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
566 const std::string thread_name = thread_sp->GetName ();
567 if (! thread_name.empty())
568 thread_obj_sp->SetObject("name", std::make_shared<JSONString>(thread_name));
570 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
571 thread_obj_sp->SetObject("reason", std::make_shared<JSONString>(stop_reason_str));
573 if (! description.empty())
574 thread_obj_sp->SetObject("description", std::make_shared<JSONString>(description));
576 if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
578 thread_obj_sp->SetObject("metype",
579 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
581 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
582 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
584 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
585 tid_stop_info.details.exception.data[i]));
587 thread_obj_sp->SetObject("medata", medata_array_sp);
590 // TODO: Expedite interesting regions of inferior memory
593 return threads_array_sp;
596 GDBRemoteCommunication::PacketResult
597 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
599 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
601 // Ensure we have a debugged process.
602 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
603 return SendErrorResponse (50);
606 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
607 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
609 // Ensure we can get info on the given thread.
610 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
612 return SendErrorResponse (51);
614 // Grab the reason this thread stopped.
615 struct ThreadStopInfo tid_stop_info;
616 std::string description;
617 if (!thread_sp->GetStopReason (tid_stop_info, description))
618 return SendErrorResponse (52);
620 // FIXME implement register handling for exec'd inferiors.
621 // if (tid_stop_info.reason == eStopReasonExec)
623 // const bool force = true;
624 // InitializeRegisters(force);
627 StreamString response;
628 // Output the T packet with the thread
629 response.PutChar ('T');
630 int signum = tid_stop_info.details.signal.signo;
633 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
635 m_debugged_process_sp->GetID (),
638 tid_stop_info.reason,
639 tid_stop_info.details.exception.type);
642 // Print the signal number.
643 response.PutHex8 (signum & 0xff);
646 response.Printf ("thread:%" PRIx64 ";", tid);
648 // Include the thread name if there is one.
649 const std::string thread_name = thread_sp->GetName ();
650 if (!thread_name.empty ())
652 size_t thread_name_len = thread_name.length ();
654 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
656 response.PutCString ("name:");
657 response.PutCString (thread_name.c_str ());
661 // The thread name contains special chars, send as hex bytes.
662 response.PutCString ("hexname:");
663 response.PutCStringAsRawHex8 (thread_name.c_str ());
665 response.PutChar (';');
668 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
669 // will send all thread IDs back in the "threads" key whose value is
670 // a list of hex thread IDs separated by commas:
671 // "threads:10a,10b,10c;"
672 // This will save the debugger from having to send a pair of qfThreadInfo
673 // and qsThreadInfo packets, but it also might take a lot of room in the
674 // stop reply packet, so it must be enabled only on systems where there
675 // are no limits on packet lengths.
676 if (m_list_threads_in_stop_reply)
678 response.PutCString ("threads:");
680 uint32_t thread_index = 0;
681 NativeThreadProtocolSP listed_thread_sp;
682 for (listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); listed_thread_sp; ++thread_index, listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
684 if (thread_index > 0)
685 response.PutChar (',');
686 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
688 response.PutChar (';');
690 // Include JSON info that describes the stop reason for any threads
691 // that actually have stop reasons. We use the new "jstopinfo" key
692 // whose values is hex ascii JSON that contains the thread IDs
693 // thread stop info only for threads that have stop reasons. Only send
694 // this if we have more than one thread otherwise this packet has all
695 // the info it needs.
696 if (thread_index > 0)
698 const bool threads_with_valid_stop_info_only = true;
699 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
700 threads_with_valid_stop_info_only);
703 response.PutCString("jstopinfo:");
704 StreamString unescaped_response;
705 threads_info_sp->Write(unescaped_response);
706 response.PutCStringAsRawHex8(unescaped_response.GetData());
707 response.PutChar(';');
710 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a jstopinfo field for pid %" PRIu64,
711 __FUNCTION__, m_debugged_process_sp->GetID());
717 // Expedite registers.
720 // Grab the register context.
721 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
724 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
725 const RegisterSet *reg_set_p;
726 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
729 log->Printf ("GDBRemoteCommunicationServerLLGS::%s expediting registers from set '%s' (registers set count: %zu)", __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", reg_set_p->num_registers);
731 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
733 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
734 if (reg_info_p == nullptr)
737 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get register info for register set '%s', register index %" PRIu32, __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", *reg_num_p);
739 else if (reg_info_p->value_regs == nullptr)
741 // Only expediate registers that are not contained in other registers.
742 RegisterValue reg_value;
743 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
744 if (error.Success ())
746 response.Printf ("%.02x:", *reg_num_p);
747 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, ®_value);
748 response.PutChar (';');
753 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__, reg_info_p->name ? reg_info_p->name : "<unnamed-register>", *reg_num_p, error.AsCString ());
761 const char* reason_str = GetStopReasonString(tid_stop_info.reason);
762 if (reason_str != nullptr)
764 response.Printf ("reason:%s;", reason_str);
767 if (!description.empty())
769 // Description may contains special chars, send as hex bytes.
770 response.PutCString ("description:");
771 response.PutCStringAsRawHex8 (description.c_str ());
772 response.PutChar (';');
774 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
776 response.PutCString ("metype:");
777 response.PutHex64 (tid_stop_info.details.exception.type);
778 response.PutCString (";mecount:");
779 response.PutHex32 (tid_stop_info.details.exception.data_count);
780 response.PutChar (';');
782 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
784 response.PutCString ("medata:");
785 response.PutHex64 (tid_stop_info.details.exception.data[i]);
786 response.PutChar (';');
790 return SendPacketNoLock (response.GetData(), response.GetSize());
794 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (NativeProcessProtocol *process)
796 assert (process && "process cannot be NULL");
798 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
800 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
802 PacketResult result = SendStopReasonForState(StateType::eStateExited);
803 if (result != PacketResult::Success)
806 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
809 // Close the pipe to the inferior terminal i/o if we launched it
811 MaybeCloseInferiorTerminalConnection ();
813 // We are ready to exit the debug monitor.
818 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (NativeProcessProtocol *process)
820 assert (process && "process cannot be NULL");
822 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
824 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
826 // Send the stop reason unless this is the stop after the
828 switch (m_inferior_prev_state)
830 case eStateLaunching:
831 case eStateAttaching:
832 // Don't send anything per debugserver behavior.
835 // In all other cases, send the stop reason.
836 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
837 if (result != PacketResult::Success)
840 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
847 GDBRemoteCommunicationServerLLGS::ProcessStateChanged (NativeProcessProtocol *process, lldb::StateType state)
849 assert (process && "process cannot be NULL");
850 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
853 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
856 StateAsCString (state));
861 case StateType::eStateRunning:
862 StartSTDIOForwarding();
865 case StateType::eStateStopped:
866 // Make sure we get all of the pending stdout/stderr from the inferior
867 // and send it to the lldb host before we send the state change
870 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) does not
871 // interfere with our protocol.
872 StopSTDIOForwarding();
873 HandleInferiorState_Stopped (process);
876 case StateType::eStateExited:
879 StopSTDIOForwarding();
880 HandleInferiorState_Exited (process);
886 log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
889 StateAsCString (state));
894 // Remember the previous state reported to us.
895 m_inferior_prev_state = state;
899 GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
901 ClearProcessSpecificData ();
905 GDBRemoteCommunicationServerLLGS::DataAvailableCallback ()
907 Log *log (GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
909 if (! m_handshake_completed)
911 if (! HandshakeWithClient())
914 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with client failed, exiting",
916 m_mainloop.RequestTermination();
919 m_handshake_completed = true;
922 bool interrupt = false;
927 const PacketResult result = GetPacketAndSendResponse (0, error, interrupt, done);
928 if (result == PacketResult::ErrorReplyTimeout)
929 break; // No more packets in the queue
931 if ((result != PacketResult::Success))
934 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet failed: %s",
935 __FUNCTION__, error.AsCString());
936 m_mainloop.RequestTermination();
943 GDBRemoteCommunicationServerLLGS::InitializeConnection (std::unique_ptr<Connection> &&connection)
945 IOObjectSP read_object_sp = connection->GetReadObject();
946 GDBRemoteCommunicationServer::SetConnection(connection.release());
949 m_network_handle_up = m_mainloop.RegisterReadObject(read_object_sp,
950 [this] (MainLoopBase &) { DataAvailableCallback(); }, error);
954 GDBRemoteCommunication::PacketResult
955 GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
957 if ((buffer == nullptr) || (len == 0))
960 return PacketResult::Success;
963 StreamString response;
964 response.PutChar ('O');
965 response.PutBytesAsRawHex8 (buffer, len);
967 return SendPacketNoLock (response.GetData (), response.GetSize ());
971 GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
975 // Set up the reading/handling of process I/O
976 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
979 error.SetErrorString ("failed to create ConnectionFileDescriptor");
983 m_stdio_communication.SetCloseOnEOF (false);
984 m_stdio_communication.SetConnection (conn_up.release());
985 if (!m_stdio_communication.IsConnected ())
987 error.SetErrorString ("failed to set connection for inferior I/O communication");
995 GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding()
997 // Don't forward if not connected (e.g. when attaching).
998 if (! m_stdio_communication.IsConnected())
1001 // llgs local-process debugging may specify PTY paths, which will make these
1002 // file actions non-null
1003 // process launch -e/o will also make these file actions non-null
1004 // nullptr means that the traffic is expected to flow over gdb-remote protocol
1005 if ( m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) &&
1006 m_process_launch_info.GetFileActionForFD(STDERR_FILENO))
1010 lldbassert(! m_stdio_handle_up);
1011 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1012 m_stdio_communication.GetConnection()->GetReadObject(),
1013 [this] (MainLoopBase &) { SendProcessOutput(); }, error);
1015 if (! m_stdio_handle_up)
1017 // Not much we can do about the failure. Log it and continue without forwarding.
1018 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1019 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio forwarding: %s",
1020 __FUNCTION__, error.AsCString());
1025 GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
1027 m_stdio_handle_up.reset();
1031 GDBRemoteCommunicationServerLLGS::SendProcessOutput()
1034 ConnectionStatus status;
1038 size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1041 case eConnectionStatusSuccess:
1042 SendONotification(buffer, bytes_read);
1044 case eConnectionStatusLostConnection:
1045 case eConnectionStatusEndOfFile:
1046 case eConnectionStatusError:
1047 case eConnectionStatusNoConnection:
1048 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1049 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
1050 m_stdio_handle_up.reset();
1053 case eConnectionStatusInterrupted:
1054 case eConnectionStatusTimedOut:
1060 GDBRemoteCommunication::PacketResult
1061 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1063 // Fail if we don't have a current process.
1064 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1065 return SendErrorResponse (68);
1067 lldb::pid_t pid = m_debugged_process_sp->GetID ();
1069 if (pid == LLDB_INVALID_PROCESS_ID)
1070 return SendErrorResponse (1);
1072 ProcessInstanceInfo proc_info;
1073 if (!Host::GetProcessInfo (pid, proc_info))
1074 return SendErrorResponse (1);
1076 StreamString response;
1077 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1078 return SendPacketNoLock (response.GetData (), response.GetSize ());
1081 GDBRemoteCommunication::PacketResult
1082 GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
1084 // Fail if we don't have a current process.
1085 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1086 return SendErrorResponse (68);
1088 // Make sure we set the current thread so g and p packets return
1089 // the data the gdb will expect.
1090 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1091 SetCurrentThreadID (tid);
1093 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1095 return SendErrorResponse (69);
1097 StreamString response;
1098 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1100 return SendPacketNoLock (response.GetData(), response.GetSize());
1103 GDBRemoteCommunication::PacketResult
1104 GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1106 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1108 StopSTDIOForwarding();
1110 if (! m_debugged_process_sp)
1113 log->Printf("GDBRemoteCommunicationServerLLGS::%s No debugged process found.", __FUNCTION__);
1114 return PacketResult::Success;
1117 Error error = m_debugged_process_sp->Kill();
1118 if (error.Fail() && log)
1119 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged process %" PRIu64 ": %s",
1120 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1122 // No OK response for kill packet.
1123 // return SendOKResponse ();
1124 return PacketResult::Success;
1127 GDBRemoteCommunication::PacketResult
1128 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1130 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1131 if (packet.GetU32(0))
1132 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1134 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1135 return SendOKResponse ();
1138 GDBRemoteCommunication::PacketResult
1139 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1141 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1143 packet.GetHexByteString (path);
1144 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1145 return SendOKResponse ();
1148 GDBRemoteCommunication::PacketResult
1149 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1151 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1154 StreamString response;
1155 response.PutCStringAsRawHex8(working_dir.GetCString());
1156 return SendPacketNoLock(response.GetData(), response.GetSize());
1159 return SendErrorResponse(14);
1162 GDBRemoteCommunication::PacketResult
1163 GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1165 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1167 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1169 // Ensure we have a native process.
1170 if (!m_debugged_process_sp)
1173 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1174 return SendErrorResponse (0x36);
1177 // Pull out the signal number.
1178 packet.SetFilePos (::strlen ("C"));
1179 if (packet.GetBytesLeft () < 1)
1181 // Shouldn't be using a C without a signal.
1182 return SendIllFormedResponse (packet, "C packet specified without signal.");
1184 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1185 if (signo == std::numeric_limits<uint32_t>::max ())
1186 return SendIllFormedResponse (packet, "failed to parse signal number");
1188 // Handle optional continue address.
1189 if (packet.GetBytesLeft () > 0)
1191 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1192 if (*packet.Peek () == ';')
1193 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1195 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1198 ResumeActionList resume_actions (StateType::eStateRunning, 0);
1201 // We have two branches: what to do if a continue thread is specified (in which case we target
1202 // sending the signal to that thread), or when we don't have a continue thread set (in which
1203 // case we send a signal to the process).
1205 // TODO discuss with Greg Clayton, make sure this makes sense.
1207 lldb::tid_t signal_tid = GetContinueThreadID ();
1208 if (signal_tid != LLDB_INVALID_THREAD_ID)
1210 // The resume action for the continue thread (or all threads if a continue thread is not set).
1211 ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
1213 // Add the action for the continue thread (or all threads when the continue thread isn't present).
1214 resume_actions.Append (action);
1218 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1219 error = m_debugged_process_sp->Signal (signo);
1223 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1225 m_debugged_process_sp->GetID (),
1226 error.AsCString ());
1228 return SendErrorResponse (0x52);
1232 // Resume the threads.
1233 error = m_debugged_process_sp->Resume (resume_actions);
1237 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1239 m_debugged_process_sp->GetID (),
1240 error.AsCString ());
1242 return SendErrorResponse (0x38);
1245 // Don't send an "OK" packet; response is the stopped/exited message.
1246 return PacketResult::Success;
1249 GDBRemoteCommunication::PacketResult
1250 GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1252 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1254 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1256 packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1258 // For now just support all continue.
1259 const bool has_continue_address = (packet.GetBytesLeft () > 0);
1260 if (has_continue_address)
1263 log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1264 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1267 // Ensure we have a native process.
1268 if (!m_debugged_process_sp)
1271 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1272 return SendErrorResponse (0x36);
1275 // Build the ResumeActionList
1276 ResumeActionList actions (StateType::eStateRunning, 0);
1278 Error error = m_debugged_process_sp->Resume (actions);
1283 log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1285 m_debugged_process_sp->GetID (),
1286 error.AsCString ());
1288 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1292 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1294 // No response required from continue.
1295 return PacketResult::Success;
1298 GDBRemoteCommunication::PacketResult
1299 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1301 StreamString response;
1302 response.Printf("vCont;c;C;s;S");
1304 return SendPacketNoLock(response.GetData(), response.GetSize());
1307 GDBRemoteCommunication::PacketResult
1308 GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1310 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1312 log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1314 packet.SetFilePos (::strlen ("vCont"));
1316 if (packet.GetBytesLeft() == 0)
1319 log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1320 return SendIllFormedResponse (packet, "Missing action from vCont package");
1323 // Check if this is all continue (no options or ";c").
1324 if (::strcmp (packet.Peek (), ";c") == 0)
1326 // Move past the ';', then do a simple 'c'.
1327 packet.SetFilePos (packet.GetFilePos () + 1);
1328 return Handle_c (packet);
1330 else if (::strcmp (packet.Peek (), ";s") == 0)
1332 // Move past the ';', then do a simple 's'.
1333 packet.SetFilePos (packet.GetFilePos () + 1);
1334 return Handle_s (packet);
1337 // Ensure we have a native process.
1338 if (!m_debugged_process_sp)
1341 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1342 return SendErrorResponse (0x36);
1345 ResumeActionList thread_actions;
1347 while (packet.GetBytesLeft () && *packet.Peek () == ';')
1349 // Skip the semi-colon.
1352 // Build up the thread action.
1353 ResumeAction thread_action;
1354 thread_action.tid = LLDB_INVALID_THREAD_ID;
1355 thread_action.state = eStateInvalid;
1356 thread_action.signal = 0;
1358 const char action = packet.GetChar ();
1362 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1363 if (thread_action.signal == 0)
1364 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1369 thread_action.state = eStateRunning;
1373 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1374 if (thread_action.signal == 0)
1375 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1380 thread_action.state = eStateStepping;
1384 return SendIllFormedResponse (packet, "Unsupported vCont action");
1388 // Parse out optional :{thread-id} value.
1389 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1391 // Consume the separator.
1394 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1395 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1396 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1399 thread_actions.Append (thread_action);
1402 Error error = m_debugged_process_sp->Resume (thread_actions);
1407 log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1409 m_debugged_process_sp->GetID (),
1410 error.AsCString ());
1412 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1416 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1418 // No response required from vCont.
1419 return PacketResult::Success;
1423 GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1425 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1427 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1429 m_current_tid = tid;
1430 if (m_debugged_process_sp)
1431 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1435 GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1437 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1439 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1441 m_continue_tid = tid;
1444 GDBRemoteCommunication::PacketResult
1445 GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1447 // Handle the $? gdbremote command.
1449 // If no process, indicate error
1450 if (!m_debugged_process_sp)
1451 return SendErrorResponse (02);
1453 return SendStopReasonForState (m_debugged_process_sp->GetState());
1456 GDBRemoteCommunication::PacketResult
1457 GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
1459 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1461 switch (process_state)
1463 case eStateAttaching:
1464 case eStateLaunching:
1466 case eStateStepping:
1467 case eStateDetached:
1468 // NOTE: gdb protocol doc looks like it should return $OK
1469 // when everything is running (i.e. no stopped result).
1470 return PacketResult::Success; // Ignore
1472 case eStateSuspended:
1476 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1477 // Make sure we set the current thread so g and p packets return
1478 // the data the gdb will expect.
1479 SetCurrentThreadID (tid);
1480 return SendStopReplyPacketForThread (tid);
1484 case eStateUnloaded:
1486 return SendWResponse(m_debugged_process_sp.get());
1491 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1493 m_debugged_process_sp->GetID (),
1494 StateAsCString (process_state));
1499 return SendErrorResponse (0);
1502 GDBRemoteCommunication::PacketResult
1503 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1505 // Fail if we don't have a current process.
1506 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1507 return SendErrorResponse (68);
1509 // Ensure we have a thread.
1510 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1512 return SendErrorResponse (69);
1514 // Get the register context for the first thread.
1515 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1516 if (!reg_context_sp)
1517 return SendErrorResponse (69);
1519 // Parse out the register number from the request.
1520 packet.SetFilePos (strlen("qRegisterInfo"));
1521 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1522 if (reg_index == std::numeric_limits<uint32_t>::max ())
1523 return SendErrorResponse (69);
1525 // Return the end of registers response if we've iterated one past the end of the register set.
1526 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1527 return SendErrorResponse (69);
1529 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1531 return SendErrorResponse (69);
1533 // Build the reginfos response.
1534 StreamGDBRemote response;
1536 response.PutCString ("name:");
1537 response.PutCString (reg_info->name);
1538 response.PutChar (';');
1540 if (reg_info->alt_name && reg_info->alt_name[0])
1542 response.PutCString ("alt-name:");
1543 response.PutCString (reg_info->alt_name);
1544 response.PutChar (';');
1547 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1549 switch (reg_info->encoding)
1551 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
1552 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
1553 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1554 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
1558 switch (reg_info->format)
1560 case eFormatBinary: response.PutCString ("format:binary;"); break;
1561 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
1562 case eFormatHex: response.PutCString ("format:hex;"); break;
1563 case eFormatFloat: response.PutCString ("format:float;"); break;
1564 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
1565 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
1566 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
1567 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
1568 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
1569 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
1570 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1571 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1575 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1576 if (register_set_name)
1578 response.PutCString ("set:");
1579 response.PutCString (register_set_name);
1580 response.PutChar (';');
1583 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
1584 response.Printf ("ehframe:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1586 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1587 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1589 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1591 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
1592 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
1593 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
1594 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
1595 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
1596 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
1597 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
1598 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
1599 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
1600 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
1601 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
1602 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
1603 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
1607 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1609 response.PutCString ("container-regs:");
1611 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1614 response.PutChar (',');
1615 response.Printf ("%" PRIx32, *reg_num);
1617 response.PutChar (';');
1620 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1622 response.PutCString ("invalidate-regs:");
1624 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1627 response.PutChar (',');
1628 response.Printf ("%" PRIx32, *reg_num);
1630 response.PutChar (';');
1633 if (reg_info->dynamic_size_dwarf_expr_bytes)
1635 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1636 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1637 for(uint32_t i = 0; i < dwarf_opcode_len; ++i)
1638 response.PutHex8 (reg_info->dynamic_size_dwarf_expr_bytes[i]);
1639 response.PutChar(';');
1641 return SendPacketNoLock(response.GetData(), response.GetSize());
1644 GDBRemoteCommunication::PacketResult
1645 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1647 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1649 // Fail if we don't have a current process.
1650 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1653 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1654 return SendOKResponse ();
1657 StreamGDBRemote response;
1658 response.PutChar ('m');
1661 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1663 NativeThreadProtocolSP thread_sp;
1664 uint32_t thread_index;
1665 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1667 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1670 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32 "(%s, tid=0x%" PRIx64 ")", __FUNCTION__, thread_index, thread_sp ? "is not null" : "null", thread_sp ? thread_sp->GetID () : LLDB_INVALID_THREAD_ID);
1671 if (thread_index > 0)
1672 response.PutChar(',');
1673 response.Printf ("%" PRIx64, thread_sp->GetID ());
1677 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1679 return SendPacketNoLock(response.GetData(), response.GetSize());
1682 GDBRemoteCommunication::PacketResult
1683 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1685 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1686 return SendPacketNoLock ("l", 1);
1689 GDBRemoteCommunication::PacketResult
1690 GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1692 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1694 // Parse out the register number from the request.
1695 packet.SetFilePos (strlen("p"));
1696 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1697 if (reg_index == std::numeric_limits<uint32_t>::max ())
1700 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1701 return SendErrorResponse (0x15);
1704 // Get the thread to use.
1705 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1709 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1710 return SendErrorResponse (0x15);
1713 // Get the thread's register context.
1714 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1715 if (!reg_context_sp)
1718 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1719 return SendErrorResponse (0x15);
1722 // Return the end of registers response if we've iterated one past the end of the register set.
1723 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1726 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1727 return SendErrorResponse (0x15);
1730 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1734 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1735 return SendErrorResponse (0x15);
1738 // Build the reginfos response.
1739 StreamGDBRemote response;
1741 // Retrieve the value
1742 RegisterValue reg_value;
1743 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1747 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1748 return SendErrorResponse (0x15);
1751 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1755 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1756 return SendErrorResponse (0x15);
1759 // FIXME flip as needed to get data in big/little endian format for this host.
1760 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1761 response.PutHex8 (data[i]);
1763 return SendPacketNoLock (response.GetData (), response.GetSize ());
1766 GDBRemoteCommunication::PacketResult
1767 GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1769 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1771 // Ensure there is more content.
1772 if (packet.GetBytesLeft () < 1)
1773 return SendIllFormedResponse (packet, "Empty P packet");
1775 // Parse out the register number from the request.
1776 packet.SetFilePos (strlen("P"));
1777 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1778 if (reg_index == std::numeric_limits<uint32_t>::max ())
1781 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1782 return SendErrorResponse (0x29);
1785 // Note debugserver would send an E30 here.
1786 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1787 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1789 // Get process architecture.
1790 ArchSpec process_arch;
1791 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1794 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1795 return SendErrorResponse (0x49);
1798 // Parse out the value.
1799 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1800 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1802 // Get the thread to use.
1803 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1807 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1808 return SendErrorResponse (0x28);
1811 // Get the thread's register context.
1812 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1813 if (!reg_context_sp)
1816 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1817 return SendErrorResponse (0x15);
1820 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1824 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1825 return SendErrorResponse (0x48);
1828 // Return the end of registers response if we've iterated one past the end of the register set.
1829 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1832 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1833 return SendErrorResponse (0x47);
1836 // The dwarf expression are evaluate on host site
1837 // which may cause register size to change
1838 // Hence the reg_size may not be same as reg_info->bytes_size
1839 if ((reg_size != reg_info->byte_size) && !(reg_info->dynamic_size_dwarf_expr_bytes))
1841 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1844 // Build the reginfos response.
1845 StreamGDBRemote response;
1847 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1848 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1852 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1853 return SendErrorResponse (0x32);
1856 return SendOKResponse();
1859 GDBRemoteCommunication::PacketResult
1860 GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1862 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1864 // Fail if we don't have a current process.
1865 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1868 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1869 return SendErrorResponse (0x15);
1872 // Parse out which variant of $H is requested.
1873 packet.SetFilePos (strlen("H"));
1874 if (packet.GetBytesLeft () < 1)
1877 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1878 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1881 const char h_variant = packet.GetChar ();
1892 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1893 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1896 // Parse out the thread number.
1897 // FIXME return a parse success/fail value. All values are valid here.
1898 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1900 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1901 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1903 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1907 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1908 return SendErrorResponse (0x15);
1912 // Now switch the given thread type.
1916 SetCurrentThreadID (tid);
1920 SetContinueThreadID (tid);
1924 assert (false && "unsupported $H variant - shouldn't get here");
1925 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1928 return SendOKResponse();
1931 GDBRemoteCommunication::PacketResult
1932 GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1934 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1936 // Fail if we don't have a current process.
1937 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1940 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1941 return SendErrorResponse (0x15);
1944 packet.SetFilePos (::strlen("I"));
1948 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1953 // write directly to stdin *this might block if stdin buffer is full*
1954 // TODO: enqueue this block in circular buffer and send window size to remote host
1955 ConnectionStatus status;
1957 m_stdio_communication.Write(tmp, read, status, &error);
1960 return SendErrorResponse (0x15);
1964 return SendOKResponse();
1967 GDBRemoteCommunication::PacketResult
1968 GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1970 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1972 // Fail if we don't have a current process.
1973 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1976 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1977 return SendErrorResponse (0x15);
1980 // Interrupt the process.
1981 Error error = m_debugged_process_sp->Interrupt ();
1986 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1988 m_debugged_process_sp->GetID (),
1989 error.AsCString ());
1991 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1995 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1997 // No response required from stop all.
1998 return PacketResult::Success;
2001 GDBRemoteCommunication::PacketResult
2002 GDBRemoteCommunicationServerLLGS::Handle_memory_read(StringExtractorGDBRemote &packet)
2004 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2006 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2009 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2010 return SendErrorResponse (0x15);
2013 // Parse out the memory address.
2014 packet.SetFilePos (strlen("m"));
2015 if (packet.GetBytesLeft() < 1)
2016 return SendIllFormedResponse(packet, "Too short m packet");
2018 // Read the address. Punting on validation.
2019 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2020 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2023 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2024 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2026 // Get # bytes to read.
2027 if (packet.GetBytesLeft() < 1)
2028 return SendIllFormedResponse(packet, "Length missing in m packet");
2030 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2031 if (byte_count == 0)
2034 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
2035 return SendOKResponse();
2038 // Allocate the response buffer.
2039 std::string buf(byte_count, '\0');
2041 return SendErrorResponse (0x78);
2044 // Retrieve the process memory.
2045 size_t bytes_read = 0;
2046 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
2050 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2051 return SendErrorResponse (0x08);
2054 if (bytes_read == 0)
2057 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, byte_count);
2058 return SendErrorResponse (0x08);
2061 StreamGDBRemote response;
2062 packet.SetFilePos(0);
2063 char kind = packet.GetChar('?');
2065 response.PutEscapedBytes(buf.data(), byte_count);
2068 assert(kind == 'm');
2069 for (size_t i = 0; i < bytes_read; ++i)
2070 response.PutHex8(buf[i]);
2073 return SendPacketNoLock(response.GetData(), response.GetSize());
2076 GDBRemoteCommunication::PacketResult
2077 GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2079 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2081 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2084 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2085 return SendErrorResponse (0x15);
2088 // Parse out the memory address.
2089 packet.SetFilePos (strlen("M"));
2090 if (packet.GetBytesLeft() < 1)
2091 return SendIllFormedResponse(packet, "Too short M packet");
2093 // Read the address. Punting on validation.
2094 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2095 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2098 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2099 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2101 // Get # bytes to read.
2102 if (packet.GetBytesLeft() < 1)
2103 return SendIllFormedResponse(packet, "Length missing in M packet");
2105 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2106 if (byte_count == 0)
2109 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2110 return PacketResult::Success;
2114 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2115 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2117 // Allocate the conversion buffer.
2118 std::vector<uint8_t> buf(byte_count, 0);
2120 return SendErrorResponse (0x78);
2122 // Convert the hex memory write contents to bytes.
2123 StreamGDBRemote response;
2124 const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
2125 if (convert_count != byte_count)
2128 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": asked to write %" PRIu64 " bytes, but only found %" PRIu64 " to convert.", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count, convert_count);
2129 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2132 // Write the process memory.
2133 size_t bytes_written = 0;
2134 Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
2138 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2139 return SendErrorResponse (0x09);
2142 if (bytes_written == 0)
2145 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count);
2146 return SendErrorResponse (0x09);
2149 return SendOKResponse ();
2152 GDBRemoteCommunication::PacketResult
2153 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2155 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2157 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2158 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
2159 // client only asks this when a process is being debugged.
2161 // Ensure we have a process running; otherwise, we can't figure this out
2162 // since we won't have a NativeProcessProtocol.
2163 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2166 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2167 return SendErrorResponse (0x15);
2170 // Test if we can get any region back when asking for the region around NULL.
2171 MemoryRegionInfo region_info;
2172 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2175 // We don't support memory region info collection for this NativeProcessProtocol.
2176 return SendUnimplementedResponse ("");
2179 return SendOKResponse();
2182 GDBRemoteCommunication::PacketResult
2183 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2185 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2187 // Ensure we have a process.
2188 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2191 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2192 return SendErrorResponse (0x15);
2195 // Parse out the memory address.
2196 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2197 if (packet.GetBytesLeft() < 1)
2198 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2200 // Read the address. Punting on validation.
2201 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2203 StreamGDBRemote response;
2205 // Get the memory region info for the target address.
2206 MemoryRegionInfo region_info;
2207 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2210 // Return the error message.
2212 response.PutCString ("error:");
2213 response.PutCStringAsRawHex8 (error.AsCString ());
2214 response.PutChar (';');
2218 // Range start and size.
2219 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2222 if (region_info.GetReadable () ||
2223 region_info.GetWritable () ||
2224 region_info.GetExecutable ())
2226 // Write permissions info.
2227 response.PutCString ("permissions:");
2229 if (region_info.GetReadable ())
2230 response.PutChar ('r');
2231 if (region_info.GetWritable ())
2232 response.PutChar('w');
2233 if (region_info.GetExecutable())
2234 response.PutChar ('x');
2236 response.PutChar (';');
2240 return SendPacketNoLock(response.GetData(), response.GetSize());
2243 GDBRemoteCommunication::PacketResult
2244 GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2246 // Ensure we have a process.
2247 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2249 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2251 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2252 return SendErrorResponse (0x15);
2255 // Parse out software or hardware breakpoint or watchpoint requested.
2256 packet.SetFilePos (strlen("Z"));
2257 if (packet.GetBytesLeft() < 1)
2258 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2260 bool want_breakpoint = true;
2261 bool want_hardware = false;
2262 uint32_t watch_flags = 0;
2264 const GDBStoppointType stoppoint_type =
2265 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2266 switch (stoppoint_type)
2268 case eBreakpointSoftware:
2269 want_hardware = false; want_breakpoint = true; break;
2270 case eBreakpointHardware:
2271 want_hardware = true; want_breakpoint = true; break;
2272 case eWatchpointWrite:
2274 want_hardware = true; want_breakpoint = false; break;
2275 case eWatchpointRead:
2277 want_hardware = true; want_breakpoint = false; break;
2278 case eWatchpointReadWrite:
2280 want_hardware = true; want_breakpoint = false; break;
2281 case eStoppointInvalid:
2282 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2286 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2287 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2289 // Parse out the stoppoint address.
2290 if (packet.GetBytesLeft() < 1)
2291 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2292 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2294 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2295 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2297 // Parse out the stoppoint size (i.e. size hint for opcode size).
2298 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2299 if (size == std::numeric_limits<uint32_t>::max ())
2300 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2302 if (want_breakpoint)
2304 // Try to set the breakpoint.
2305 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2306 if (error.Success ())
2307 return SendOKResponse ();
2308 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2310 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2311 " failed to set breakpoint: %s",
2313 m_debugged_process_sp->GetID (),
2314 error.AsCString ());
2315 return SendErrorResponse (0x09);
2319 // Try to set the watchpoint.
2320 const Error error = m_debugged_process_sp->SetWatchpoint (
2321 addr, size, watch_flags, want_hardware);
2322 if (error.Success ())
2323 return SendOKResponse ();
2324 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2326 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2327 " failed to set watchpoint: %s",
2329 m_debugged_process_sp->GetID (),
2330 error.AsCString ());
2331 return SendErrorResponse (0x09);
2335 GDBRemoteCommunication::PacketResult
2336 GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2338 // Ensure we have a process.
2339 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2341 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2343 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2344 return SendErrorResponse (0x15);
2347 // Parse out software or hardware breakpoint or watchpoint requested.
2348 packet.SetFilePos (strlen("z"));
2349 if (packet.GetBytesLeft() < 1)
2350 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2352 bool want_breakpoint = true;
2354 const GDBStoppointType stoppoint_type =
2355 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2356 switch (stoppoint_type)
2358 case eBreakpointHardware: want_breakpoint = true; break;
2359 case eBreakpointSoftware: want_breakpoint = true; break;
2360 case eWatchpointWrite: want_breakpoint = false; break;
2361 case eWatchpointRead: want_breakpoint = false; break;
2362 case eWatchpointReadWrite: want_breakpoint = false; break;
2364 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2368 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2369 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2371 // Parse out the stoppoint address.
2372 if (packet.GetBytesLeft() < 1)
2373 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2374 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2376 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2377 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2380 // Parse out the stoppoint size (i.e. size hint for opcode size).
2381 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2382 if (size == std::numeric_limits<uint32_t>::max ())
2383 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2386 if (want_breakpoint)
2388 // Try to clear the breakpoint.
2389 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2390 if (error.Success ())
2391 return SendOKResponse ();
2392 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2394 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2395 " failed to remove breakpoint: %s",
2397 m_debugged_process_sp->GetID (),
2398 error.AsCString ());
2399 return SendErrorResponse (0x09);
2403 // Try to clear the watchpoint.
2404 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2405 if (error.Success ())
2406 return SendOKResponse ();
2407 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2409 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2410 " failed to remove watchpoint: %s",
2412 m_debugged_process_sp->GetID (),
2413 error.AsCString ());
2414 return SendErrorResponse (0x09);
2418 GDBRemoteCommunication::PacketResult
2419 GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2421 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2423 // Ensure we have a process.
2424 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2427 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2428 return SendErrorResponse (0x32);
2431 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2432 // Bail out if we don't have a thread id.
2433 lldb::tid_t tid = GetContinueThreadID ();
2434 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2435 tid = GetCurrentThreadID ();
2436 if (tid == LLDB_INVALID_THREAD_ID)
2437 return SendErrorResponse (0x33);
2439 // Double check that we have such a thread.
2440 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2441 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2442 if (!thread_sp || thread_sp->GetID () != tid)
2443 return SendErrorResponse (0x33);
2445 // Create the step action for the given thread.
2446 ResumeAction action = { tid, eStateStepping, 0 };
2448 // Setup the actions list.
2449 ResumeActionList actions;
2450 actions.Append (action);
2452 // All other threads stop while we're single stepping a thread.
2453 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2454 Error error = m_debugged_process_sp->Resume (actions);
2458 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2459 return SendErrorResponse(0x49);
2462 // No response here - the stop or exit will come from the resulting action.
2463 return PacketResult::Success;
2466 GDBRemoteCommunication::PacketResult
2467 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2469 // *BSD impls should be able to do this too.
2470 #if defined(__linux__)
2471 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2473 // Parse out the offset.
2474 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2475 if (packet.GetBytesLeft () < 1)
2476 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2478 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2479 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2480 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2483 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2484 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2486 // Parse out the length.
2487 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2488 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2489 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2491 // Grab the auxv data if we need it.
2492 if (!m_active_auxv_buffer_sp)
2494 // Make sure we have a valid process.
2495 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2498 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2499 return SendErrorResponse (0x10);
2502 // Grab the auxv data.
2503 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2504 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2506 // Hmm, no auxv data, call that an error.
2508 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2509 m_active_auxv_buffer_sp.reset ();
2510 return SendErrorResponse (0x11);
2514 // FIXME find out if/how I lock the stream here.
2516 StreamGDBRemote response;
2517 bool done_with_buffer = false;
2519 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2521 // We have nothing left to send. Mark the buffer as complete.
2522 response.PutChar ('l');
2523 done_with_buffer = true;
2527 // Figure out how many bytes are available starting at the given offset.
2528 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2530 // Figure out how many bytes we're going to read.
2531 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2533 // Mark the response type according to whether we're reading the remainder of the auxv data.
2534 if (bytes_to_read >= bytes_remaining)
2536 // There will be nothing left to read after this
2537 response.PutChar ('l');
2538 done_with_buffer = true;
2542 // There will still be bytes to read after this request.
2543 response.PutChar ('m');
2546 // Now write the data in encoded binary form.
2547 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2550 if (done_with_buffer)
2551 m_active_auxv_buffer_sp.reset ();
2553 return SendPacketNoLock(response.GetData(), response.GetSize());
2555 return SendUnimplementedResponse ("not implemented on this platform");
2559 GDBRemoteCommunication::PacketResult
2560 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2562 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2564 // Move past packet name.
2565 packet.SetFilePos (strlen ("QSaveRegisterState"));
2567 // Get the thread to use.
2568 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2571 if (m_thread_suffix_supported)
2572 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2574 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2577 // Grab the register context for the thread.
2578 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2579 if (!reg_context_sp)
2582 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2583 return SendErrorResponse (0x15);
2586 // Save registers to a buffer.
2587 DataBufferSP register_data_sp;
2588 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2592 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2593 return SendErrorResponse (0x75);
2596 // Allocate a new save id.
2597 const uint32_t save_id = GetNextSavedRegistersID ();
2598 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2600 // Save the register data buffer under the save id.
2602 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2603 m_saved_registers_map[save_id] = register_data_sp;
2606 // Write the response.
2607 StreamGDBRemote response;
2608 response.Printf ("%" PRIu32, save_id);
2609 return SendPacketNoLock(response.GetData(), response.GetSize());
2612 GDBRemoteCommunication::PacketResult
2613 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2615 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2617 // Parse out save id.
2618 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2619 if (packet.GetBytesLeft () < 1)
2620 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2622 const uint32_t save_id = packet.GetU32 (0);
2626 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2627 return SendErrorResponse (0x76);
2630 // Get the thread to use.
2631 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2634 if (m_thread_suffix_supported)
2635 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2637 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2640 // Grab the register context for the thread.
2641 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2642 if (!reg_context_sp)
2645 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2646 return SendErrorResponse (0x15);
2649 // Retrieve register state buffer, then remove from the list.
2650 DataBufferSP register_data_sp;
2652 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2654 // Find the register set buffer for the given save id.
2655 auto it = m_saved_registers_map.find (save_id);
2656 if (it == m_saved_registers_map.end ())
2659 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
2660 return SendErrorResponse (0x77);
2662 register_data_sp = it->second;
2664 // Remove it from the map.
2665 m_saved_registers_map.erase (it);
2668 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2672 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2673 return SendErrorResponse (0x77);
2676 return SendOKResponse();
2679 GDBRemoteCommunication::PacketResult
2680 GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2682 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2684 // Consume the ';' after vAttach.
2685 packet.SetFilePos (strlen ("vAttach"));
2686 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2687 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2689 // Grab the PID to which we will attach (assume hex encoding).
2690 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2691 if (pid == LLDB_INVALID_PROCESS_ID)
2692 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2694 // Attempt to attach.
2696 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2698 Error error = AttachToProcess (pid);
2703 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2704 return SendErrorResponse (0x01);
2707 // Notify we attached by sending a stop packet.
2708 return SendStopReasonForState (m_debugged_process_sp->GetState ());
2711 GDBRemoteCommunication::PacketResult
2712 GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2714 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2716 StopSTDIOForwarding();
2718 // Fail if we don't have a current process.
2719 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2722 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2723 return SendErrorResponse (0x15);
2726 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2728 // Consume the ';' after D.
2729 packet.SetFilePos (1);
2730 if (packet.GetBytesLeft ())
2732 if (packet.GetChar () != ';')
2733 return SendIllFormedResponse (packet, "D missing expected ';'");
2735 // Grab the PID from which we will detach (assume hex encoding).
2736 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2737 if (pid == LLDB_INVALID_PROCESS_ID)
2738 return SendIllFormedResponse (packet, "D failed to parse the process id");
2741 if (pid != LLDB_INVALID_PROCESS_ID &&
2742 m_debugged_process_sp->GetID () != pid)
2744 return SendIllFormedResponse (packet, "Invalid pid");
2747 const Error error = m_debugged_process_sp->Detach ();
2751 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2752 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2753 return SendErrorResponse (0x01);
2756 return SendOKResponse ();
2759 GDBRemoteCommunication::PacketResult
2760 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2762 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2764 packet.SetFilePos (strlen("qThreadStopInfo"));
2765 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2766 if (tid == LLDB_INVALID_THREAD_ID)
2769 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2770 return SendErrorResponse (0x15);
2772 return SendStopReplyPacketForThread (tid);
2775 GDBRemoteCommunication::PacketResult
2776 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2778 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2780 // Ensure we have a debugged process.
2781 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2782 return SendErrorResponse (50);
2785 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2786 __FUNCTION__, m_debugged_process_sp->GetID());
2789 StreamString response;
2790 const bool threads_with_valid_stop_info_only = false;
2791 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2792 threads_with_valid_stop_info_only);
2793 if (! threads_array_sp)
2796 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2797 __FUNCTION__, m_debugged_process_sp->GetID());
2798 return SendErrorResponse(52);
2801 threads_array_sp->Write(response);
2802 StreamGDBRemote escaped_response;
2803 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2804 return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2807 GDBRemoteCommunication::PacketResult
2808 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2810 // Fail if we don't have a current process.
2811 if (!m_debugged_process_sp ||
2812 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2813 return SendErrorResponse (68);
2815 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2816 if (packet.GetBytesLeft() == 0)
2817 return SendOKResponse();
2818 if (packet.GetChar() != ':')
2819 return SendErrorResponse(67);
2821 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2822 StreamGDBRemote response;
2823 response.Printf ("num:%d;", num);
2824 return SendPacketNoLock(response.GetData(), response.GetSize());
2827 GDBRemoteCommunication::PacketResult
2828 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2830 // Fail if we don't have a current process.
2831 if (!m_debugged_process_sp ||
2832 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2833 return SendErrorResponse(67);
2835 packet.SetFilePos(strlen("qFileLoadAddress:"));
2836 if (packet.GetBytesLeft() == 0)
2837 return SendErrorResponse(68);
2839 std::string file_name;
2840 packet.GetHexByteString(file_name);
2842 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2843 Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2845 return SendErrorResponse(69);
2847 if (file_load_address == LLDB_INVALID_ADDRESS)
2848 return SendErrorResponse(1); // File not loaded
2850 StreamGDBRemote response;
2851 response.PutHex64(file_load_address);
2852 return SendPacketNoLock(response.GetData(), response.GetSize());
2856 GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2858 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2860 // Tell the stdio connection to shut down.
2861 if (m_stdio_communication.IsConnected())
2863 auto connection = m_stdio_communication.GetConnection();
2867 connection->Disconnect (&error);
2869 if (error.Success ())
2872 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2877 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2884 NativeThreadProtocolSP
2885 GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2887 NativeThreadProtocolSP thread_sp;
2889 // We have no thread if we don't have a process.
2890 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2893 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2894 // Use the current thread in that case.
2895 if (!m_thread_suffix_supported)
2897 const lldb::tid_t current_tid = GetCurrentThreadID ();
2898 if (current_tid == LLDB_INVALID_THREAD_ID)
2900 else if (current_tid == 0)
2903 return m_debugged_process_sp->GetThreadAtIndex (0);
2906 return m_debugged_process_sp->GetThreadByID (current_tid);
2909 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2911 // Parse out the ';'.
2912 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2915 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2919 if (!packet.GetBytesLeft ())
2922 // Parse out thread: portion.
2923 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2926 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2929 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2930 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2932 return m_debugged_process_sp->GetThreadByID (tid);
2938 GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2940 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2942 // Use whatever the debug process says is the current thread id
2943 // since the protocol either didn't specify or specified we want
2944 // any/all threads marked as the current thread.
2945 if (!m_debugged_process_sp)
2946 return LLDB_INVALID_THREAD_ID;
2947 return m_debugged_process_sp->GetCurrentThreadID ();
2949 // Use the specific current thread id set by the gdb remote protocol.
2950 return m_current_tid;
2954 GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2956 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2957 return m_next_saved_registers_id++;
2961 GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2963 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2965 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2967 // Clear any auxv cached data.
2968 // *BSD impls should be able to do this too.
2969 #if defined(__linux__)
2971 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2973 m_active_auxv_buffer_sp ? "was set" : "was not set");
2974 m_active_auxv_buffer_sp.reset ();
2979 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2980 const ArchSpec& arch)
2982 if (m_debugged_process_sp)
2985 if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2987 if (file_spec.Exists())
2992 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);