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 return SendPacketNoLock(response.GetData(), response.GetSize());
1636 GDBRemoteCommunication::PacketResult
1637 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1639 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1641 // Fail if we don't have a current process.
1642 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1645 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1646 return SendOKResponse ();
1649 StreamGDBRemote response;
1650 response.PutChar ('m');
1653 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1655 NativeThreadProtocolSP thread_sp;
1656 uint32_t thread_index;
1657 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1659 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1662 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);
1663 if (thread_index > 0)
1664 response.PutChar(',');
1665 response.Printf ("%" PRIx64, thread_sp->GetID ());
1669 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1671 return SendPacketNoLock(response.GetData(), response.GetSize());
1674 GDBRemoteCommunication::PacketResult
1675 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1677 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1678 return SendPacketNoLock ("l", 1);
1681 GDBRemoteCommunication::PacketResult
1682 GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1684 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1686 // Parse out the register number from the request.
1687 packet.SetFilePos (strlen("p"));
1688 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1689 if (reg_index == std::numeric_limits<uint32_t>::max ())
1692 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1693 return SendErrorResponse (0x15);
1696 // Get the thread to use.
1697 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1701 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1702 return SendErrorResponse (0x15);
1705 // Get the thread's register context.
1706 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1707 if (!reg_context_sp)
1710 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 ());
1711 return SendErrorResponse (0x15);
1714 // Return the end of registers response if we've iterated one past the end of the register set.
1715 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1718 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1719 return SendErrorResponse (0x15);
1722 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1726 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1727 return SendErrorResponse (0x15);
1730 // Build the reginfos response.
1731 StreamGDBRemote response;
1733 // Retrieve the value
1734 RegisterValue reg_value;
1735 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1739 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1740 return SendErrorResponse (0x15);
1743 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1747 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1748 return SendErrorResponse (0x15);
1751 // FIXME flip as needed to get data in big/little endian format for this host.
1752 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1753 response.PutHex8 (data[i]);
1755 return SendPacketNoLock (response.GetData (), response.GetSize ());
1758 GDBRemoteCommunication::PacketResult
1759 GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1761 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1763 // Ensure there is more content.
1764 if (packet.GetBytesLeft () < 1)
1765 return SendIllFormedResponse (packet, "Empty P packet");
1767 // Parse out the register number from the request.
1768 packet.SetFilePos (strlen("P"));
1769 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1770 if (reg_index == std::numeric_limits<uint32_t>::max ())
1773 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1774 return SendErrorResponse (0x29);
1777 // Note debugserver would send an E30 here.
1778 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1779 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1781 // Get process architecture.
1782 ArchSpec process_arch;
1783 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1786 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1787 return SendErrorResponse (0x49);
1790 // Parse out the value.
1791 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1792 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1794 // Get the thread to use.
1795 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1799 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1800 return SendErrorResponse (0x28);
1803 // Get the thread's register context.
1804 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1805 if (!reg_context_sp)
1808 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 ());
1809 return SendErrorResponse (0x15);
1812 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1816 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1817 return SendErrorResponse (0x48);
1820 // Return the end of registers response if we've iterated one past the end of the register set.
1821 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1824 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1825 return SendErrorResponse (0x47);
1828 if (reg_size != reg_info->byte_size)
1830 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1833 // Build the reginfos response.
1834 StreamGDBRemote response;
1836 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1837 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1841 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1842 return SendErrorResponse (0x32);
1845 return SendOKResponse();
1848 GDBRemoteCommunication::PacketResult
1849 GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1851 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1853 // Fail if we don't have a current process.
1854 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1857 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1858 return SendErrorResponse (0x15);
1861 // Parse out which variant of $H is requested.
1862 packet.SetFilePos (strlen("H"));
1863 if (packet.GetBytesLeft () < 1)
1866 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1867 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1870 const char h_variant = packet.GetChar ();
1881 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1882 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1885 // Parse out the thread number.
1886 // FIXME return a parse success/fail value. All values are valid here.
1887 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1889 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1890 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1892 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1896 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1897 return SendErrorResponse (0x15);
1901 // Now switch the given thread type.
1905 SetCurrentThreadID (tid);
1909 SetContinueThreadID (tid);
1913 assert (false && "unsupported $H variant - shouldn't get here");
1914 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1917 return SendOKResponse();
1920 GDBRemoteCommunication::PacketResult
1921 GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1923 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1925 // Fail if we don't have a current process.
1926 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1929 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1930 return SendErrorResponse (0x15);
1933 packet.SetFilePos (::strlen("I"));
1937 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1942 // write directly to stdin *this might block if stdin buffer is full*
1943 // TODO: enqueue this block in circular buffer and send window size to remote host
1944 ConnectionStatus status;
1946 m_stdio_communication.Write(tmp, read, status, &error);
1949 return SendErrorResponse (0x15);
1953 return SendOKResponse();
1956 GDBRemoteCommunication::PacketResult
1957 GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1959 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1961 // Fail if we don't have a current process.
1962 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1965 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1966 return SendErrorResponse (0x15);
1969 // Interrupt the process.
1970 Error error = m_debugged_process_sp->Interrupt ();
1975 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1977 m_debugged_process_sp->GetID (),
1978 error.AsCString ());
1980 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1984 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1986 // No response required from stop all.
1987 return PacketResult::Success;
1990 GDBRemoteCommunication::PacketResult
1991 GDBRemoteCommunicationServerLLGS::Handle_memory_read(StringExtractorGDBRemote &packet)
1993 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1995 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1998 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1999 return SendErrorResponse (0x15);
2002 // Parse out the memory address.
2003 packet.SetFilePos (strlen("m"));
2004 if (packet.GetBytesLeft() < 1)
2005 return SendIllFormedResponse(packet, "Too short m packet");
2007 // Read the address. Punting on validation.
2008 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2009 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2012 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2013 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2015 // Get # bytes to read.
2016 if (packet.GetBytesLeft() < 1)
2017 return SendIllFormedResponse(packet, "Length missing in m packet");
2019 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2020 if (byte_count == 0)
2023 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
2024 return SendOKResponse();
2027 // Allocate the response buffer.
2028 std::string buf(byte_count, '\0');
2030 return SendErrorResponse (0x78);
2033 // Retrieve the process memory.
2034 size_t bytes_read = 0;
2035 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
2039 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2040 return SendErrorResponse (0x08);
2043 if (bytes_read == 0)
2046 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);
2047 return SendErrorResponse (0x08);
2050 StreamGDBRemote response;
2051 packet.SetFilePos(0);
2052 char kind = packet.GetChar('?');
2054 response.PutEscapedBytes(buf.data(), byte_count);
2057 assert(kind == 'm');
2058 for (size_t i = 0; i < bytes_read; ++i)
2059 response.PutHex8(buf[i]);
2062 return SendPacketNoLock(response.GetData(), response.GetSize());
2065 GDBRemoteCommunication::PacketResult
2066 GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2068 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2070 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2073 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2074 return SendErrorResponse (0x15);
2077 // Parse out the memory address.
2078 packet.SetFilePos (strlen("M"));
2079 if (packet.GetBytesLeft() < 1)
2080 return SendIllFormedResponse(packet, "Too short M packet");
2082 // Read the address. Punting on validation.
2083 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2084 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2087 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2088 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2090 // Get # bytes to read.
2091 if (packet.GetBytesLeft() < 1)
2092 return SendIllFormedResponse(packet, "Length missing in M packet");
2094 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2095 if (byte_count == 0)
2098 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2099 return PacketResult::Success;
2103 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2104 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2106 // Allocate the conversion buffer.
2107 std::vector<uint8_t> buf(byte_count, 0);
2109 return SendErrorResponse (0x78);
2111 // Convert the hex memory write contents to bytes.
2112 StreamGDBRemote response;
2113 const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
2114 if (convert_count != byte_count)
2117 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);
2118 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2121 // Write the process memory.
2122 size_t bytes_written = 0;
2123 Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
2127 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2128 return SendErrorResponse (0x09);
2131 if (bytes_written == 0)
2134 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);
2135 return SendErrorResponse (0x09);
2138 return SendOKResponse ();
2141 GDBRemoteCommunication::PacketResult
2142 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2144 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2146 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2147 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
2148 // client only asks this when a process is being debugged.
2150 // Ensure we have a process running; otherwise, we can't figure this out
2151 // since we won't have a NativeProcessProtocol.
2152 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2155 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2156 return SendErrorResponse (0x15);
2159 // Test if we can get any region back when asking for the region around NULL.
2160 MemoryRegionInfo region_info;
2161 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2164 // We don't support memory region info collection for this NativeProcessProtocol.
2165 return SendUnimplementedResponse ("");
2168 return SendOKResponse();
2171 GDBRemoteCommunication::PacketResult
2172 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2174 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2176 // Ensure we have a process.
2177 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2180 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2181 return SendErrorResponse (0x15);
2184 // Parse out the memory address.
2185 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2186 if (packet.GetBytesLeft() < 1)
2187 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2189 // Read the address. Punting on validation.
2190 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2192 StreamGDBRemote response;
2194 // Get the memory region info for the target address.
2195 MemoryRegionInfo region_info;
2196 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2199 // Return the error message.
2201 response.PutCString ("error:");
2202 response.PutCStringAsRawHex8 (error.AsCString ());
2203 response.PutChar (';');
2207 // Range start and size.
2208 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2211 if (region_info.GetReadable () ||
2212 region_info.GetWritable () ||
2213 region_info.GetExecutable ())
2215 // Write permissions info.
2216 response.PutCString ("permissions:");
2218 if (region_info.GetReadable ())
2219 response.PutChar ('r');
2220 if (region_info.GetWritable ())
2221 response.PutChar('w');
2222 if (region_info.GetExecutable())
2223 response.PutChar ('x');
2225 response.PutChar (';');
2229 return SendPacketNoLock(response.GetData(), response.GetSize());
2232 GDBRemoteCommunication::PacketResult
2233 GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2235 // Ensure we have a process.
2236 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2238 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2240 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2241 return SendErrorResponse (0x15);
2244 // Parse out software or hardware breakpoint or watchpoint requested.
2245 packet.SetFilePos (strlen("Z"));
2246 if (packet.GetBytesLeft() < 1)
2247 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2249 bool want_breakpoint = true;
2250 bool want_hardware = false;
2251 uint32_t watch_flags = 0;
2253 const GDBStoppointType stoppoint_type =
2254 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2255 switch (stoppoint_type)
2257 case eBreakpointSoftware:
2258 want_hardware = false; want_breakpoint = true; break;
2259 case eBreakpointHardware:
2260 want_hardware = true; want_breakpoint = true; break;
2261 case eWatchpointWrite:
2263 want_hardware = true; want_breakpoint = false; break;
2264 case eWatchpointRead:
2266 want_hardware = true; want_breakpoint = false; break;
2267 case eWatchpointReadWrite:
2269 want_hardware = true; want_breakpoint = false; break;
2270 case eStoppointInvalid:
2271 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2275 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2276 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2278 // Parse out the stoppoint address.
2279 if (packet.GetBytesLeft() < 1)
2280 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2281 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2283 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2284 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2286 // Parse out the stoppoint size (i.e. size hint for opcode size).
2287 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2288 if (size == std::numeric_limits<uint32_t>::max ())
2289 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2291 if (want_breakpoint)
2293 // Try to set the breakpoint.
2294 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2295 if (error.Success ())
2296 return SendOKResponse ();
2297 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2299 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2300 " failed to set breakpoint: %s",
2302 m_debugged_process_sp->GetID (),
2303 error.AsCString ());
2304 return SendErrorResponse (0x09);
2308 // Try to set the watchpoint.
2309 const Error error = m_debugged_process_sp->SetWatchpoint (
2310 addr, size, watch_flags, want_hardware);
2311 if (error.Success ())
2312 return SendOKResponse ();
2313 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2315 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2316 " failed to set watchpoint: %s",
2318 m_debugged_process_sp->GetID (),
2319 error.AsCString ());
2320 return SendErrorResponse (0x09);
2324 GDBRemoteCommunication::PacketResult
2325 GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2327 // Ensure we have a process.
2328 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2330 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2332 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2333 return SendErrorResponse (0x15);
2336 // Parse out software or hardware breakpoint or watchpoint requested.
2337 packet.SetFilePos (strlen("z"));
2338 if (packet.GetBytesLeft() < 1)
2339 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2341 bool want_breakpoint = true;
2343 const GDBStoppointType stoppoint_type =
2344 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2345 switch (stoppoint_type)
2347 case eBreakpointHardware: want_breakpoint = true; break;
2348 case eBreakpointSoftware: want_breakpoint = true; break;
2349 case eWatchpointWrite: want_breakpoint = false; break;
2350 case eWatchpointRead: want_breakpoint = false; break;
2351 case eWatchpointReadWrite: want_breakpoint = false; break;
2353 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2357 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2358 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2360 // Parse out the stoppoint address.
2361 if (packet.GetBytesLeft() < 1)
2362 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2363 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2365 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2366 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2369 // Parse out the stoppoint size (i.e. size hint for opcode size).
2370 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2371 if (size == std::numeric_limits<uint32_t>::max ())
2372 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2375 if (want_breakpoint)
2377 // Try to clear the breakpoint.
2378 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2379 if (error.Success ())
2380 return SendOKResponse ();
2381 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2383 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2384 " failed to remove breakpoint: %s",
2386 m_debugged_process_sp->GetID (),
2387 error.AsCString ());
2388 return SendErrorResponse (0x09);
2392 // Try to clear the watchpoint.
2393 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2394 if (error.Success ())
2395 return SendOKResponse ();
2396 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2398 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2399 " failed to remove watchpoint: %s",
2401 m_debugged_process_sp->GetID (),
2402 error.AsCString ());
2403 return SendErrorResponse (0x09);
2407 GDBRemoteCommunication::PacketResult
2408 GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2410 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2412 // Ensure we have a process.
2413 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2416 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2417 return SendErrorResponse (0x32);
2420 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2421 // Bail out if we don't have a thread id.
2422 lldb::tid_t tid = GetContinueThreadID ();
2423 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2424 tid = GetCurrentThreadID ();
2425 if (tid == LLDB_INVALID_THREAD_ID)
2426 return SendErrorResponse (0x33);
2428 // Double check that we have such a thread.
2429 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2430 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2431 if (!thread_sp || thread_sp->GetID () != tid)
2432 return SendErrorResponse (0x33);
2434 // Create the step action for the given thread.
2435 ResumeAction action = { tid, eStateStepping, 0 };
2437 // Setup the actions list.
2438 ResumeActionList actions;
2439 actions.Append (action);
2441 // All other threads stop while we're single stepping a thread.
2442 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2443 Error error = m_debugged_process_sp->Resume (actions);
2447 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2448 return SendErrorResponse(0x49);
2451 // No response here - the stop or exit will come from the resulting action.
2452 return PacketResult::Success;
2455 GDBRemoteCommunication::PacketResult
2456 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2458 // *BSD impls should be able to do this too.
2459 #if defined(__linux__)
2460 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2462 // Parse out the offset.
2463 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2464 if (packet.GetBytesLeft () < 1)
2465 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2467 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2468 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2469 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2472 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2473 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2475 // Parse out the length.
2476 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2477 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2478 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2480 // Grab the auxv data if we need it.
2481 if (!m_active_auxv_buffer_sp)
2483 // Make sure we have a valid process.
2484 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2487 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2488 return SendErrorResponse (0x10);
2491 // Grab the auxv data.
2492 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2493 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2495 // Hmm, no auxv data, call that an error.
2497 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2498 m_active_auxv_buffer_sp.reset ();
2499 return SendErrorResponse (0x11);
2503 // FIXME find out if/how I lock the stream here.
2505 StreamGDBRemote response;
2506 bool done_with_buffer = false;
2508 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2510 // We have nothing left to send. Mark the buffer as complete.
2511 response.PutChar ('l');
2512 done_with_buffer = true;
2516 // Figure out how many bytes are available starting at the given offset.
2517 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2519 // Figure out how many bytes we're going to read.
2520 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2522 // Mark the response type according to whether we're reading the remainder of the auxv data.
2523 if (bytes_to_read >= bytes_remaining)
2525 // There will be nothing left to read after this
2526 response.PutChar ('l');
2527 done_with_buffer = true;
2531 // There will still be bytes to read after this request.
2532 response.PutChar ('m');
2535 // Now write the data in encoded binary form.
2536 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2539 if (done_with_buffer)
2540 m_active_auxv_buffer_sp.reset ();
2542 return SendPacketNoLock(response.GetData(), response.GetSize());
2544 return SendUnimplementedResponse ("not implemented on this platform");
2548 GDBRemoteCommunication::PacketResult
2549 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2551 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2553 // Move past packet name.
2554 packet.SetFilePos (strlen ("QSaveRegisterState"));
2556 // Get the thread to use.
2557 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2560 if (m_thread_suffix_supported)
2561 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2563 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2566 // Grab the register context for the thread.
2567 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2568 if (!reg_context_sp)
2571 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 ());
2572 return SendErrorResponse (0x15);
2575 // Save registers to a buffer.
2576 DataBufferSP register_data_sp;
2577 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2581 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2582 return SendErrorResponse (0x75);
2585 // Allocate a new save id.
2586 const uint32_t save_id = GetNextSavedRegistersID ();
2587 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2589 // Save the register data buffer under the save id.
2591 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2592 m_saved_registers_map[save_id] = register_data_sp;
2595 // Write the response.
2596 StreamGDBRemote response;
2597 response.Printf ("%" PRIu32, save_id);
2598 return SendPacketNoLock(response.GetData(), response.GetSize());
2601 GDBRemoteCommunication::PacketResult
2602 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2604 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2606 // Parse out save id.
2607 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2608 if (packet.GetBytesLeft () < 1)
2609 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2611 const uint32_t save_id = packet.GetU32 (0);
2615 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2616 return SendErrorResponse (0x76);
2619 // Get the thread to use.
2620 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2623 if (m_thread_suffix_supported)
2624 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2626 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2629 // Grab the register context for the thread.
2630 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2631 if (!reg_context_sp)
2634 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 ());
2635 return SendErrorResponse (0x15);
2638 // Retrieve register state buffer, then remove from the list.
2639 DataBufferSP register_data_sp;
2641 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2643 // Find the register set buffer for the given save id.
2644 auto it = m_saved_registers_map.find (save_id);
2645 if (it == m_saved_registers_map.end ())
2648 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);
2649 return SendErrorResponse (0x77);
2651 register_data_sp = it->second;
2653 // Remove it from the map.
2654 m_saved_registers_map.erase (it);
2657 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2661 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2662 return SendErrorResponse (0x77);
2665 return SendOKResponse();
2668 GDBRemoteCommunication::PacketResult
2669 GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2671 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2673 // Consume the ';' after vAttach.
2674 packet.SetFilePos (strlen ("vAttach"));
2675 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2676 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2678 // Grab the PID to which we will attach (assume hex encoding).
2679 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2680 if (pid == LLDB_INVALID_PROCESS_ID)
2681 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2683 // Attempt to attach.
2685 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2687 Error error = AttachToProcess (pid);
2692 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2693 return SendErrorResponse (0x01);
2696 // Notify we attached by sending a stop packet.
2697 return SendStopReasonForState (m_debugged_process_sp->GetState ());
2700 GDBRemoteCommunication::PacketResult
2701 GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2703 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2705 StopSTDIOForwarding();
2707 // Fail if we don't have a current process.
2708 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2711 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2712 return SendErrorResponse (0x15);
2715 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2717 // Consume the ';' after D.
2718 packet.SetFilePos (1);
2719 if (packet.GetBytesLeft ())
2721 if (packet.GetChar () != ';')
2722 return SendIllFormedResponse (packet, "D missing expected ';'");
2724 // Grab the PID from which we will detach (assume hex encoding).
2725 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2726 if (pid == LLDB_INVALID_PROCESS_ID)
2727 return SendIllFormedResponse (packet, "D failed to parse the process id");
2730 if (pid != LLDB_INVALID_PROCESS_ID &&
2731 m_debugged_process_sp->GetID () != pid)
2733 return SendIllFormedResponse (packet, "Invalid pid");
2736 const Error error = m_debugged_process_sp->Detach ();
2740 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2741 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2742 return SendErrorResponse (0x01);
2745 return SendOKResponse ();
2748 GDBRemoteCommunication::PacketResult
2749 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2751 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2753 packet.SetFilePos (strlen("qThreadStopInfo"));
2754 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2755 if (tid == LLDB_INVALID_THREAD_ID)
2758 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2759 return SendErrorResponse (0x15);
2761 return SendStopReplyPacketForThread (tid);
2764 GDBRemoteCommunication::PacketResult
2765 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2767 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2769 // Ensure we have a debugged process.
2770 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2771 return SendErrorResponse (50);
2774 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2775 __FUNCTION__, m_debugged_process_sp->GetID());
2778 StreamString response;
2779 const bool threads_with_valid_stop_info_only = false;
2780 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2781 threads_with_valid_stop_info_only);
2782 if (! threads_array_sp)
2785 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2786 __FUNCTION__, m_debugged_process_sp->GetID());
2787 return SendErrorResponse(52);
2790 threads_array_sp->Write(response);
2791 StreamGDBRemote escaped_response;
2792 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2793 return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2796 GDBRemoteCommunication::PacketResult
2797 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2799 // Fail if we don't have a current process.
2800 if (!m_debugged_process_sp ||
2801 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2802 return SendErrorResponse (68);
2804 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2805 if (packet.GetBytesLeft() == 0)
2806 return SendOKResponse();
2807 if (packet.GetChar() != ':')
2808 return SendErrorResponse(67);
2810 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2811 StreamGDBRemote response;
2812 response.Printf ("num:%d;", num);
2813 return SendPacketNoLock(response.GetData(), response.GetSize());
2816 GDBRemoteCommunication::PacketResult
2817 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2819 // Fail if we don't have a current process.
2820 if (!m_debugged_process_sp ||
2821 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2822 return SendErrorResponse(67);
2824 packet.SetFilePos(strlen("qFileLoadAddress:"));
2825 if (packet.GetBytesLeft() == 0)
2826 return SendErrorResponse(68);
2828 std::string file_name;
2829 packet.GetHexByteString(file_name);
2831 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2832 Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2834 return SendErrorResponse(69);
2836 if (file_load_address == LLDB_INVALID_ADDRESS)
2837 return SendErrorResponse(1); // File not loaded
2839 StreamGDBRemote response;
2840 response.PutHex64(file_load_address);
2841 return SendPacketNoLock(response.GetData(), response.GetSize());
2845 GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2847 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2849 // Tell the stdio connection to shut down.
2850 if (m_stdio_communication.IsConnected())
2852 auto connection = m_stdio_communication.GetConnection();
2856 connection->Disconnect (&error);
2858 if (error.Success ())
2861 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2866 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2873 NativeThreadProtocolSP
2874 GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2876 NativeThreadProtocolSP thread_sp;
2878 // We have no thread if we don't have a process.
2879 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2882 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2883 // Use the current thread in that case.
2884 if (!m_thread_suffix_supported)
2886 const lldb::tid_t current_tid = GetCurrentThreadID ();
2887 if (current_tid == LLDB_INVALID_THREAD_ID)
2889 else if (current_tid == 0)
2892 return m_debugged_process_sp->GetThreadAtIndex (0);
2895 return m_debugged_process_sp->GetThreadByID (current_tid);
2898 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2900 // Parse out the ';'.
2901 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2904 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2908 if (!packet.GetBytesLeft ())
2911 // Parse out thread: portion.
2912 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2915 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2918 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2919 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2921 return m_debugged_process_sp->GetThreadByID (tid);
2927 GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2929 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2931 // Use whatever the debug process says is the current thread id
2932 // since the protocol either didn't specify or specified we want
2933 // any/all threads marked as the current thread.
2934 if (!m_debugged_process_sp)
2935 return LLDB_INVALID_THREAD_ID;
2936 return m_debugged_process_sp->GetCurrentThreadID ();
2938 // Use the specific current thread id set by the gdb remote protocol.
2939 return m_current_tid;
2943 GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2945 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2946 return m_next_saved_registers_id++;
2950 GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2952 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2954 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2956 // Clear any auxv cached data.
2957 // *BSD impls should be able to do this too.
2958 #if defined(__linux__)
2960 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2962 m_active_auxv_buffer_sp ? "was set" : "was not set");
2963 m_active_auxv_buffer_sp.reset ();
2968 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2969 const ArchSpec& arch)
2971 if (m_debugged_process_sp)
2974 if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2976 if (file_spec.Exists())
2981 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);