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/Target/Platform.h"
43 #include "lldb/Host/common/NativeRegisterContext.h"
44 #include "lldb/Host/common/NativeProcessProtocol.h"
45 #include "lldb/Host/common/NativeThreadProtocol.h"
46 #include "lldb/Utility/JSON.h"
47 #include "lldb/Utility/LLDBAssert.h"
50 #include "Utility/StringExtractorGDBRemote.h"
51 #include "Utility/UriParser.h"
52 #include "ProcessGDBRemote.h"
53 #include "ProcessGDBRemoteLog.h"
56 using namespace lldb_private;
57 using namespace lldb_private::process_gdb_remote;
60 //----------------------------------------------------------------------
62 //----------------------------------------------------------------------
66 enum GDBRemoteServerError
68 // Set to the first unused error number in literal form below
70 eErrorNoProcess = eErrorFirst,
76 //----------------------------------------------------------------------
77 // GDBRemoteCommunicationServerLLGS constructor
78 //----------------------------------------------------------------------
79 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
80 const lldb::PlatformSP& platform_sp,
82 GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
83 m_platform_sp (platform_sp),
84 m_mainloop (mainloop),
85 m_current_tid (LLDB_INVALID_THREAD_ID),
86 m_continue_tid (LLDB_INVALID_THREAD_ID),
87 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
88 m_debugged_process_sp (),
89 m_stdio_communication ("process.stdio"),
90 m_inferior_prev_state (StateType::eStateInvalid),
91 m_active_auxv_buffer_sp (),
92 m_saved_registers_mutex (),
93 m_saved_registers_map (),
94 m_next_saved_registers_id (1),
95 m_handshake_completed (false)
98 RegisterPacketHandlers();
102 GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
105 &GDBRemoteCommunicationServerLLGS::Handle_C);
106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
107 &GDBRemoteCommunicationServerLLGS::Handle_c);
108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
109 &GDBRemoteCommunicationServerLLGS::Handle_D);
110 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
111 &GDBRemoteCommunicationServerLLGS::Handle_H);
112 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
113 &GDBRemoteCommunicationServerLLGS::Handle_I);
114 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
115 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
116 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
117 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
118 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
119 &GDBRemoteCommunicationServerLLGS::Handle_M);
120 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
121 &GDBRemoteCommunicationServerLLGS::Handle_p);
122 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
123 &GDBRemoteCommunicationServerLLGS::Handle_P);
124 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
125 &GDBRemoteCommunicationServerLLGS::Handle_qC);
126 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
127 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
128 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
129 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
130 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
131 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
132 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
134 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
135 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
136 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
137 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
138 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
139 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
140 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
141 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
142 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
143 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
144 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
146 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
147 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
148 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
149 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
150 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
154 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
155 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
156 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
157 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
158 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
159 &GDBRemoteCommunicationServerLLGS::Handle_s);
160 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
161 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
162 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
163 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
164 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
165 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
167 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
168 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_x,
169 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
170 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
171 &GDBRemoteCommunicationServerLLGS::Handle_Z);
172 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
173 &GDBRemoteCommunicationServerLLGS::Handle_z);
175 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
176 [this](StringExtractorGDBRemote packet,
182 return this->Handle_k (packet);
187 GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
189 if ((argc < 1) || !args || !args[0] || !args[0][0])
190 return Error ("%s: no process command line specified to launch", __FUNCTION__);
192 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
197 GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
199 m_process_launch_info.GetFlags ().Set (launch_flags);
204 GDBRemoteCommunicationServerLLGS::LaunchProcess ()
206 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
208 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
209 return Error ("%s: no process command line specified to launch", __FUNCTION__);
213 Mutex::Locker locker (m_debugged_process_mutex);
214 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
215 error = NativeProcessProtocol::Launch(
216 m_process_launch_info,
219 m_debugged_process_sp);
222 if (!error.Success ())
224 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
228 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
230 // llgs local-process debugging may specify PTY paths, which will make these
231 // file actions non-null
232 // process launch -i/e/o will also make these file actions non-null
233 // nullptr means that the traffic is expected to flow over gdb-remote protocol
235 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
236 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
237 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
240 // nullptr means it's not redirected to file or pty (in case of LLGS local)
241 // at least one of stdio will be transferred pty<->gdb-remote
242 // we need to give the pty master handle to this object to read and/or write
244 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
246 // Setup stdout/stderr mapping from inferior to $O
247 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
248 if (terminal_fd >= 0)
251 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
252 error = SetSTDIOFileDescriptor (terminal_fd);
259 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
265 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 ());
268 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
274 GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
278 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
280 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
282 // Before we try to attach, make sure we aren't already monitoring something else.
283 if (m_debugged_process_sp && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
284 return Error("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, m_debugged_process_sp->GetID());
287 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
288 if (!error.Success ())
290 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
294 // Setup stdout/stderr mapping from inferior.
295 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
296 if (terminal_fd >= 0)
299 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
300 error = SetSTDIOFileDescriptor (terminal_fd);
307 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
310 printf ("Attached to process %" PRIu64 "...\n", pid);
316 GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
318 assert (process && "process cannot be NULL");
319 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
322 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
325 StateAsCString (process->GetState ()));
329 GDBRemoteCommunication::PacketResult
330 GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
332 assert (process && "process cannot be NULL");
333 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
335 // send W notification
336 ExitType exit_type = ExitType::eExitTypeInvalid;
338 std::string exit_description;
340 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
344 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
346 StreamGDBRemote response;
347 response.PutChar ('E');
348 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
349 return SendPacketNoLock(response.GetData(), response.GetSize());
354 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 ());
356 StreamGDBRemote response;
358 char return_type_code;
361 case ExitType::eExitTypeExit:
362 return_type_code = 'W';
364 case ExitType::eExitTypeSignal:
365 return_type_code = 'X';
367 case ExitType::eExitTypeStop:
368 return_type_code = 'S';
370 case ExitType::eExitTypeInvalid:
371 return_type_code = 'E';
374 response.PutChar (return_type_code);
376 // POSIX exit status limited to unsigned 8 bits.
377 response.PutHex8 (return_code);
379 return SendPacketNoLock(response.GetData(), response.GetSize());
384 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
389 for (i = buf_size-1; i >= 0; i--)
390 response.PutHex8 (buf[i]);
394 for (i = 0; i < buf_size; i++)
395 response.PutHex8 (buf[i]);
400 WriteRegisterValueInHexFixedWidth (StreamString &response,
401 NativeRegisterContextSP ®_ctx_sp,
402 const RegisterInfo ®_info,
403 const RegisterValue *reg_value_p)
405 RegisterValue reg_value;
408 Error error = reg_ctx_sp->ReadRegister (®_info, reg_value);
409 if (error.Success ())
410 reg_value_p = ®_value;
416 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
420 // Zero-out any unreadable values.
421 if (reg_info.byte_size > 0)
423 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
424 AppendHexValue (response, zeros.data(), zeros.size(), false);
429 static JSONObject::SP
430 GetRegistersAsJSON(NativeThreadProtocol &thread, bool abridged)
432 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
434 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
438 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
440 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
441 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
442 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
445 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
447 uint32_t reg_num = *reg_num_p;
449 // Expedite only a couple of registers until we figure out why sending registers is
451 static const uint32_t k_expedited_registers[] = {
452 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM
454 static const uint32_t k_abridged_expedited_registers[] = {
455 LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM
458 for (const uint32_t *generic_reg_p = abridged ? k_abridged_expedited_registers : k_expedited_registers;
459 *generic_reg_p != LLDB_INVALID_REGNUM;
462 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, *generic_reg_p);
463 if (reg_num == LLDB_INVALID_REGNUM)
464 continue; // Target does not support the given register.
467 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
468 if (reg_info_p == nullptr)
471 log->Printf("%s failed to get register info for register index %" PRIu32,
472 __FUNCTION__, reg_num);
476 if (reg_info_p->value_regs != nullptr)
477 continue; // Only expedite registers that are not contained in other registers.
479 RegisterValue reg_value;
480 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
484 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
485 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
491 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, ®_value);
493 register_object_sp->SetObject(std::to_string(reg_num),
494 std::make_shared<JSONString>(stream.GetString()));
497 return register_object_sp;
501 GetStopReasonString(StopReason stop_reason)
505 case eStopReasonTrace:
507 case eStopReasonBreakpoint:
509 case eStopReasonWatchpoint:
511 case eStopReasonSignal:
513 case eStopReasonException:
515 case eStopReasonExec:
517 case eStopReasonInstrumentation:
518 case eStopReasonInvalid:
519 case eStopReasonPlanComplete:
520 case eStopReasonThreadExiting:
521 case eStopReasonNone:
528 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged)
530 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
532 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
534 // Ensure we can get info on the given thread.
535 uint32_t thread_idx = 0;
536 for ( NativeThreadProtocolSP thread_sp;
537 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
541 lldb::tid_t tid = thread_sp->GetID();
543 // Grab the reason this thread stopped.
544 struct ThreadStopInfo tid_stop_info;
545 std::string description;
546 if (!thread_sp->GetStopReason (tid_stop_info, description))
549 const int signum = tid_stop_info.details.signal.signo;
552 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
557 tid_stop_info.reason,
558 tid_stop_info.details.exception.type);
561 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
562 threads_array_sp->AppendObject(thread_obj_sp);
564 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp, abridged))
565 thread_obj_sp->SetObject("registers", registers_sp);
567 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
569 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
571 const std::string thread_name = thread_sp->GetName ();
572 if (! thread_name.empty())
573 thread_obj_sp->SetObject("name", std::make_shared<JSONString>(thread_name));
575 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
576 thread_obj_sp->SetObject("reason", std::make_shared<JSONString>(stop_reason_str));
578 if (! description.empty())
579 thread_obj_sp->SetObject("description", std::make_shared<JSONString>(description));
581 if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
583 thread_obj_sp->SetObject("metype",
584 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
586 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
587 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
589 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
590 tid_stop_info.details.exception.data[i]));
592 thread_obj_sp->SetObject("medata", medata_array_sp);
595 // TODO: Expedite interesting regions of inferior memory
598 return threads_array_sp;
601 GDBRemoteCommunication::PacketResult
602 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
604 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
606 // Ensure we have a debugged process.
607 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
608 return SendErrorResponse (50);
611 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
612 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
614 // Ensure we can get info on the given thread.
615 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
617 return SendErrorResponse (51);
619 // Grab the reason this thread stopped.
620 struct ThreadStopInfo tid_stop_info;
621 std::string description;
622 if (!thread_sp->GetStopReason (tid_stop_info, description))
623 return SendErrorResponse (52);
625 // FIXME implement register handling for exec'd inferiors.
626 // if (tid_stop_info.reason == eStopReasonExec)
628 // const bool force = true;
629 // InitializeRegisters(force);
632 StreamString response;
633 // Output the T packet with the thread
634 response.PutChar ('T');
635 int signum = tid_stop_info.details.signal.signo;
638 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
640 m_debugged_process_sp->GetID (),
643 tid_stop_info.reason,
644 tid_stop_info.details.exception.type);
647 // Print the signal number.
648 response.PutHex8 (signum & 0xff);
651 response.Printf ("thread:%" PRIx64 ";", tid);
653 // Include the thread name if there is one.
654 const std::string thread_name = thread_sp->GetName ();
655 if (!thread_name.empty ())
657 size_t thread_name_len = thread_name.length ();
659 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
661 response.PutCString ("name:");
662 response.PutCString (thread_name.c_str ());
666 // The thread name contains special chars, send as hex bytes.
667 response.PutCString ("hexname:");
668 response.PutCStringAsRawHex8 (thread_name.c_str ());
670 response.PutChar (';');
673 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
674 // will send all thread IDs back in the "threads" key whose value is
675 // a list of hex thread IDs separated by commas:
676 // "threads:10a,10b,10c;"
677 // This will save the debugger from having to send a pair of qfThreadInfo
678 // and qsThreadInfo packets, but it also might take a lot of room in the
679 // stop reply packet, so it must be enabled only on systems where there
680 // are no limits on packet lengths.
681 if (m_list_threads_in_stop_reply)
683 response.PutCString ("threads:");
685 uint32_t thread_index = 0;
686 NativeThreadProtocolSP listed_thread_sp;
687 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))
689 if (thread_index > 0)
690 response.PutChar (',');
691 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
693 response.PutChar (';');
695 // Include JSON info that describes the stop reason for any threads
696 // that actually have stop reasons. We use the new "jstopinfo" key
697 // whose values is hex ascii JSON that contains the thread IDs
698 // thread stop info only for threads that have stop reasons. Only send
699 // this if we have more than one thread otherwise this packet has all
700 // the info it needs.
701 if (thread_index > 0)
703 const bool threads_with_valid_stop_info_only = true;
704 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
705 threads_with_valid_stop_info_only);
708 response.PutCString("jstopinfo:");
709 StreamString unescaped_response;
710 threads_info_sp->Write(unescaped_response);
711 response.PutCStringAsRawHex8(unescaped_response.GetData());
712 response.PutChar(';');
715 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a jstopinfo field for pid %" PRIu64,
716 __FUNCTION__, m_debugged_process_sp->GetID());
722 // Expedite registers.
725 // Grab the register context.
726 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
729 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
730 const RegisterSet *reg_set_p;
731 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
734 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);
736 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
738 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
739 if (reg_info_p == nullptr)
742 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);
744 else if (reg_info_p->value_regs == nullptr)
746 // Only expediate registers that are not contained in other registers.
747 RegisterValue reg_value;
748 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
749 if (error.Success ())
751 response.Printf ("%.02x:", *reg_num_p);
752 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, ®_value);
753 response.PutChar (';');
758 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 ());
766 const char* reason_str = GetStopReasonString(tid_stop_info.reason);
767 if (reason_str != nullptr)
769 response.Printf ("reason:%s;", reason_str);
772 if (!description.empty())
774 // Description may contains special chars, send as hex bytes.
775 response.PutCString ("description:");
776 response.PutCStringAsRawHex8 (description.c_str ());
777 response.PutChar (';');
779 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
781 response.PutCString ("metype:");
782 response.PutHex64 (tid_stop_info.details.exception.type);
783 response.PutCString (";mecount:");
784 response.PutHex32 (tid_stop_info.details.exception.data_count);
785 response.PutChar (';');
787 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
789 response.PutCString ("medata:");
790 response.PutHex64 (tid_stop_info.details.exception.data[i]);
791 response.PutChar (';');
795 return SendPacketNoLock (response.GetData(), response.GetSize());
799 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (NativeProcessProtocol *process)
801 assert (process && "process cannot be NULL");
803 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
805 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
807 PacketResult result = SendStopReasonForState(StateType::eStateExited);
808 if (result != PacketResult::Success)
811 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
814 // Close the pipe to the inferior terminal i/o if we launched it
816 MaybeCloseInferiorTerminalConnection ();
818 // We are ready to exit the debug monitor.
823 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (NativeProcessProtocol *process)
825 assert (process && "process cannot be NULL");
827 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
829 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
831 // Send the stop reason unless this is the stop after the
833 switch (m_inferior_prev_state)
835 case eStateLaunching:
836 case eStateAttaching:
837 // Don't send anything per debugserver behavior.
840 // In all other cases, send the stop reason.
841 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
842 if (result != PacketResult::Success)
845 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
852 GDBRemoteCommunicationServerLLGS::ProcessStateChanged (NativeProcessProtocol *process, lldb::StateType state)
854 assert (process && "process cannot be NULL");
855 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
858 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
861 StateAsCString (state));
866 case StateType::eStateRunning:
867 StartSTDIOForwarding();
870 case StateType::eStateStopped:
871 // Make sure we get all of the pending stdout/stderr from the inferior
872 // and send it to the lldb host before we send the state change
875 // Then stop the forwarding, so that any late output (see llvm.org/pr25652) does not
876 // interfere with our protocol.
877 StopSTDIOForwarding();
878 HandleInferiorState_Stopped (process);
881 case StateType::eStateExited:
884 StopSTDIOForwarding();
885 HandleInferiorState_Exited (process);
891 log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
894 StateAsCString (state));
899 // Remember the previous state reported to us.
900 m_inferior_prev_state = state;
904 GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
906 ClearProcessSpecificData ();
910 GDBRemoteCommunicationServerLLGS::DataAvailableCallback ()
912 Log *log (GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
914 if (! m_handshake_completed)
916 if (! HandshakeWithClient())
919 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with client failed, exiting",
921 m_mainloop.RequestTermination();
924 m_handshake_completed = true;
927 bool interrupt = false;
932 const PacketResult result = GetPacketAndSendResponse (0, error, interrupt, done);
933 if (result == PacketResult::ErrorReplyTimeout)
934 break; // No more packets in the queue
936 if ((result != PacketResult::Success))
939 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet failed: %s",
940 __FUNCTION__, error.AsCString());
941 m_mainloop.RequestTermination();
948 GDBRemoteCommunicationServerLLGS::InitializeConnection (std::unique_ptr<Connection> &&connection)
950 IOObjectSP read_object_sp = connection->GetReadObject();
951 GDBRemoteCommunicationServer::SetConnection(connection.release());
954 m_network_handle_up = m_mainloop.RegisterReadObject(read_object_sp,
955 [this] (MainLoopBase &) { DataAvailableCallback(); }, error);
959 GDBRemoteCommunication::PacketResult
960 GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
962 if ((buffer == nullptr) || (len == 0))
965 return PacketResult::Success;
968 StreamString response;
969 response.PutChar ('O');
970 response.PutBytesAsRawHex8 (buffer, len);
972 return SendPacketNoLock (response.GetData (), response.GetSize ());
976 GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
980 // Set up the reading/handling of process I/O
981 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
984 error.SetErrorString ("failed to create ConnectionFileDescriptor");
988 m_stdio_communication.SetCloseOnEOF (false);
989 m_stdio_communication.SetConnection (conn_up.release());
990 if (!m_stdio_communication.IsConnected ())
992 error.SetErrorString ("failed to set connection for inferior I/O communication");
1000 GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding()
1002 // Don't forward if not connected (e.g. when attaching).
1003 if (! m_stdio_communication.IsConnected())
1006 // llgs local-process debugging may specify PTY paths, which will make these
1007 // file actions non-null
1008 // process launch -e/o will also make these file actions non-null
1009 // nullptr means that the traffic is expected to flow over gdb-remote protocol
1010 if ( m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) &&
1011 m_process_launch_info.GetFileActionForFD(STDERR_FILENO))
1015 lldbassert(! m_stdio_handle_up);
1016 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1017 m_stdio_communication.GetConnection()->GetReadObject(),
1018 [this] (MainLoopBase &) { SendProcessOutput(); }, error);
1020 if (! m_stdio_handle_up)
1022 // Not much we can do about the failure. Log it and continue without forwarding.
1023 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1024 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio forwarding: %s",
1025 __FUNCTION__, error.AsCString());
1030 GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
1032 m_stdio_handle_up.reset();
1036 GDBRemoteCommunicationServerLLGS::SendProcessOutput()
1039 ConnectionStatus status;
1043 size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1046 case eConnectionStatusSuccess:
1047 SendONotification(buffer, bytes_read);
1049 case eConnectionStatusLostConnection:
1050 case eConnectionStatusEndOfFile:
1051 case eConnectionStatusError:
1052 case eConnectionStatusNoConnection:
1053 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1054 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
1055 m_stdio_handle_up.reset();
1058 case eConnectionStatusInterrupted:
1059 case eConnectionStatusTimedOut:
1065 GDBRemoteCommunication::PacketResult
1066 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1068 // Fail if we don't have a current process.
1069 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1070 return SendErrorResponse (68);
1072 lldb::pid_t pid = m_debugged_process_sp->GetID ();
1074 if (pid == LLDB_INVALID_PROCESS_ID)
1075 return SendErrorResponse (1);
1077 ProcessInstanceInfo proc_info;
1078 if (!Host::GetProcessInfo (pid, proc_info))
1079 return SendErrorResponse (1);
1081 StreamString response;
1082 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1083 return SendPacketNoLock (response.GetData (), response.GetSize ());
1086 GDBRemoteCommunication::PacketResult
1087 GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
1089 // Fail if we don't have a current process.
1090 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1091 return SendErrorResponse (68);
1093 // Make sure we set the current thread so g and p packets return
1094 // the data the gdb will expect.
1095 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1096 SetCurrentThreadID (tid);
1098 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1100 return SendErrorResponse (69);
1102 StreamString response;
1103 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1105 return SendPacketNoLock (response.GetData(), response.GetSize());
1108 GDBRemoteCommunication::PacketResult
1109 GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1111 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1113 StopSTDIOForwarding();
1115 if (! m_debugged_process_sp)
1118 log->Printf("GDBRemoteCommunicationServerLLGS::%s No debugged process found.", __FUNCTION__);
1119 return PacketResult::Success;
1122 Error error = m_debugged_process_sp->Kill();
1123 if (error.Fail() && log)
1124 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged process %" PRIu64 ": %s",
1125 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1127 // No OK response for kill packet.
1128 // return SendOKResponse ();
1129 return PacketResult::Success;
1132 GDBRemoteCommunication::PacketResult
1133 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1135 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1136 if (packet.GetU32(0))
1137 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1139 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1140 return SendOKResponse ();
1143 GDBRemoteCommunication::PacketResult
1144 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1146 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1148 packet.GetHexByteString (path);
1149 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1150 return SendOKResponse ();
1153 GDBRemoteCommunication::PacketResult
1154 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1156 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1159 StreamString response;
1160 response.PutCStringAsRawHex8(working_dir.GetCString());
1161 return SendPacketNoLock(response.GetData(), response.GetSize());
1164 return SendErrorResponse(14);
1167 GDBRemoteCommunication::PacketResult
1168 GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1170 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1172 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1174 // Ensure we have a native process.
1175 if (!m_debugged_process_sp)
1178 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1179 return SendErrorResponse (0x36);
1182 // Pull out the signal number.
1183 packet.SetFilePos (::strlen ("C"));
1184 if (packet.GetBytesLeft () < 1)
1186 // Shouldn't be using a C without a signal.
1187 return SendIllFormedResponse (packet, "C packet specified without signal.");
1189 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1190 if (signo == std::numeric_limits<uint32_t>::max ())
1191 return SendIllFormedResponse (packet, "failed to parse signal number");
1193 // Handle optional continue address.
1194 if (packet.GetBytesLeft () > 0)
1196 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1197 if (*packet.Peek () == ';')
1198 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1200 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1203 ResumeActionList resume_actions (StateType::eStateRunning, 0);
1206 // We have two branches: what to do if a continue thread is specified (in which case we target
1207 // sending the signal to that thread), or when we don't have a continue thread set (in which
1208 // case we send a signal to the process).
1210 // TODO discuss with Greg Clayton, make sure this makes sense.
1212 lldb::tid_t signal_tid = GetContinueThreadID ();
1213 if (signal_tid != LLDB_INVALID_THREAD_ID)
1215 // The resume action for the continue thread (or all threads if a continue thread is not set).
1216 ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
1218 // Add the action for the continue thread (or all threads when the continue thread isn't present).
1219 resume_actions.Append (action);
1223 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1224 error = m_debugged_process_sp->Signal (signo);
1228 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1230 m_debugged_process_sp->GetID (),
1231 error.AsCString ());
1233 return SendErrorResponse (0x52);
1237 // Resume the threads.
1238 error = m_debugged_process_sp->Resume (resume_actions);
1242 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1244 m_debugged_process_sp->GetID (),
1245 error.AsCString ());
1247 return SendErrorResponse (0x38);
1250 // Don't send an "OK" packet; response is the stopped/exited message.
1251 return PacketResult::Success;
1254 GDBRemoteCommunication::PacketResult
1255 GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1257 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1259 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1261 packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1263 // For now just support all continue.
1264 const bool has_continue_address = (packet.GetBytesLeft () > 0);
1265 if (has_continue_address)
1268 log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1269 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1272 // Ensure we have a native process.
1273 if (!m_debugged_process_sp)
1276 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1277 return SendErrorResponse (0x36);
1280 // Build the ResumeActionList
1281 ResumeActionList actions (StateType::eStateRunning, 0);
1283 Error error = m_debugged_process_sp->Resume (actions);
1288 log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1290 m_debugged_process_sp->GetID (),
1291 error.AsCString ());
1293 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1297 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1299 // No response required from continue.
1300 return PacketResult::Success;
1303 GDBRemoteCommunication::PacketResult
1304 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1306 StreamString response;
1307 response.Printf("vCont;c;C;s;S");
1309 return SendPacketNoLock(response.GetData(), response.GetSize());
1312 GDBRemoteCommunication::PacketResult
1313 GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1315 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1317 log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1319 packet.SetFilePos (::strlen ("vCont"));
1321 if (packet.GetBytesLeft() == 0)
1324 log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1325 return SendIllFormedResponse (packet, "Missing action from vCont package");
1328 // Check if this is all continue (no options or ";c").
1329 if (::strcmp (packet.Peek (), ";c") == 0)
1331 // Move past the ';', then do a simple 'c'.
1332 packet.SetFilePos (packet.GetFilePos () + 1);
1333 return Handle_c (packet);
1335 else if (::strcmp (packet.Peek (), ";s") == 0)
1337 // Move past the ';', then do a simple 's'.
1338 packet.SetFilePos (packet.GetFilePos () + 1);
1339 return Handle_s (packet);
1342 // Ensure we have a native process.
1343 if (!m_debugged_process_sp)
1346 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1347 return SendErrorResponse (0x36);
1350 ResumeActionList thread_actions;
1352 while (packet.GetBytesLeft () && *packet.Peek () == ';')
1354 // Skip the semi-colon.
1357 // Build up the thread action.
1358 ResumeAction thread_action;
1359 thread_action.tid = LLDB_INVALID_THREAD_ID;
1360 thread_action.state = eStateInvalid;
1361 thread_action.signal = 0;
1363 const char action = packet.GetChar ();
1367 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1368 if (thread_action.signal == 0)
1369 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1370 // Fall through to next case...
1374 thread_action.state = eStateRunning;
1378 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1379 if (thread_action.signal == 0)
1380 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1381 // Fall through to next case...
1385 thread_action.state = eStateStepping;
1389 return SendIllFormedResponse (packet, "Unsupported vCont action");
1393 // Parse out optional :{thread-id} value.
1394 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1396 // Consume the separator.
1399 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1400 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1401 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1404 thread_actions.Append (thread_action);
1407 Error error = m_debugged_process_sp->Resume (thread_actions);
1412 log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1414 m_debugged_process_sp->GetID (),
1415 error.AsCString ());
1417 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1421 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1423 // No response required from vCont.
1424 return PacketResult::Success;
1428 GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1430 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1432 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1434 m_current_tid = tid;
1435 if (m_debugged_process_sp)
1436 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1440 GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1442 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1444 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1446 m_continue_tid = tid;
1449 GDBRemoteCommunication::PacketResult
1450 GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1452 // Handle the $? gdbremote command.
1454 // If no process, indicate error
1455 if (!m_debugged_process_sp)
1456 return SendErrorResponse (02);
1458 return SendStopReasonForState (m_debugged_process_sp->GetState());
1461 GDBRemoteCommunication::PacketResult
1462 GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
1464 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1466 switch (process_state)
1468 case eStateAttaching:
1469 case eStateLaunching:
1471 case eStateStepping:
1472 case eStateDetached:
1473 // NOTE: gdb protocol doc looks like it should return $OK
1474 // when everything is running (i.e. no stopped result).
1475 return PacketResult::Success; // Ignore
1477 case eStateSuspended:
1481 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1482 // Make sure we set the current thread so g and p packets return
1483 // the data the gdb will expect.
1484 SetCurrentThreadID (tid);
1485 return SendStopReplyPacketForThread (tid);
1489 case eStateUnloaded:
1491 return SendWResponse(m_debugged_process_sp.get());
1496 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1498 m_debugged_process_sp->GetID (),
1499 StateAsCString (process_state));
1504 return SendErrorResponse (0);
1507 GDBRemoteCommunication::PacketResult
1508 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1510 // Fail if we don't have a current process.
1511 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1512 return SendErrorResponse (68);
1514 // Ensure we have a thread.
1515 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1517 return SendErrorResponse (69);
1519 // Get the register context for the first thread.
1520 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1521 if (!reg_context_sp)
1522 return SendErrorResponse (69);
1524 // Parse out the register number from the request.
1525 packet.SetFilePos (strlen("qRegisterInfo"));
1526 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1527 if (reg_index == std::numeric_limits<uint32_t>::max ())
1528 return SendErrorResponse (69);
1530 // Return the end of registers response if we've iterated one past the end of the register set.
1531 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1532 return SendErrorResponse (69);
1534 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1536 return SendErrorResponse (69);
1538 // Build the reginfos response.
1539 StreamGDBRemote response;
1541 response.PutCString ("name:");
1542 response.PutCString (reg_info->name);
1543 response.PutChar (';');
1545 if (reg_info->alt_name && reg_info->alt_name[0])
1547 response.PutCString ("alt-name:");
1548 response.PutCString (reg_info->alt_name);
1549 response.PutChar (';');
1552 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1554 switch (reg_info->encoding)
1556 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
1557 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
1558 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1559 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
1563 switch (reg_info->format)
1565 case eFormatBinary: response.PutCString ("format:binary;"); break;
1566 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
1567 case eFormatHex: response.PutCString ("format:hex;"); break;
1568 case eFormatFloat: response.PutCString ("format:float;"); break;
1569 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
1570 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
1571 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
1572 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
1573 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
1574 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
1575 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1576 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1580 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1581 if (register_set_name)
1583 response.PutCString ("set:");
1584 response.PutCString (register_set_name);
1585 response.PutChar (';');
1588 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
1589 response.Printf ("ehframe:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1591 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1592 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1594 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1596 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
1597 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
1598 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
1599 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
1600 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
1601 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
1602 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
1603 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
1604 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
1605 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
1606 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
1607 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
1608 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
1612 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1614 response.PutCString ("container-regs:");
1616 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1619 response.PutChar (',');
1620 response.Printf ("%" PRIx32, *reg_num);
1622 response.PutChar (';');
1625 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1627 response.PutCString ("invalidate-regs:");
1629 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1632 response.PutChar (',');
1633 response.Printf ("%" PRIx32, *reg_num);
1635 response.PutChar (';');
1638 return SendPacketNoLock(response.GetData(), response.GetSize());
1641 GDBRemoteCommunication::PacketResult
1642 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1644 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1646 // Fail if we don't have a current process.
1647 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1650 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1651 return SendOKResponse ();
1654 StreamGDBRemote response;
1655 response.PutChar ('m');
1658 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1660 NativeThreadProtocolSP thread_sp;
1661 uint32_t thread_index;
1662 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1664 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1667 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);
1668 if (thread_index > 0)
1669 response.PutChar(',');
1670 response.Printf ("%" PRIx64, thread_sp->GetID ());
1674 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1676 return SendPacketNoLock(response.GetData(), response.GetSize());
1679 GDBRemoteCommunication::PacketResult
1680 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1682 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1683 return SendPacketNoLock ("l", 1);
1686 GDBRemoteCommunication::PacketResult
1687 GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1689 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1691 // Parse out the register number from the request.
1692 packet.SetFilePos (strlen("p"));
1693 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1694 if (reg_index == std::numeric_limits<uint32_t>::max ())
1697 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1698 return SendErrorResponse (0x15);
1701 // Get the thread to use.
1702 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1706 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1707 return SendErrorResponse (0x15);
1710 // Get the thread's register context.
1711 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1712 if (!reg_context_sp)
1715 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 ());
1716 return SendErrorResponse (0x15);
1719 // Return the end of registers response if we've iterated one past the end of the register set.
1720 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1723 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1724 return SendErrorResponse (0x15);
1727 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1731 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1732 return SendErrorResponse (0x15);
1735 // Build the reginfos response.
1736 StreamGDBRemote response;
1738 // Retrieve the value
1739 RegisterValue reg_value;
1740 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1744 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1745 return SendErrorResponse (0x15);
1748 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1752 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1753 return SendErrorResponse (0x15);
1756 // FIXME flip as needed to get data in big/little endian format for this host.
1757 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1758 response.PutHex8 (data[i]);
1760 return SendPacketNoLock (response.GetData (), response.GetSize ());
1763 GDBRemoteCommunication::PacketResult
1764 GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1766 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1768 // Ensure there is more content.
1769 if (packet.GetBytesLeft () < 1)
1770 return SendIllFormedResponse (packet, "Empty P packet");
1772 // Parse out the register number from the request.
1773 packet.SetFilePos (strlen("P"));
1774 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1775 if (reg_index == std::numeric_limits<uint32_t>::max ())
1778 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1779 return SendErrorResponse (0x29);
1782 // Note debugserver would send an E30 here.
1783 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1784 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1786 // Get process architecture.
1787 ArchSpec process_arch;
1788 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1791 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1792 return SendErrorResponse (0x49);
1795 // Parse out the value.
1796 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1797 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1799 // Get the thread to use.
1800 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1804 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1805 return SendErrorResponse (0x28);
1808 // Get the thread's register context.
1809 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1810 if (!reg_context_sp)
1813 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 ());
1814 return SendErrorResponse (0x15);
1817 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1821 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1822 return SendErrorResponse (0x48);
1825 // Return the end of registers response if we've iterated one past the end of the register set.
1826 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1829 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1830 return SendErrorResponse (0x47);
1833 if (reg_size != reg_info->byte_size)
1835 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1838 // Build the reginfos response.
1839 StreamGDBRemote response;
1841 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1842 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1846 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1847 return SendErrorResponse (0x32);
1850 return SendOKResponse();
1853 GDBRemoteCommunication::PacketResult
1854 GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1856 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1858 // Fail if we don't have a current process.
1859 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1862 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1863 return SendErrorResponse (0x15);
1866 // Parse out which variant of $H is requested.
1867 packet.SetFilePos (strlen("H"));
1868 if (packet.GetBytesLeft () < 1)
1871 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1872 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1875 const char h_variant = packet.GetChar ();
1886 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1887 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1890 // Parse out the thread number.
1891 // FIXME return a parse success/fail value. All values are valid here.
1892 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1894 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1895 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1897 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1901 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1902 return SendErrorResponse (0x15);
1906 // Now switch the given thread type.
1910 SetCurrentThreadID (tid);
1914 SetContinueThreadID (tid);
1918 assert (false && "unsupported $H variant - shouldn't get here");
1919 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1922 return SendOKResponse();
1925 GDBRemoteCommunication::PacketResult
1926 GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1928 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1930 // Fail if we don't have a current process.
1931 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1934 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1935 return SendErrorResponse (0x15);
1938 packet.SetFilePos (::strlen("I"));
1942 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1947 // write directly to stdin *this might block if stdin buffer is full*
1948 // TODO: enqueue this block in circular buffer and send window size to remote host
1949 ConnectionStatus status;
1951 m_stdio_communication.Write(tmp, read, status, &error);
1954 return SendErrorResponse (0x15);
1958 return SendOKResponse();
1961 GDBRemoteCommunication::PacketResult
1962 GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1964 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1966 // Fail if we don't have a current process.
1967 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1970 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1971 return SendErrorResponse (0x15);
1974 // Interrupt the process.
1975 Error error = m_debugged_process_sp->Interrupt ();
1980 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1982 m_debugged_process_sp->GetID (),
1983 error.AsCString ());
1985 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1989 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1991 // No response required from stop all.
1992 return PacketResult::Success;
1995 GDBRemoteCommunication::PacketResult
1996 GDBRemoteCommunicationServerLLGS::Handle_memory_read(StringExtractorGDBRemote &packet)
1998 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2000 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2003 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2004 return SendErrorResponse (0x15);
2007 // Parse out the memory address.
2008 packet.SetFilePos (strlen("m"));
2009 if (packet.GetBytesLeft() < 1)
2010 return SendIllFormedResponse(packet, "Too short m packet");
2012 // Read the address. Punting on validation.
2013 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2014 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2017 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2018 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2020 // Get # bytes to read.
2021 if (packet.GetBytesLeft() < 1)
2022 return SendIllFormedResponse(packet, "Length missing in m packet");
2024 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2025 if (byte_count == 0)
2028 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
2029 return SendOKResponse();
2032 // Allocate the response buffer.
2033 std::string buf(byte_count, '\0');
2035 return SendErrorResponse (0x78);
2038 // Retrieve the process memory.
2039 size_t bytes_read = 0;
2040 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
2044 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2045 return SendErrorResponse (0x08);
2048 if (bytes_read == 0)
2051 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);
2052 return SendErrorResponse (0x08);
2055 StreamGDBRemote response;
2056 packet.SetFilePos(0);
2057 char kind = packet.GetChar('?');
2059 response.PutEscapedBytes(buf.data(), byte_count);
2062 assert(kind == 'm');
2063 for (size_t i = 0; i < bytes_read; ++i)
2064 response.PutHex8(buf[i]);
2067 return SendPacketNoLock(response.GetData(), response.GetSize());
2070 GDBRemoteCommunication::PacketResult
2071 GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2073 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2075 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2078 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2079 return SendErrorResponse (0x15);
2082 // Parse out the memory address.
2083 packet.SetFilePos (strlen("M"));
2084 if (packet.GetBytesLeft() < 1)
2085 return SendIllFormedResponse(packet, "Too short M packet");
2087 // Read the address. Punting on validation.
2088 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2089 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2092 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2093 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2095 // Get # bytes to read.
2096 if (packet.GetBytesLeft() < 1)
2097 return SendIllFormedResponse(packet, "Length missing in M packet");
2099 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2100 if (byte_count == 0)
2103 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2104 return PacketResult::Success;
2108 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2109 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2111 // Allocate the conversion buffer.
2112 std::vector<uint8_t> buf(byte_count, 0);
2114 return SendErrorResponse (0x78);
2116 // Convert the hex memory write contents to bytes.
2117 StreamGDBRemote response;
2118 const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
2119 if (convert_count != byte_count)
2122 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);
2123 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2126 // Write the process memory.
2127 size_t bytes_written = 0;
2128 Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
2132 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2133 return SendErrorResponse (0x09);
2136 if (bytes_written == 0)
2139 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);
2140 return SendErrorResponse (0x09);
2143 return SendOKResponse ();
2146 GDBRemoteCommunication::PacketResult
2147 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2149 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2151 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2152 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
2153 // client only asks this when a process is being debugged.
2155 // Ensure we have a process running; otherwise, we can't figure this out
2156 // since we won't have a NativeProcessProtocol.
2157 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2160 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2161 return SendErrorResponse (0x15);
2164 // Test if we can get any region back when asking for the region around NULL.
2165 MemoryRegionInfo region_info;
2166 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2169 // We don't support memory region info collection for this NativeProcessProtocol.
2170 return SendUnimplementedResponse ("");
2173 return SendOKResponse();
2176 GDBRemoteCommunication::PacketResult
2177 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2179 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2181 // Ensure we have a process.
2182 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2185 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2186 return SendErrorResponse (0x15);
2189 // Parse out the memory address.
2190 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2191 if (packet.GetBytesLeft() < 1)
2192 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2194 // Read the address. Punting on validation.
2195 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2197 StreamGDBRemote response;
2199 // Get the memory region info for the target address.
2200 MemoryRegionInfo region_info;
2201 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2204 // Return the error message.
2206 response.PutCString ("error:");
2207 response.PutCStringAsRawHex8 (error.AsCString ());
2208 response.PutChar (';');
2212 // Range start and size.
2213 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2216 if (region_info.GetReadable () ||
2217 region_info.GetWritable () ||
2218 region_info.GetExecutable ())
2220 // Write permissions info.
2221 response.PutCString ("permissions:");
2223 if (region_info.GetReadable ())
2224 response.PutChar ('r');
2225 if (region_info.GetWritable ())
2226 response.PutChar('w');
2227 if (region_info.GetExecutable())
2228 response.PutChar ('x');
2230 response.PutChar (';');
2234 return SendPacketNoLock(response.GetData(), response.GetSize());
2237 GDBRemoteCommunication::PacketResult
2238 GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2240 // Ensure we have a process.
2241 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2243 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2245 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2246 return SendErrorResponse (0x15);
2249 // Parse out software or hardware breakpoint or watchpoint requested.
2250 packet.SetFilePos (strlen("Z"));
2251 if (packet.GetBytesLeft() < 1)
2252 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2254 bool want_breakpoint = true;
2255 bool want_hardware = false;
2256 uint32_t watch_flags = 0;
2258 const GDBStoppointType stoppoint_type =
2259 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2260 switch (stoppoint_type)
2262 case eBreakpointSoftware:
2263 want_hardware = false; want_breakpoint = true; break;
2264 case eBreakpointHardware:
2265 want_hardware = true; want_breakpoint = true; break;
2266 case eWatchpointWrite:
2268 want_hardware = true; want_breakpoint = false; break;
2269 case eWatchpointRead:
2271 want_hardware = true; want_breakpoint = false; break;
2272 case eWatchpointReadWrite:
2274 want_hardware = true; want_breakpoint = false; break;
2275 case eStoppointInvalid:
2276 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2280 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2281 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2283 // Parse out the stoppoint address.
2284 if (packet.GetBytesLeft() < 1)
2285 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2286 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2288 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2289 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2291 // Parse out the stoppoint size (i.e. size hint for opcode size).
2292 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2293 if (size == std::numeric_limits<uint32_t>::max ())
2294 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2296 if (want_breakpoint)
2298 // Try to set the breakpoint.
2299 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2300 if (error.Success ())
2301 return SendOKResponse ();
2302 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2304 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2305 " failed to set breakpoint: %s",
2307 m_debugged_process_sp->GetID (),
2308 error.AsCString ());
2309 return SendErrorResponse (0x09);
2313 // Try to set the watchpoint.
2314 const Error error = m_debugged_process_sp->SetWatchpoint (
2315 addr, size, watch_flags, want_hardware);
2316 if (error.Success ())
2317 return SendOKResponse ();
2318 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2320 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2321 " failed to set watchpoint: %s",
2323 m_debugged_process_sp->GetID (),
2324 error.AsCString ());
2325 return SendErrorResponse (0x09);
2329 GDBRemoteCommunication::PacketResult
2330 GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2332 // Ensure we have a process.
2333 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2335 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2337 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2338 return SendErrorResponse (0x15);
2341 // Parse out software or hardware breakpoint or watchpoint requested.
2342 packet.SetFilePos (strlen("z"));
2343 if (packet.GetBytesLeft() < 1)
2344 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2346 bool want_breakpoint = true;
2348 const GDBStoppointType stoppoint_type =
2349 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2350 switch (stoppoint_type)
2352 case eBreakpointHardware: want_breakpoint = true; break;
2353 case eBreakpointSoftware: want_breakpoint = true; break;
2354 case eWatchpointWrite: want_breakpoint = false; break;
2355 case eWatchpointRead: want_breakpoint = false; break;
2356 case eWatchpointReadWrite: want_breakpoint = false; break;
2358 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2362 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2363 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2365 // Parse out the stoppoint address.
2366 if (packet.GetBytesLeft() < 1)
2367 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2368 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2370 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2371 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2374 // Parse out the stoppoint size (i.e. size hint for opcode size).
2375 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2376 if (size == std::numeric_limits<uint32_t>::max ())
2377 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2380 if (want_breakpoint)
2382 // Try to clear the breakpoint.
2383 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2384 if (error.Success ())
2385 return SendOKResponse ();
2386 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2388 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2389 " failed to remove breakpoint: %s",
2391 m_debugged_process_sp->GetID (),
2392 error.AsCString ());
2393 return SendErrorResponse (0x09);
2397 // Try to clear the watchpoint.
2398 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2399 if (error.Success ())
2400 return SendOKResponse ();
2401 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2403 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2404 " failed to remove watchpoint: %s",
2406 m_debugged_process_sp->GetID (),
2407 error.AsCString ());
2408 return SendErrorResponse (0x09);
2412 GDBRemoteCommunication::PacketResult
2413 GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2415 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2417 // Ensure we have a process.
2418 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2421 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2422 return SendErrorResponse (0x32);
2425 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2426 // Bail out if we don't have a thread id.
2427 lldb::tid_t tid = GetContinueThreadID ();
2428 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2429 tid = GetCurrentThreadID ();
2430 if (tid == LLDB_INVALID_THREAD_ID)
2431 return SendErrorResponse (0x33);
2433 // Double check that we have such a thread.
2434 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2435 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2436 if (!thread_sp || thread_sp->GetID () != tid)
2437 return SendErrorResponse (0x33);
2439 // Create the step action for the given thread.
2440 ResumeAction action = { tid, eStateStepping, 0 };
2442 // Setup the actions list.
2443 ResumeActionList actions;
2444 actions.Append (action);
2446 // All other threads stop while we're single stepping a thread.
2447 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2448 Error error = m_debugged_process_sp->Resume (actions);
2452 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2453 return SendErrorResponse(0x49);
2456 // No response here - the stop or exit will come from the resulting action.
2457 return PacketResult::Success;
2460 GDBRemoteCommunication::PacketResult
2461 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2463 // *BSD impls should be able to do this too.
2464 #if defined(__linux__)
2465 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2467 // Parse out the offset.
2468 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2469 if (packet.GetBytesLeft () < 1)
2470 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2472 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2473 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2474 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2477 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2478 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2480 // Parse out the length.
2481 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2482 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2483 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2485 // Grab the auxv data if we need it.
2486 if (!m_active_auxv_buffer_sp)
2488 // Make sure we have a valid process.
2489 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2492 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2493 return SendErrorResponse (0x10);
2496 // Grab the auxv data.
2497 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2498 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2500 // Hmm, no auxv data, call that an error.
2502 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2503 m_active_auxv_buffer_sp.reset ();
2504 return SendErrorResponse (0x11);
2508 // FIXME find out if/how I lock the stream here.
2510 StreamGDBRemote response;
2511 bool done_with_buffer = false;
2513 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2515 // We have nothing left to send. Mark the buffer as complete.
2516 response.PutChar ('l');
2517 done_with_buffer = true;
2521 // Figure out how many bytes are available starting at the given offset.
2522 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2524 // Figure out how many bytes we're going to read.
2525 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2527 // Mark the response type according to whether we're reading the remainder of the auxv data.
2528 if (bytes_to_read >= bytes_remaining)
2530 // There will be nothing left to read after this
2531 response.PutChar ('l');
2532 done_with_buffer = true;
2536 // There will still be bytes to read after this request.
2537 response.PutChar ('m');
2540 // Now write the data in encoded binary form.
2541 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2544 if (done_with_buffer)
2545 m_active_auxv_buffer_sp.reset ();
2547 return SendPacketNoLock(response.GetData(), response.GetSize());
2549 return SendUnimplementedResponse ("not implemented on this platform");
2553 GDBRemoteCommunication::PacketResult
2554 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2556 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2558 // Move past packet name.
2559 packet.SetFilePos (strlen ("QSaveRegisterState"));
2561 // Get the thread to use.
2562 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2565 if (m_thread_suffix_supported)
2566 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2568 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2571 // Grab the register context for the thread.
2572 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2573 if (!reg_context_sp)
2576 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 ());
2577 return SendErrorResponse (0x15);
2580 // Save registers to a buffer.
2581 DataBufferSP register_data_sp;
2582 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2586 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2587 return SendErrorResponse (0x75);
2590 // Allocate a new save id.
2591 const uint32_t save_id = GetNextSavedRegistersID ();
2592 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2594 // Save the register data buffer under the save id.
2596 Mutex::Locker locker (m_saved_registers_mutex);
2597 m_saved_registers_map[save_id] = register_data_sp;
2600 // Write the response.
2601 StreamGDBRemote response;
2602 response.Printf ("%" PRIu32, save_id);
2603 return SendPacketNoLock(response.GetData(), response.GetSize());
2606 GDBRemoteCommunication::PacketResult
2607 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2609 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2611 // Parse out save id.
2612 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2613 if (packet.GetBytesLeft () < 1)
2614 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2616 const uint32_t save_id = packet.GetU32 (0);
2620 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2621 return SendErrorResponse (0x76);
2624 // Get the thread to use.
2625 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2628 if (m_thread_suffix_supported)
2629 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2631 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2634 // Grab the register context for the thread.
2635 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2636 if (!reg_context_sp)
2639 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 ());
2640 return SendErrorResponse (0x15);
2643 // Retrieve register state buffer, then remove from the list.
2644 DataBufferSP register_data_sp;
2646 Mutex::Locker locker (m_saved_registers_mutex);
2648 // Find the register set buffer for the given save id.
2649 auto it = m_saved_registers_map.find (save_id);
2650 if (it == m_saved_registers_map.end ())
2653 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);
2654 return SendErrorResponse (0x77);
2656 register_data_sp = it->second;
2658 // Remove it from the map.
2659 m_saved_registers_map.erase (it);
2662 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2666 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2667 return SendErrorResponse (0x77);
2670 return SendOKResponse();
2673 GDBRemoteCommunication::PacketResult
2674 GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2676 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2678 // Consume the ';' after vAttach.
2679 packet.SetFilePos (strlen ("vAttach"));
2680 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2681 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2683 // Grab the PID to which we will attach (assume hex encoding).
2684 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2685 if (pid == LLDB_INVALID_PROCESS_ID)
2686 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2688 // Attempt to attach.
2690 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2692 Error error = AttachToProcess (pid);
2697 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2698 return SendErrorResponse (0x01);
2701 // Notify we attached by sending a stop packet.
2702 return SendStopReasonForState (m_debugged_process_sp->GetState ());
2705 GDBRemoteCommunication::PacketResult
2706 GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2708 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2710 StopSTDIOForwarding();
2712 // Fail if we don't have a current process.
2713 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2716 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2717 return SendErrorResponse (0x15);
2720 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2722 // Consume the ';' after D.
2723 packet.SetFilePos (1);
2724 if (packet.GetBytesLeft ())
2726 if (packet.GetChar () != ';')
2727 return SendIllFormedResponse (packet, "D missing expected ';'");
2729 // Grab the PID from which we will detach (assume hex encoding).
2730 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2731 if (pid == LLDB_INVALID_PROCESS_ID)
2732 return SendIllFormedResponse (packet, "D failed to parse the process id");
2735 if (pid != LLDB_INVALID_PROCESS_ID &&
2736 m_debugged_process_sp->GetID () != pid)
2738 return SendIllFormedResponse (packet, "Invalid pid");
2741 const Error error = m_debugged_process_sp->Detach ();
2745 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2746 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2747 return SendErrorResponse (0x01);
2750 return SendOKResponse ();
2753 GDBRemoteCommunication::PacketResult
2754 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2756 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2758 packet.SetFilePos (strlen("qThreadStopInfo"));
2759 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2760 if (tid == LLDB_INVALID_THREAD_ID)
2763 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2764 return SendErrorResponse (0x15);
2766 return SendStopReplyPacketForThread (tid);
2769 GDBRemoteCommunication::PacketResult
2770 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2772 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2774 // Ensure we have a debugged process.
2775 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2776 return SendErrorResponse (50);
2779 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2780 __FUNCTION__, m_debugged_process_sp->GetID());
2783 StreamString response;
2784 const bool threads_with_valid_stop_info_only = false;
2785 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2786 threads_with_valid_stop_info_only);
2787 if (! threads_array_sp)
2790 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2791 __FUNCTION__, m_debugged_process_sp->GetID());
2792 return SendErrorResponse(52);
2795 threads_array_sp->Write(response);
2796 StreamGDBRemote escaped_response;
2797 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2798 return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2801 GDBRemoteCommunication::PacketResult
2802 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2804 // Fail if we don't have a current process.
2805 if (!m_debugged_process_sp ||
2806 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2807 return SendErrorResponse (68);
2809 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2810 if (packet.GetBytesLeft() == 0)
2811 return SendOKResponse();
2812 if (packet.GetChar() != ':')
2813 return SendErrorResponse(67);
2815 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2816 StreamGDBRemote response;
2817 response.Printf ("num:%d;", num);
2818 return SendPacketNoLock(response.GetData(), response.GetSize());
2821 GDBRemoteCommunication::PacketResult
2822 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2824 // Fail if we don't have a current process.
2825 if (!m_debugged_process_sp ||
2826 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2827 return SendErrorResponse(67);
2829 packet.SetFilePos(strlen("qFileLoadAddress:"));
2830 if (packet.GetBytesLeft() == 0)
2831 return SendErrorResponse(68);
2833 std::string file_name;
2834 packet.GetHexByteString(file_name);
2836 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2837 Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2839 return SendErrorResponse(69);
2841 if (file_load_address == LLDB_INVALID_ADDRESS)
2842 return SendErrorResponse(1); // File not loaded
2844 StreamGDBRemote response;
2845 response.PutHex64(file_load_address);
2846 return SendPacketNoLock(response.GetData(), response.GetSize());
2850 GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2852 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2854 // Tell the stdio connection to shut down.
2855 if (m_stdio_communication.IsConnected())
2857 auto connection = m_stdio_communication.GetConnection();
2861 connection->Disconnect (&error);
2863 if (error.Success ())
2866 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2871 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2878 NativeThreadProtocolSP
2879 GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2881 NativeThreadProtocolSP thread_sp;
2883 // We have no thread if we don't have a process.
2884 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2887 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2888 // Use the current thread in that case.
2889 if (!m_thread_suffix_supported)
2891 const lldb::tid_t current_tid = GetCurrentThreadID ();
2892 if (current_tid == LLDB_INVALID_THREAD_ID)
2894 else if (current_tid == 0)
2897 return m_debugged_process_sp->GetThreadAtIndex (0);
2900 return m_debugged_process_sp->GetThreadByID (current_tid);
2903 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2905 // Parse out the ';'.
2906 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2909 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2913 if (!packet.GetBytesLeft ())
2916 // Parse out thread: portion.
2917 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2920 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2923 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2924 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2926 return m_debugged_process_sp->GetThreadByID (tid);
2932 GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2934 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2936 // Use whatever the debug process says is the current thread id
2937 // since the protocol either didn't specify or specified we want
2938 // any/all threads marked as the current thread.
2939 if (!m_debugged_process_sp)
2940 return LLDB_INVALID_THREAD_ID;
2941 return m_debugged_process_sp->GetCurrentThreadID ();
2943 // Use the specific current thread id set by the gdb remote protocol.
2944 return m_current_tid;
2948 GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2950 Mutex::Locker locker (m_saved_registers_mutex);
2951 return m_next_saved_registers_id++;
2955 GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2957 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2959 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2961 // Clear any auxv cached data.
2962 // *BSD impls should be able to do this too.
2963 #if defined(__linux__)
2965 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2967 m_active_auxv_buffer_sp ? "was set" : "was not set");
2968 m_active_auxv_buffer_sp.reset ();
2973 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2974 const ArchSpec& arch)
2976 if (m_debugged_process_sp)
2979 if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2981 if (file_spec.Exists())
2986 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);