1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include <errno.h>
11 
12 #include "lldb/Host/Config.h"
13 
14 #include "GDBRemoteCommunicationServerLLGS.h"
15 #include "lldb/Core/StreamGDBRemote.h"
16 
17 // C Includes
18 // C++ Includes
19 #include <cstring>
20 #include <chrono>
21 #include <thread>
22 
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 
48 // Project includes
49 #include "Utility/StringExtractorGDBRemote.h"
50 #include "Utility/UriParser.h"
51 #include "ProcessGDBRemote.h"
52 #include "ProcessGDBRemoteLog.h"
53 
54 using namespace lldb;
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
57 using namespace llvm;
58 
59 //----------------------------------------------------------------------
60 // GDBRemote Errors
61 //----------------------------------------------------------------------
62 
63 namespace
64 {
65     enum GDBRemoteServerError
66     {
67         // Set to the first unused error number in literal form below
68         eErrorFirst = 29,
69         eErrorNoProcess = eErrorFirst,
70         eErrorResume,
71         eErrorExitStatus
72     };
73 }
74 
75 //----------------------------------------------------------------------
76 // GDBRemoteCommunicationServerLLGS constructor
77 //----------------------------------------------------------------------
78 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
79         const lldb::PlatformSP& platform_sp,
80         MainLoop &mainloop) :
81     GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
82     m_platform_sp (platform_sp),
83     m_mainloop (mainloop),
84     m_current_tid (LLDB_INVALID_THREAD_ID),
85     m_continue_tid (LLDB_INVALID_THREAD_ID),
86     m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
87     m_debugged_process_sp (),
88     m_stdio_communication ("process.stdio"),
89     m_inferior_prev_state (StateType::eStateInvalid),
90     m_active_auxv_buffer_sp (),
91     m_saved_registers_mutex (),
92     m_saved_registers_map (),
93     m_next_saved_registers_id (1),
94     m_handshake_completed (false)
95 {
96     assert(platform_sp);
97     RegisterPacketHandlers();
98 }
99 
100 void
101 GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
102 {
103     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
104                                   &GDBRemoteCommunicationServerLLGS::Handle_C);
105     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
106                                   &GDBRemoteCommunicationServerLLGS::Handle_c);
107     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
108                                   &GDBRemoteCommunicationServerLLGS::Handle_D);
109     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
110                                   &GDBRemoteCommunicationServerLLGS::Handle_H);
111     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
112                                   &GDBRemoteCommunicationServerLLGS::Handle_I);
113     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
114                                   &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
115     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
116                                   &GDBRemoteCommunicationServerLLGS::Handle_m);
117     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
118                                   &GDBRemoteCommunicationServerLLGS::Handle_M);
119     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
120                                   &GDBRemoteCommunicationServerLLGS::Handle_p);
121     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
122                                   &GDBRemoteCommunicationServerLLGS::Handle_P);
123     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
124                                   &GDBRemoteCommunicationServerLLGS::Handle_qC);
125     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
126                                   &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
127     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
128                                   &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
129     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
130                                   &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
131     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
132                                   &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
133     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
134                                   &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
135     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
136                                   &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
137     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
138                                   &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
139     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
140                                   &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
141     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
142                                   &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
143     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
144                                   &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
145     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
146                                   &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
147     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148                                   &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
150                                   &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
151     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
152                                   &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
153     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
154                                   &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
155     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156                                   &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158                                   &GDBRemoteCommunicationServerLLGS::Handle_s);
159     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
160                                   &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
161     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
162                                   &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
163     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
164                                   &GDBRemoteCommunicationServerLLGS::Handle_vCont);
165     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
166                                   &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
167     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
168                                   &GDBRemoteCommunicationServerLLGS::Handle_Z);
169     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
170                                   &GDBRemoteCommunicationServerLLGS::Handle_z);
171 
172     RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
173                           [this](StringExtractorGDBRemote packet,
174                                  Error &error,
175                                  bool &interrupt,
176                                  bool &quit)
177                           {
178                               quit = true;
179                               return this->Handle_k (packet);
180                           });
181 }
182 
183 Error
184 GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
185 {
186     if ((argc < 1) || !args || !args[0] || !args[0][0])
187         return Error ("%s: no process command line specified to launch", __FUNCTION__);
188 
189     m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
190     return Error ();
191 }
192 
193 Error
194 GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
195 {
196     m_process_launch_info.GetFlags ().Set (launch_flags);
197     return Error ();
198 }
199 
200 Error
201 GDBRemoteCommunicationServerLLGS::LaunchProcess ()
202 {
203     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
204 
205     if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
206         return Error ("%s: no process command line specified to launch", __FUNCTION__);
207 
208     Error error;
209     {
210         Mutex::Locker locker (m_debugged_process_mutex);
211         assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
212         error = NativeProcessProtocol::Launch(
213             m_process_launch_info,
214             *this,
215             m_mainloop,
216             m_debugged_process_sp);
217     }
218 
219     if (!error.Success ())
220     {
221         fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
222         return error;
223     }
224 
225     // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
226     // as needed.
227     // llgs local-process debugging may specify PTY paths, which will make these
228     // file actions non-null
229     // process launch -i/e/o will also make these file actions non-null
230     // nullptr means that the traffic is expected to flow over gdb-remote protocol
231     if (
232         m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr  ||
233         m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr  ||
234         m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
235         )
236     {
237         // nullptr means it's not redirected to file or pty (in case of LLGS local)
238         // at least one of stdio will be transferred pty<->gdb-remote
239         // we need to give the pty master handle to this object to read and/or write
240         if (log)
241             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
242 
243         // Setup stdout/stderr mapping from inferior to $O
244         auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
245         if (terminal_fd >= 0)
246         {
247             if (log)
248                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
249             error = SetSTDIOFileDescriptor (terminal_fd);
250             if (error.Fail ())
251                 return error;
252         }
253         else
254         {
255             if (log)
256                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
257         }
258     }
259     else
260     {
261         if (log)
262             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
263     }
264 
265     printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
266 
267     // Add to list of spawned processes.
268     lldb::pid_t pid;
269     if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
270     {
271         // add to spawned pids
272         Mutex::Locker locker (m_spawned_pids_mutex);
273         // On an lldb-gdbserver, we would expect there to be only one.
274         assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
275         m_spawned_pids.insert (pid);
276     }
277 
278     return error;
279 }
280 
281 Error
282 GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
283 {
284     Error error;
285 
286     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
287     if (log)
288         log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
289 
290     // Scope for mutex locker.
291     {
292         // Before we try to attach, make sure we aren't already monitoring something else.
293         Mutex::Locker locker (m_spawned_pids_mutex);
294         if (!m_spawned_pids.empty ())
295         {
296             error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
297             return error;
298         }
299 
300         // Try to attach.
301         error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
302         if (!error.Success ())
303         {
304             fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
305             return error;
306         }
307 
308         // Setup stdout/stderr mapping from inferior.
309         auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
310         if (terminal_fd >= 0)
311         {
312             if (log)
313                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
314             error = SetSTDIOFileDescriptor (terminal_fd);
315             if (error.Fail ())
316                 return error;
317         }
318         else
319         {
320             if (log)
321                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
322         }
323 
324         printf ("Attached to process %" PRIu64 "...\n", pid);
325 
326         // Add to list of spawned processes.
327         assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
328         m_spawned_pids.insert (pid);
329 
330         return error;
331     }
332 }
333 
334 void
335 GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
336 {
337     assert (process && "process cannot be NULL");
338     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
339     if (log)
340     {
341         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
342                 __FUNCTION__,
343                 process->GetID (),
344                 StateAsCString (process->GetState ()));
345     }
346 }
347 
348 GDBRemoteCommunication::PacketResult
349 GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
350 {
351     assert (process && "process cannot be NULL");
352     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
353 
354     // send W notification
355     ExitType exit_type = ExitType::eExitTypeInvalid;
356     int return_code = 0;
357     std::string exit_description;
358 
359     const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
360     if (!got_exit_info)
361     {
362         if (log)
363             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
364 
365         StreamGDBRemote response;
366         response.PutChar ('E');
367         response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
368         return SendPacketNoLock(response.GetData(), response.GetSize());
369     }
370     else
371     {
372         if (log)
373             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 ());
374 
375         StreamGDBRemote response;
376 
377         char return_type_code;
378         switch (exit_type)
379         {
380             case ExitType::eExitTypeExit:
381                 return_type_code = 'W';
382                 break;
383             case ExitType::eExitTypeSignal:
384                 return_type_code = 'X';
385                 break;
386             case ExitType::eExitTypeStop:
387                 return_type_code = 'S';
388                 break;
389             case ExitType::eExitTypeInvalid:
390                 return_type_code = 'E';
391                 break;
392         }
393         response.PutChar (return_type_code);
394 
395         // POSIX exit status limited to unsigned 8 bits.
396         response.PutHex8 (return_code);
397 
398         return SendPacketNoLock(response.GetData(), response.GetSize());
399     }
400 }
401 
402 static void
403 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
404 {
405     int64_t i;
406     if (swap)
407     {
408         for (i = buf_size-1; i >= 0; i--)
409             response.PutHex8 (buf[i]);
410     }
411     else
412     {
413         for (i = 0; i < buf_size; i++)
414             response.PutHex8 (buf[i]);
415     }
416 }
417 
418 static void
419 WriteRegisterValueInHexFixedWidth (StreamString &response,
420                                    NativeRegisterContextSP &reg_ctx_sp,
421                                    const RegisterInfo &reg_info,
422                                    const RegisterValue *reg_value_p)
423 {
424     RegisterValue reg_value;
425     if (!reg_value_p)
426     {
427         Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
428         if (error.Success ())
429             reg_value_p = &reg_value;
430         // else log.
431     }
432 
433     if (reg_value_p)
434     {
435         AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
436     }
437     else
438     {
439         // Zero-out any unreadable values.
440         if (reg_info.byte_size > 0)
441         {
442             std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
443             AppendHexValue (response, zeros.data(), zeros.size(), false);
444         }
445     }
446 }
447 
448 static JSONObject::SP
449 GetRegistersAsJSON(NativeThreadProtocol &thread)
450 {
451     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
452 
453     NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
454     if (! reg_ctx_sp)
455         return nullptr;
456 
457     JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
458 
459 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
460     // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
461     const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
462     if (! reg_set_p)
463         return nullptr;
464     for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
465     {
466         uint32_t reg_num = *reg_num_p;
467 #else
468     // Expedite only a couple of registers until we figure out why sending registers is
469     // expensive.
470     static const uint32_t k_expedited_registers[] = {
471         LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA
472     };
473     for (uint32_t generic_reg: k_expedited_registers)
474     {
475         uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, generic_reg);
476         if (reg_num == LLDB_INVALID_REGNUM)
477             continue; // Target does not support the given register.
478 #endif
479 
480         const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
481         if (reg_info_p == nullptr)
482         {
483             if (log)
484                 log->Printf("%s failed to get register info for register index %" PRIu32,
485                         __FUNCTION__, reg_num);
486             continue;
487         }
488 
489         if (reg_info_p->value_regs != nullptr)
490             continue; // Only expedite registers that are not contained in other registers.
491 
492         RegisterValue reg_value;
493         Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
494         if (error.Fail())
495         {
496             if (log)
497                 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
498                         reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
499                         error.AsCString ());
500             continue;
501         }
502 
503         StreamString stream;
504         WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, &reg_value);
505 
506         register_object_sp->SetObject(std::to_string(reg_num),
507                 std::make_shared<JSONString>(stream.GetString()));
508     }
509 
510     return register_object_sp;
511 }
512 
513 static const char *
514 GetStopReasonString(StopReason stop_reason)
515 {
516     switch (stop_reason)
517     {
518     case eStopReasonTrace:
519         return "trace";
520     case eStopReasonBreakpoint:
521         return "breakpoint";
522     case eStopReasonWatchpoint:
523         return "watchpoint";
524     case eStopReasonSignal:
525         return "signal";
526     case eStopReasonException:
527         return "exception";
528     case eStopReasonExec:
529         return "exec";
530     case eStopReasonInstrumentation:
531     case eStopReasonInvalid:
532     case eStopReasonPlanComplete:
533     case eStopReasonThreadExiting:
534     case eStopReasonNone:
535         break; // ignored
536     }
537     return nullptr;
538 }
539 
540 GDBRemoteCommunication::PacketResult
541 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
542 {
543     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
544 
545     // Ensure we have a debugged process.
546     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
547         return SendErrorResponse (50);
548 
549     if (log)
550         log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
551                 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
552 
553     // Ensure we can get info on the given thread.
554     NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
555     if (!thread_sp)
556         return SendErrorResponse (51);
557 
558     // Grab the reason this thread stopped.
559     struct ThreadStopInfo tid_stop_info;
560     std::string description;
561     if (!thread_sp->GetStopReason (tid_stop_info, description))
562         return SendErrorResponse (52);
563 
564     // FIXME implement register handling for exec'd inferiors.
565     // if (tid_stop_info.reason == eStopReasonExec)
566     // {
567     //     const bool force = true;
568     //     InitializeRegisters(force);
569     // }
570 
571     StreamString response;
572     // Output the T packet with the thread
573     response.PutChar ('T');
574     int signum = tid_stop_info.details.signal.signo;
575     if (log)
576     {
577         log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
578                 __FUNCTION__,
579                 m_debugged_process_sp->GetID (),
580                 tid,
581                 signum,
582                 tid_stop_info.reason,
583                 tid_stop_info.details.exception.type);
584     }
585 
586     // Print the signal number.
587     response.PutHex8 (signum & 0xff);
588 
589     // Include the tid.
590     response.Printf ("thread:%" PRIx64 ";", tid);
591 
592     // Include the thread name if there is one.
593     const std::string thread_name = thread_sp->GetName ();
594     if (!thread_name.empty ())
595     {
596         size_t thread_name_len = thread_name.length ();
597 
598         if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
599         {
600             response.PutCString ("name:");
601             response.PutCString (thread_name.c_str ());
602         }
603         else
604         {
605             // The thread name contains special chars, send as hex bytes.
606             response.PutCString ("hexname:");
607             response.PutCStringAsRawHex8 (thread_name.c_str ());
608         }
609         response.PutChar (';');
610     }
611 
612     // If a 'QListThreadsInStopReply' was sent to enable this feature, we
613     // will send all thread IDs back in the "threads" key whose value is
614     // a list of hex thread IDs separated by commas:
615     //  "threads:10a,10b,10c;"
616     // This will save the debugger from having to send a pair of qfThreadInfo
617     // and qsThreadInfo packets, but it also might take a lot of room in the
618     // stop reply packet, so it must be enabled only on systems where there
619     // are no limits on packet lengths.
620     if (m_list_threads_in_stop_reply)
621     {
622         response.PutCString ("threads:");
623 
624         uint32_t thread_index = 0;
625         NativeThreadProtocolSP listed_thread_sp;
626         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))
627         {
628             if (thread_index > 0)
629                 response.PutChar (',');
630             response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
631         }
632         response.PutChar (';');
633     }
634 
635     //
636     // Expedite registers.
637     //
638 
639     // Grab the register context.
640     NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
641     if (reg_ctx_sp)
642     {
643         // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
644         const RegisterSet *reg_set_p;
645         if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
646         {
647             if (log)
648                 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);
649 
650             for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
651             {
652                 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
653                 if (reg_info_p == nullptr)
654                 {
655                     if (log)
656                         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);
657                 }
658                 else if (reg_info_p->value_regs == nullptr)
659                 {
660                     // Only expediate registers that are not contained in other registers.
661                     RegisterValue reg_value;
662                     Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
663                     if (error.Success ())
664                     {
665                         response.Printf ("%.02x:", *reg_num_p);
666                         WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, &reg_value);
667                         response.PutChar (';');
668                     }
669                     else
670                     {
671                         if (log)
672                             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 ());
673 
674                     }
675                 }
676             }
677         }
678     }
679 
680     const char* reason_str = GetStopReasonString(tid_stop_info.reason);
681     if (reason_str != nullptr)
682     {
683         response.Printf ("reason:%s;", reason_str);
684     }
685 
686     if (!description.empty())
687     {
688         // Description may contains special chars, send as hex bytes.
689         response.PutCString ("description:");
690         response.PutCStringAsRawHex8 (description.c_str ());
691         response.PutChar (';');
692     }
693     else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
694     {
695         response.PutCString ("metype:");
696         response.PutHex64 (tid_stop_info.details.exception.type);
697         response.PutCString (";mecount:");
698         response.PutHex32 (tid_stop_info.details.exception.data_count);
699         response.PutChar (';');
700 
701         for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
702         {
703             response.PutCString ("medata:");
704             response.PutHex64 (tid_stop_info.details.exception.data[i]);
705             response.PutChar (';');
706         }
707     }
708 
709     return SendPacketNoLock (response.GetData(), response.GetSize());
710 }
711 
712 void
713 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (NativeProcessProtocol *process)
714 {
715     assert (process && "process cannot be NULL");
716 
717     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
718     if (log)
719         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
720 
721     PacketResult result = SendStopReasonForState(StateType::eStateExited);
722     if (result != PacketResult::Success)
723     {
724         if (log)
725             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
726     }
727 
728     // Remove the process from the list of spawned pids.
729     {
730         Mutex::Locker locker (m_spawned_pids_mutex);
731         if (m_spawned_pids.erase (process->GetID ()) < 1)
732         {
733             if (log)
734                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
735 
736         }
737     }
738 
739     // Close the pipe to the inferior terminal i/o if we launched it
740     // and set one up.
741     MaybeCloseInferiorTerminalConnection ();
742 
743     // We are ready to exit the debug monitor.
744     m_exit_now = true;
745 }
746 
747 void
748 GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (NativeProcessProtocol *process)
749 {
750     assert (process && "process cannot be NULL");
751 
752     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
753     if (log)
754         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
755 
756     // Send the stop reason unless this is the stop after the
757     // launch or attach.
758     switch (m_inferior_prev_state)
759     {
760         case eStateLaunching:
761         case eStateAttaching:
762             // Don't send anything per debugserver behavior.
763             break;
764         default:
765             // In all other cases, send the stop reason.
766             PacketResult result = SendStopReasonForState(StateType::eStateStopped);
767             if (result != PacketResult::Success)
768             {
769                 if (log)
770                     log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
771             }
772             break;
773     }
774 }
775 
776 void
777 GDBRemoteCommunicationServerLLGS::ProcessStateChanged (NativeProcessProtocol *process, lldb::StateType state)
778 {
779     assert (process && "process cannot be NULL");
780     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
781     if (log)
782     {
783         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
784                 __FUNCTION__,
785                 process->GetID (),
786                 StateAsCString (state));
787     }
788 
789     // Make sure we get all of the pending stdout/stderr from the inferior
790     // and send it to the lldb host before we send the state change
791     // notification
792     SendProcessOutput();
793 
794     switch (state)
795     {
796     case StateType::eStateExited:
797         HandleInferiorState_Exited (process);
798         break;
799 
800     case StateType::eStateStopped:
801         HandleInferiorState_Stopped (process);
802         break;
803 
804     default:
805         if (log)
806         {
807             log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
808                     __FUNCTION__,
809                     process->GetID (),
810                     StateAsCString (state));
811         }
812         break;
813     }
814 
815     // Remember the previous state reported to us.
816     m_inferior_prev_state = state;
817 }
818 
819 void
820 GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
821 {
822     ClearProcessSpecificData ();
823 }
824 
825 void
826 GDBRemoteCommunicationServerLLGS::DataAvailableCallback ()
827 {
828     Log *log (GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
829 
830     if (! m_handshake_completed)
831     {
832         if (! HandshakeWithClient())
833         {
834             if(log)
835                 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with client failed, exiting",
836                         __FUNCTION__);
837             m_mainloop.RequestTermination();
838             return;
839         }
840         m_handshake_completed = true;
841     }
842 
843     bool interrupt = false;
844     bool done = false;
845     Error error;
846     while (true)
847     {
848         const PacketResult result = GetPacketAndSendResponse (0, error, interrupt, done);
849         if (result == PacketResult::ErrorReplyTimeout)
850             break; // No more packets in the queue
851 
852         if ((result != PacketResult::Success))
853         {
854             if(log)
855                 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet failed: %s",
856                         __FUNCTION__, error.AsCString());
857             m_mainloop.RequestTermination();
858             break;
859         }
860     }
861 }
862 
863 Error
864 GDBRemoteCommunicationServerLLGS::InitializeConnection (std::unique_ptr<Connection> &&connection)
865 {
866     IOObjectSP read_object_sp = connection->GetReadObject();
867     GDBRemoteCommunicationServer::SetConnection(connection.release());
868 
869     Error error;
870     m_network_handle_up = m_mainloop.RegisterReadObject(read_object_sp,
871             [this] (MainLoopBase &) { DataAvailableCallback(); }, error);
872     return error;
873 }
874 
875 GDBRemoteCommunication::PacketResult
876 GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
877 {
878     if ((buffer == nullptr) || (len == 0))
879     {
880         // Nothing to send.
881         return PacketResult::Success;
882     }
883 
884     StreamString response;
885     response.PutChar ('O');
886     response.PutBytesAsRawHex8 (buffer, len);
887 
888     return SendPacketNoLock (response.GetData (), response.GetSize ());
889 }
890 
891 Error
892 GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
893 {
894     Error error;
895 
896     // Set up the reading/handling of process I/O
897     std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
898     if (!conn_up)
899     {
900         error.SetErrorString ("failed to create ConnectionFileDescriptor");
901         return error;
902     }
903 
904     Mutex::Locker locker(m_stdio_communication_mutex);
905     m_stdio_communication.SetCloseOnEOF (false);
906     m_stdio_communication.SetConnection (conn_up.release());
907     if (!m_stdio_communication.IsConnected ())
908     {
909         error.SetErrorString ("failed to set connection for inferior I/O communication");
910         return error;
911     }
912 
913     // llgs local-process debugging may specify PTY paths, which will make these
914     // file actions non-null
915     // process launch -e/o will also make these file actions non-null
916     // nullptr means that the traffic is expected to flow over gdb-remote protocol
917     if (
918         m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
919         m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
920         )
921     {
922         // output from the process must be forwarded over gdb-remote
923         m_stdio_handle_up = m_mainloop.RegisterReadObject(
924                 m_stdio_communication.GetConnection()->GetReadObject(),
925                 [this] (MainLoopBase &) { SendProcessOutput(); }, error);
926         if (! m_stdio_handle_up)
927         {
928             m_stdio_communication.Disconnect();
929             return error;
930         }
931     }
932 
933     return Error();
934 }
935 
936 void
937 GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
938 {
939     Mutex::Locker locker(m_stdio_communication_mutex);
940     m_stdio_handle_up.reset();
941 }
942 
943 void
944 GDBRemoteCommunicationServerLLGS::SendProcessOutput()
945 {
946     char buffer[1024];
947     ConnectionStatus status;
948     Error error;
949     Mutex::Locker locker(m_stdio_communication_mutex);
950     while (true)
951     {
952         size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
953         switch (status)
954         {
955         case eConnectionStatusSuccess:
956             SendONotification(buffer, bytes_read);
957             break;
958         case eConnectionStatusLostConnection:
959         case eConnectionStatusEndOfFile:
960         case eConnectionStatusError:
961         case eConnectionStatusNoConnection:
962             if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
963                 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
964             m_stdio_handle_up.reset();
965             return;
966 
967         case eConnectionStatusInterrupted:
968         case eConnectionStatusTimedOut:
969             return;
970         }
971     }
972 }
973 
974 GDBRemoteCommunication::PacketResult
975 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
976 {
977     // Fail if we don't have a current process.
978     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
979         return SendErrorResponse (68);
980 
981     lldb::pid_t pid = m_debugged_process_sp->GetID ();
982 
983     if (pid == LLDB_INVALID_PROCESS_ID)
984         return SendErrorResponse (1);
985 
986     ProcessInstanceInfo proc_info;
987     if (!Host::GetProcessInfo (pid, proc_info))
988         return SendErrorResponse (1);
989 
990     StreamString response;
991     CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
992     return SendPacketNoLock (response.GetData (), response.GetSize ());
993 }
994 
995 GDBRemoteCommunication::PacketResult
996 GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
997 {
998     // Fail if we don't have a current process.
999     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1000         return SendErrorResponse (68);
1001 
1002     // Make sure we set the current thread so g and p packets return
1003     // the data the gdb will expect.
1004     lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1005     SetCurrentThreadID (tid);
1006 
1007     NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1008     if (!thread_sp)
1009         return SendErrorResponse (69);
1010 
1011     StreamString response;
1012     response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1013 
1014     return SendPacketNoLock (response.GetData(), response.GetSize());
1015 }
1016 
1017 bool
1018 GDBRemoteCommunicationServerLLGS::DebuggedProcessReaped (lldb::pid_t pid)
1019 {
1020     // reap a process that we were debugging (but not debugserver)
1021     Mutex::Locker locker (m_spawned_pids_mutex);
1022     return m_spawned_pids.erase(pid) > 0;
1023 }
1024 
1025 bool
1026 GDBRemoteCommunicationServerLLGS::ReapDebuggedProcess (void *callback_baton,
1027                                         lldb::pid_t pid,
1028                                         bool exited,
1029                                         int signal,    // Zero for no signal
1030                                         int status)    // Exit value of process if signal is zero
1031 {
1032     GDBRemoteCommunicationServerLLGS *server = (GDBRemoteCommunicationServerLLGS *)callback_baton;
1033     server->DebuggedProcessReaped (pid);
1034     return true;
1035 }
1036 
1037 GDBRemoteCommunication::PacketResult
1038 GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1039 {
1040     // shutdown all spawned processes
1041     std::set<lldb::pid_t> spawned_pids_copy;
1042 
1043     // copy pids
1044     {
1045         Mutex::Locker locker (m_spawned_pids_mutex);
1046         spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
1047     }
1048 
1049     // nuke the spawned processes
1050     for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
1051     {
1052         lldb::pid_t spawned_pid = *it;
1053         if (!KillSpawnedProcess (spawned_pid))
1054         {
1055             fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
1056         }
1057     }
1058 
1059     StopSTDIOForwarding();
1060 
1061     // No OK response for kill packet.
1062     // return SendOKResponse ();
1063     return PacketResult::Success;
1064 }
1065 
1066 GDBRemoteCommunication::PacketResult
1067 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1068 {
1069     packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1070     if (packet.GetU32(0))
1071         m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1072     else
1073         m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1074     return SendOKResponse ();
1075 }
1076 
1077 GDBRemoteCommunication::PacketResult
1078 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1079 {
1080     packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1081     std::string path;
1082     packet.GetHexByteString (path);
1083     m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1084     return SendOKResponse ();
1085 }
1086 
1087 GDBRemoteCommunication::PacketResult
1088 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1089 {
1090     FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1091     if (working_dir)
1092     {
1093         StreamString response;
1094         response.PutCStringAsRawHex8(working_dir.GetCString());
1095         return SendPacketNoLock(response.GetData(), response.GetSize());
1096     }
1097 
1098     return SendErrorResponse(14);
1099 }
1100 
1101 GDBRemoteCommunication::PacketResult
1102 GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1103 {
1104     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1105     if (log)
1106         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1107 
1108     // Ensure we have a native process.
1109     if (!m_debugged_process_sp)
1110     {
1111         if (log)
1112             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1113         return SendErrorResponse (0x36);
1114     }
1115 
1116     // Pull out the signal number.
1117     packet.SetFilePos (::strlen ("C"));
1118     if (packet.GetBytesLeft () < 1)
1119     {
1120         // Shouldn't be using a C without a signal.
1121         return SendIllFormedResponse (packet, "C packet specified without signal.");
1122     }
1123     const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1124     if (signo == std::numeric_limits<uint32_t>::max ())
1125         return SendIllFormedResponse (packet, "failed to parse signal number");
1126 
1127     // Handle optional continue address.
1128     if (packet.GetBytesLeft () > 0)
1129     {
1130         // FIXME add continue at address support for $C{signo}[;{continue-address}].
1131         if (*packet.Peek () == ';')
1132             return SendUnimplementedResponse (packet.GetStringRef().c_str());
1133         else
1134             return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1135     }
1136 
1137     ResumeActionList resume_actions (StateType::eStateRunning, 0);
1138     Error error;
1139 
1140     // We have two branches: what to do if a continue thread is specified (in which case we target
1141     // sending the signal to that thread), or when we don't have a continue thread set (in which
1142     // case we send a signal to the process).
1143 
1144     // TODO discuss with Greg Clayton, make sure this makes sense.
1145 
1146     lldb::tid_t signal_tid = GetContinueThreadID ();
1147     if (signal_tid != LLDB_INVALID_THREAD_ID)
1148     {
1149         // The resume action for the continue thread (or all threads if a continue thread is not set).
1150         ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
1151 
1152         // Add the action for the continue thread (or all threads when the continue thread isn't present).
1153         resume_actions.Append (action);
1154     }
1155     else
1156     {
1157         // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1158         error = m_debugged_process_sp->Signal (signo);
1159         if (error.Fail ())
1160         {
1161             if (log)
1162                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1163                              __FUNCTION__,
1164                              m_debugged_process_sp->GetID (),
1165                              error.AsCString ());
1166 
1167             return SendErrorResponse (0x52);
1168         }
1169     }
1170 
1171     // Resume the threads.
1172     error = m_debugged_process_sp->Resume (resume_actions);
1173     if (error.Fail ())
1174     {
1175         if (log)
1176             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1177                          __FUNCTION__,
1178                          m_debugged_process_sp->GetID (),
1179                          error.AsCString ());
1180 
1181         return SendErrorResponse (0x38);
1182     }
1183 
1184     // Don't send an "OK" packet; response is the stopped/exited message.
1185     return PacketResult::Success;
1186 }
1187 
1188 GDBRemoteCommunication::PacketResult
1189 GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1190 {
1191     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1192     if (log)
1193         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1194 
1195     packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1196 
1197     // For now just support all continue.
1198     const bool has_continue_address = (packet.GetBytesLeft () > 0);
1199     if (has_continue_address)
1200     {
1201         if (log)
1202             log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1203         return SendUnimplementedResponse (packet.GetStringRef().c_str());
1204     }
1205 
1206     // Ensure we have a native process.
1207     if (!m_debugged_process_sp)
1208     {
1209         if (log)
1210             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1211         return SendErrorResponse (0x36);
1212     }
1213 
1214     // Build the ResumeActionList
1215     ResumeActionList actions (StateType::eStateRunning, 0);
1216 
1217     Error error = m_debugged_process_sp->Resume (actions);
1218     if (error.Fail ())
1219     {
1220         if (log)
1221         {
1222             log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1223                          __FUNCTION__,
1224                          m_debugged_process_sp->GetID (),
1225                          error.AsCString ());
1226         }
1227         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1228     }
1229 
1230     if (log)
1231         log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1232 
1233     // No response required from continue.
1234     return PacketResult::Success;
1235 }
1236 
1237 GDBRemoteCommunication::PacketResult
1238 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1239 {
1240     StreamString response;
1241     response.Printf("vCont;c;C;s;S");
1242 
1243     return SendPacketNoLock(response.GetData(), response.GetSize());
1244 }
1245 
1246 GDBRemoteCommunication::PacketResult
1247 GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1248 {
1249     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1250     if (log)
1251         log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1252 
1253     packet.SetFilePos (::strlen ("vCont"));
1254 
1255     if (packet.GetBytesLeft() == 0)
1256     {
1257         if (log)
1258             log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1259         return SendIllFormedResponse (packet, "Missing action from vCont package");
1260     }
1261 
1262     // Check if this is all continue (no options or ";c").
1263     if (::strcmp (packet.Peek (), ";c") == 0)
1264     {
1265         // Move past the ';', then do a simple 'c'.
1266         packet.SetFilePos (packet.GetFilePos () + 1);
1267         return Handle_c (packet);
1268     }
1269     else if (::strcmp (packet.Peek (), ";s") == 0)
1270     {
1271         // Move past the ';', then do a simple 's'.
1272         packet.SetFilePos (packet.GetFilePos () + 1);
1273         return Handle_s (packet);
1274     }
1275 
1276     // Ensure we have a native process.
1277     if (!m_debugged_process_sp)
1278     {
1279         if (log)
1280             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1281         return SendErrorResponse (0x36);
1282     }
1283 
1284     ResumeActionList thread_actions;
1285 
1286     while (packet.GetBytesLeft () && *packet.Peek () == ';')
1287     {
1288         // Skip the semi-colon.
1289         packet.GetChar ();
1290 
1291         // Build up the thread action.
1292         ResumeAction thread_action;
1293         thread_action.tid = LLDB_INVALID_THREAD_ID;
1294         thread_action.state = eStateInvalid;
1295         thread_action.signal = 0;
1296 
1297         const char action = packet.GetChar ();
1298         switch (action)
1299         {
1300             case 'C':
1301                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1302                 if (thread_action.signal == 0)
1303                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1304                 // Fall through to next case...
1305 
1306             case 'c':
1307                 // Continue
1308                 thread_action.state = eStateRunning;
1309                 break;
1310 
1311             case 'S':
1312                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1313                 if (thread_action.signal == 0)
1314                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1315                 // Fall through to next case...
1316 
1317             case 's':
1318                 // Step
1319                 thread_action.state = eStateStepping;
1320                 break;
1321 
1322             default:
1323                 return SendIllFormedResponse (packet, "Unsupported vCont action");
1324                 break;
1325         }
1326 
1327         // Parse out optional :{thread-id} value.
1328         if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1329         {
1330             // Consume the separator.
1331             packet.GetChar ();
1332 
1333             thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1334             if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1335                 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1336         }
1337 
1338         thread_actions.Append (thread_action);
1339     }
1340 
1341     Error error = m_debugged_process_sp->Resume (thread_actions);
1342     if (error.Fail ())
1343     {
1344         if (log)
1345         {
1346             log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1347                          __FUNCTION__,
1348                          m_debugged_process_sp->GetID (),
1349                          error.AsCString ());
1350         }
1351         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1352     }
1353 
1354     if (log)
1355         log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1356 
1357     // No response required from vCont.
1358     return PacketResult::Success;
1359 }
1360 
1361 void
1362 GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1363 {
1364     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1365     if (log)
1366         log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1367 
1368     m_current_tid = tid;
1369     if (m_debugged_process_sp)
1370         m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1371 }
1372 
1373 void
1374 GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1375 {
1376     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1377     if (log)
1378         log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1379 
1380     m_continue_tid = tid;
1381 }
1382 
1383 GDBRemoteCommunication::PacketResult
1384 GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1385 {
1386     // Handle the $? gdbremote command.
1387 
1388     // If no process, indicate error
1389     if (!m_debugged_process_sp)
1390         return SendErrorResponse (02);
1391 
1392     return SendStopReasonForState (m_debugged_process_sp->GetState());
1393 }
1394 
1395 GDBRemoteCommunication::PacketResult
1396 GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
1397 {
1398     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1399 
1400     switch (process_state)
1401     {
1402         case eStateAttaching:
1403         case eStateLaunching:
1404         case eStateRunning:
1405         case eStateStepping:
1406         case eStateDetached:
1407             // NOTE: gdb protocol doc looks like it should return $OK
1408             // when everything is running (i.e. no stopped result).
1409             return PacketResult::Success;  // Ignore
1410 
1411         case eStateSuspended:
1412         case eStateStopped:
1413         case eStateCrashed:
1414         {
1415             lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1416             // Make sure we set the current thread so g and p packets return
1417             // the data the gdb will expect.
1418             SetCurrentThreadID (tid);
1419             return SendStopReplyPacketForThread (tid);
1420         }
1421 
1422         case eStateInvalid:
1423         case eStateUnloaded:
1424         case eStateExited:
1425             return SendWResponse(m_debugged_process_sp.get());
1426 
1427         default:
1428             if (log)
1429             {
1430                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1431                              __FUNCTION__,
1432                              m_debugged_process_sp->GetID (),
1433                              StateAsCString (process_state));
1434             }
1435             break;
1436     }
1437 
1438     return SendErrorResponse (0);
1439 }
1440 
1441 GDBRemoteCommunication::PacketResult
1442 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1443 {
1444     // Fail if we don't have a current process.
1445     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1446         return SendErrorResponse (68);
1447 
1448     // Ensure we have a thread.
1449     NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1450     if (!thread_sp)
1451         return SendErrorResponse (69);
1452 
1453     // Get the register context for the first thread.
1454     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1455     if (!reg_context_sp)
1456         return SendErrorResponse (69);
1457 
1458     // Parse out the register number from the request.
1459     packet.SetFilePos (strlen("qRegisterInfo"));
1460     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1461     if (reg_index == std::numeric_limits<uint32_t>::max ())
1462         return SendErrorResponse (69);
1463 
1464     // Return the end of registers response if we've iterated one past the end of the register set.
1465     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1466         return SendErrorResponse (69);
1467 
1468     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1469     if (!reg_info)
1470         return SendErrorResponse (69);
1471 
1472     // Build the reginfos response.
1473     StreamGDBRemote response;
1474 
1475     response.PutCString ("name:");
1476     response.PutCString (reg_info->name);
1477     response.PutChar (';');
1478 
1479     if (reg_info->alt_name && reg_info->alt_name[0])
1480     {
1481         response.PutCString ("alt-name:");
1482         response.PutCString (reg_info->alt_name);
1483         response.PutChar (';');
1484     }
1485 
1486     response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1487 
1488     switch (reg_info->encoding)
1489     {
1490         case eEncodingUint:    response.PutCString ("encoding:uint;"); break;
1491         case eEncodingSint:    response.PutCString ("encoding:sint;"); break;
1492         case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1493         case eEncodingVector:  response.PutCString ("encoding:vector;"); break;
1494         default: break;
1495     }
1496 
1497     switch (reg_info->format)
1498     {
1499         case eFormatBinary:          response.PutCString ("format:binary;"); break;
1500         case eFormatDecimal:         response.PutCString ("format:decimal;"); break;
1501         case eFormatHex:             response.PutCString ("format:hex;"); break;
1502         case eFormatFloat:           response.PutCString ("format:float;"); break;
1503         case eFormatVectorOfSInt8:   response.PutCString ("format:vector-sint8;"); break;
1504         case eFormatVectorOfUInt8:   response.PutCString ("format:vector-uint8;"); break;
1505         case eFormatVectorOfSInt16:  response.PutCString ("format:vector-sint16;"); break;
1506         case eFormatVectorOfUInt16:  response.PutCString ("format:vector-uint16;"); break;
1507         case eFormatVectorOfSInt32:  response.PutCString ("format:vector-sint32;"); break;
1508         case eFormatVectorOfUInt32:  response.PutCString ("format:vector-uint32;"); break;
1509         case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1510         case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1511         default: break;
1512     };
1513 
1514     const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1515     if (register_set_name)
1516     {
1517         response.PutCString ("set:");
1518         response.PutCString (register_set_name);
1519         response.PutChar (';');
1520     }
1521 
1522     if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
1523         response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
1524 
1525     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1526         response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1527 
1528     switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1529     {
1530         case LLDB_REGNUM_GENERIC_PC:     response.PutCString("generic:pc;"); break;
1531         case LLDB_REGNUM_GENERIC_SP:     response.PutCString("generic:sp;"); break;
1532         case LLDB_REGNUM_GENERIC_FP:     response.PutCString("generic:fp;"); break;
1533         case LLDB_REGNUM_GENERIC_RA:     response.PutCString("generic:ra;"); break;
1534         case LLDB_REGNUM_GENERIC_FLAGS:  response.PutCString("generic:flags;"); break;
1535         case LLDB_REGNUM_GENERIC_ARG1:   response.PutCString("generic:arg1;"); break;
1536         case LLDB_REGNUM_GENERIC_ARG2:   response.PutCString("generic:arg2;"); break;
1537         case LLDB_REGNUM_GENERIC_ARG3:   response.PutCString("generic:arg3;"); break;
1538         case LLDB_REGNUM_GENERIC_ARG4:   response.PutCString("generic:arg4;"); break;
1539         case LLDB_REGNUM_GENERIC_ARG5:   response.PutCString("generic:arg5;"); break;
1540         case LLDB_REGNUM_GENERIC_ARG6:   response.PutCString("generic:arg6;"); break;
1541         case LLDB_REGNUM_GENERIC_ARG7:   response.PutCString("generic:arg7;"); break;
1542         case LLDB_REGNUM_GENERIC_ARG8:   response.PutCString("generic:arg8;"); break;
1543         default: break;
1544     }
1545 
1546     if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1547     {
1548         response.PutCString ("container-regs:");
1549         int i = 0;
1550         for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1551         {
1552             if (i > 0)
1553                 response.PutChar (',');
1554             response.Printf ("%" PRIx32, *reg_num);
1555         }
1556         response.PutChar (';');
1557     }
1558 
1559     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1560     {
1561         response.PutCString ("invalidate-regs:");
1562         int i = 0;
1563         for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1564         {
1565             if (i > 0)
1566                 response.PutChar (',');
1567             response.Printf ("%" PRIx32, *reg_num);
1568         }
1569         response.PutChar (';');
1570     }
1571 
1572     return SendPacketNoLock(response.GetData(), response.GetSize());
1573 }
1574 
1575 GDBRemoteCommunication::PacketResult
1576 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1577 {
1578     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1579 
1580     // Fail if we don't have a current process.
1581     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1582     {
1583         if (log)
1584             log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1585         return SendOKResponse ();
1586     }
1587 
1588     StreamGDBRemote response;
1589     response.PutChar ('m');
1590 
1591     if (log)
1592         log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1593 
1594     NativeThreadProtocolSP thread_sp;
1595     uint32_t thread_index;
1596     for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1597          thread_sp;
1598          ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1599     {
1600         if (log)
1601             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);
1602         if (thread_index > 0)
1603             response.PutChar(',');
1604         response.Printf ("%" PRIx64, thread_sp->GetID ());
1605     }
1606 
1607     if (log)
1608         log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1609 
1610     return SendPacketNoLock(response.GetData(), response.GetSize());
1611 }
1612 
1613 GDBRemoteCommunication::PacketResult
1614 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1615 {
1616     // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1617     return SendPacketNoLock ("l", 1);
1618 }
1619 
1620 GDBRemoteCommunication::PacketResult
1621 GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1622 {
1623     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1624 
1625     // Parse out the register number from the request.
1626     packet.SetFilePos (strlen("p"));
1627     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1628     if (reg_index == std::numeric_limits<uint32_t>::max ())
1629     {
1630         if (log)
1631             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1632         return SendErrorResponse (0x15);
1633     }
1634 
1635     // Get the thread to use.
1636     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1637     if (!thread_sp)
1638     {
1639         if (log)
1640             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1641         return SendErrorResponse (0x15);
1642     }
1643 
1644     // Get the thread's register context.
1645     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1646     if (!reg_context_sp)
1647     {
1648         if (log)
1649             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 ());
1650         return SendErrorResponse (0x15);
1651     }
1652 
1653     // Return the end of registers response if we've iterated one past the end of the register set.
1654     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1655     {
1656         if (log)
1657             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1658         return SendErrorResponse (0x15);
1659     }
1660 
1661     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1662     if (!reg_info)
1663     {
1664         if (log)
1665             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1666         return SendErrorResponse (0x15);
1667     }
1668 
1669     // Build the reginfos response.
1670     StreamGDBRemote response;
1671 
1672     // Retrieve the value
1673     RegisterValue reg_value;
1674     Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1675     if (error.Fail ())
1676     {
1677         if (log)
1678             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1679         return SendErrorResponse (0x15);
1680     }
1681 
1682     const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1683     if (!data)
1684     {
1685         if (log)
1686             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1687         return SendErrorResponse (0x15);
1688     }
1689 
1690     // FIXME flip as needed to get data in big/little endian format for this host.
1691     for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1692         response.PutHex8 (data[i]);
1693 
1694     return SendPacketNoLock (response.GetData (), response.GetSize ());
1695 }
1696 
1697 GDBRemoteCommunication::PacketResult
1698 GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1699 {
1700     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1701 
1702     // Ensure there is more content.
1703     if (packet.GetBytesLeft () < 1)
1704         return SendIllFormedResponse (packet, "Empty P packet");
1705 
1706     // Parse out the register number from the request.
1707     packet.SetFilePos (strlen("P"));
1708     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1709     if (reg_index == std::numeric_limits<uint32_t>::max ())
1710     {
1711         if (log)
1712             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1713         return SendErrorResponse (0x29);
1714     }
1715 
1716     // Note debugserver would send an E30 here.
1717     if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1718         return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1719 
1720     // Get process architecture.
1721     ArchSpec process_arch;
1722     if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1723     {
1724         if (log)
1725             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1726         return SendErrorResponse (0x49);
1727     }
1728 
1729     // Parse out the value.
1730     uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1731     size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1732 
1733     // Get the thread to use.
1734     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1735     if (!thread_sp)
1736     {
1737         if (log)
1738             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1739         return SendErrorResponse (0x28);
1740     }
1741 
1742     // Get the thread's register context.
1743     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1744     if (!reg_context_sp)
1745     {
1746         if (log)
1747             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 ());
1748         return SendErrorResponse (0x15);
1749     }
1750 
1751     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1752     if (!reg_info)
1753     {
1754         if (log)
1755             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1756         return SendErrorResponse (0x48);
1757     }
1758 
1759     // Return the end of registers response if we've iterated one past the end of the register set.
1760     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1761     {
1762         if (log)
1763             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1764         return SendErrorResponse (0x47);
1765     }
1766 
1767     if (reg_size != reg_info->byte_size)
1768     {
1769         return SendIllFormedResponse (packet, "P packet register size is incorrect");
1770     }
1771 
1772     // Build the reginfos response.
1773     StreamGDBRemote response;
1774 
1775     RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1776     Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1777     if (error.Fail ())
1778     {
1779         if (log)
1780             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1781         return SendErrorResponse (0x32);
1782     }
1783 
1784     return SendOKResponse();
1785 }
1786 
1787 GDBRemoteCommunication::PacketResult
1788 GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1789 {
1790     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1791 
1792     // Fail if we don't have a current process.
1793     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1794     {
1795         if (log)
1796             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1797         return SendErrorResponse (0x15);
1798     }
1799 
1800     // Parse out which variant of $H is requested.
1801     packet.SetFilePos (strlen("H"));
1802     if (packet.GetBytesLeft () < 1)
1803     {
1804         if (log)
1805             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1806         return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1807     }
1808 
1809     const char h_variant = packet.GetChar ();
1810     switch (h_variant)
1811     {
1812         case 'g':
1813             break;
1814 
1815         case 'c':
1816             break;
1817 
1818         default:
1819             if (log)
1820                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1821             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1822     }
1823 
1824     // Parse out the thread number.
1825     // FIXME return a parse success/fail value.  All values are valid here.
1826     const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1827 
1828     // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1829     if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1830     {
1831         NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1832         if (!thread_sp)
1833         {
1834             if (log)
1835                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1836             return SendErrorResponse (0x15);
1837         }
1838     }
1839 
1840     // Now switch the given thread type.
1841     switch (h_variant)
1842     {
1843         case 'g':
1844             SetCurrentThreadID (tid);
1845             break;
1846 
1847         case 'c':
1848             SetContinueThreadID (tid);
1849             break;
1850 
1851         default:
1852             assert (false && "unsupported $H variant - shouldn't get here");
1853             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1854     }
1855 
1856     return SendOKResponse();
1857 }
1858 
1859 GDBRemoteCommunication::PacketResult
1860 GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1861 {
1862     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1863 
1864     // Fail if we don't have a current process.
1865     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1866     {
1867         if (log)
1868             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1869         return SendErrorResponse (0x15);
1870     }
1871 
1872     packet.SetFilePos (::strlen("I"));
1873     char tmp[4096];
1874     for (;;)
1875     {
1876         size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1877         if (read == 0)
1878         {
1879             break;
1880         }
1881         // write directly to stdin *this might block if stdin buffer is full*
1882         // TODO: enqueue this block in circular buffer and send window size to remote host
1883         ConnectionStatus status;
1884         Error error;
1885         Mutex::Locker locker(m_stdio_communication_mutex);
1886         m_stdio_communication.Write(tmp, read, status, &error);
1887         if (error.Fail())
1888         {
1889             return SendErrorResponse (0x15);
1890         }
1891     }
1892 
1893     return SendOKResponse();
1894 }
1895 
1896 GDBRemoteCommunication::PacketResult
1897 GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1898 {
1899     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1900 
1901     // Fail if we don't have a current process.
1902     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1903     {
1904         if (log)
1905             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1906         return SendErrorResponse (0x15);
1907     }
1908 
1909     // Interrupt the process.
1910     Error error = m_debugged_process_sp->Interrupt ();
1911     if (error.Fail ())
1912     {
1913         if (log)
1914         {
1915             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1916                          __FUNCTION__,
1917                          m_debugged_process_sp->GetID (),
1918                          error.AsCString ());
1919         }
1920         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1921     }
1922 
1923     if (log)
1924         log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1925 
1926     // No response required from stop all.
1927     return PacketResult::Success;
1928 }
1929 
1930 GDBRemoteCommunication::PacketResult
1931 GDBRemoteCommunicationServerLLGS::Handle_m (StringExtractorGDBRemote &packet)
1932 {
1933     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1934 
1935     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1936     {
1937         if (log)
1938             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1939         return SendErrorResponse (0x15);
1940     }
1941 
1942     // Parse out the memory address.
1943     packet.SetFilePos (strlen("m"));
1944     if (packet.GetBytesLeft() < 1)
1945         return SendIllFormedResponse(packet, "Too short m packet");
1946 
1947     // Read the address.  Punting on validation.
1948     // FIXME replace with Hex U64 read with no default value that fails on failed read.
1949     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
1950 
1951     // Validate comma.
1952     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
1953         return SendIllFormedResponse(packet, "Comma sep missing in m packet");
1954 
1955     // Get # bytes to read.
1956     if (packet.GetBytesLeft() < 1)
1957         return SendIllFormedResponse(packet, "Length missing in m packet");
1958 
1959     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
1960     if (byte_count == 0)
1961     {
1962         if (log)
1963             log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
1964         return PacketResult::Success;
1965     }
1966 
1967     // Allocate the response buffer.
1968     std::string buf(byte_count, '\0');
1969     if (buf.empty())
1970         return SendErrorResponse (0x78);
1971 
1972 
1973     // Retrieve the process memory.
1974     size_t bytes_read = 0;
1975     Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
1976     if (error.Fail ())
1977     {
1978         if (log)
1979             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
1980         return SendErrorResponse (0x08);
1981     }
1982 
1983     if (bytes_read == 0)
1984     {
1985         if (log)
1986             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);
1987         return SendErrorResponse (0x08);
1988     }
1989 
1990     StreamGDBRemote response;
1991     for (size_t i = 0; i < bytes_read; ++i)
1992         response.PutHex8(buf[i]);
1993 
1994     return SendPacketNoLock(response.GetData(), response.GetSize());
1995 }
1996 
1997 GDBRemoteCommunication::PacketResult
1998 GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
1999 {
2000     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2001 
2002     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2003     {
2004         if (log)
2005             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2006         return SendErrorResponse (0x15);
2007     }
2008 
2009     // Parse out the memory address.
2010     packet.SetFilePos (strlen("M"));
2011     if (packet.GetBytesLeft() < 1)
2012         return SendIllFormedResponse(packet, "Too short M packet");
2013 
2014     // Read the address.  Punting on validation.
2015     // FIXME replace with Hex U64 read with no default value that fails on failed read.
2016     const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2017 
2018     // Validate comma.
2019     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2020         return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2021 
2022     // Get # bytes to read.
2023     if (packet.GetBytesLeft() < 1)
2024         return SendIllFormedResponse(packet, "Length missing in M packet");
2025 
2026     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2027     if (byte_count == 0)
2028     {
2029         if (log)
2030             log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2031         return PacketResult::Success;
2032     }
2033 
2034     // Validate colon.
2035     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2036         return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2037 
2038     // Allocate the conversion buffer.
2039     std::vector<uint8_t> buf(byte_count, 0);
2040     if (buf.empty())
2041         return SendErrorResponse (0x78);
2042 
2043     // Convert the hex memory write contents to bytes.
2044     StreamGDBRemote response;
2045     const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
2046     if (convert_count != byte_count)
2047     {
2048         if (log)
2049             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);
2050         return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2051     }
2052 
2053     // Write the process memory.
2054     size_t bytes_written = 0;
2055     Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
2056     if (error.Fail ())
2057     {
2058         if (log)
2059             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2060         return SendErrorResponse (0x09);
2061     }
2062 
2063     if (bytes_written == 0)
2064     {
2065         if (log)
2066             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);
2067         return SendErrorResponse (0x09);
2068     }
2069 
2070     return SendOKResponse ();
2071 }
2072 
2073 GDBRemoteCommunication::PacketResult
2074 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2075 {
2076     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2077 
2078     // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2079     // request, but we're not guaranteed to be attached to a process.  For now we'll assume the
2080     // client only asks this when a process is being debugged.
2081 
2082     // Ensure we have a process running; otherwise, we can't figure this out
2083     // since we won't have a NativeProcessProtocol.
2084     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2085     {
2086         if (log)
2087             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2088         return SendErrorResponse (0x15);
2089     }
2090 
2091     // Test if we can get any region back when asking for the region around NULL.
2092     MemoryRegionInfo region_info;
2093     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2094     if (error.Fail ())
2095     {
2096         // We don't support memory region info collection for this NativeProcessProtocol.
2097         return SendUnimplementedResponse ("");
2098     }
2099 
2100     return SendOKResponse();
2101 }
2102 
2103 GDBRemoteCommunication::PacketResult
2104 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2105 {
2106     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2107 
2108     // Ensure we have a process.
2109     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2110     {
2111         if (log)
2112             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2113         return SendErrorResponse (0x15);
2114     }
2115 
2116     // Parse out the memory address.
2117     packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2118     if (packet.GetBytesLeft() < 1)
2119         return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2120 
2121     // Read the address.  Punting on validation.
2122     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2123 
2124     StreamGDBRemote response;
2125 
2126     // Get the memory region info for the target address.
2127     MemoryRegionInfo region_info;
2128     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2129     if (error.Fail ())
2130     {
2131         // Return the error message.
2132 
2133         response.PutCString ("error:");
2134         response.PutCStringAsRawHex8 (error.AsCString ());
2135         response.PutChar (';');
2136     }
2137     else
2138     {
2139         // Range start and size.
2140         response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2141 
2142         // Permissions.
2143         if (region_info.GetReadable () ||
2144             region_info.GetWritable () ||
2145             region_info.GetExecutable ())
2146         {
2147             // Write permissions info.
2148             response.PutCString ("permissions:");
2149 
2150             if (region_info.GetReadable ())
2151                 response.PutChar ('r');
2152             if (region_info.GetWritable ())
2153                 response.PutChar('w');
2154             if (region_info.GetExecutable())
2155                 response.PutChar ('x');
2156 
2157             response.PutChar (';');
2158         }
2159     }
2160 
2161     return SendPacketNoLock(response.GetData(), response.GetSize());
2162 }
2163 
2164 GDBRemoteCommunication::PacketResult
2165 GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2166 {
2167     // Ensure we have a process.
2168     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2169     {
2170         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2171         if (log)
2172             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2173         return SendErrorResponse (0x15);
2174     }
2175 
2176     // Parse out software or hardware breakpoint or watchpoint requested.
2177     packet.SetFilePos (strlen("Z"));
2178     if (packet.GetBytesLeft() < 1)
2179         return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2180 
2181     bool want_breakpoint = true;
2182     bool want_hardware = false;
2183 
2184     const GDBStoppointType stoppoint_type =
2185         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2186     switch (stoppoint_type)
2187     {
2188         case eBreakpointSoftware:
2189             want_hardware = false; want_breakpoint = true;  break;
2190         case eBreakpointHardware:
2191             want_hardware = true;  want_breakpoint = true;  break;
2192         case eWatchpointWrite:
2193             want_hardware = true;  want_breakpoint = false; break;
2194         case eWatchpointRead:
2195             want_hardware = true;  want_breakpoint = false; break;
2196         case eWatchpointReadWrite:
2197             want_hardware = true;  want_breakpoint = false; break;
2198         case eStoppointInvalid:
2199             return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2200 
2201     }
2202 
2203     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2204         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2205 
2206     // Parse out the stoppoint address.
2207     if (packet.GetBytesLeft() < 1)
2208         return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2209     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2210 
2211     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2212         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2213 
2214     // Parse out the stoppoint size (i.e. size hint for opcode size).
2215     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2216     if (size == std::numeric_limits<uint32_t>::max ())
2217         return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2218 
2219     if (want_breakpoint)
2220     {
2221         // Try to set the breakpoint.
2222         const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2223         if (error.Success ())
2224             return SendOKResponse ();
2225         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2226         if (log)
2227             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2228                     " failed to set breakpoint: %s",
2229                     __FUNCTION__,
2230                     m_debugged_process_sp->GetID (),
2231                     error.AsCString ());
2232         return SendErrorResponse (0x09);
2233     }
2234     else
2235     {
2236         uint32_t watch_flags =
2237             stoppoint_type == eWatchpointWrite
2238             ? 0x1  // Write
2239             : 0x3; // ReadWrite
2240 
2241         // Try to set the watchpoint.
2242         const Error error = m_debugged_process_sp->SetWatchpoint (
2243                 addr, size, watch_flags, want_hardware);
2244         if (error.Success ())
2245             return SendOKResponse ();
2246         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2247         if (log)
2248             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2249                     " failed to set watchpoint: %s",
2250                     __FUNCTION__,
2251                     m_debugged_process_sp->GetID (),
2252                     error.AsCString ());
2253         return SendErrorResponse (0x09);
2254     }
2255 }
2256 
2257 GDBRemoteCommunication::PacketResult
2258 GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2259 {
2260     // Ensure we have a process.
2261     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2262     {
2263         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2264         if (log)
2265             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2266         return SendErrorResponse (0x15);
2267     }
2268 
2269     // Parse out software or hardware breakpoint or watchpoint requested.
2270     packet.SetFilePos (strlen("z"));
2271     if (packet.GetBytesLeft() < 1)
2272         return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2273 
2274     bool want_breakpoint = true;
2275 
2276     const GDBStoppointType stoppoint_type =
2277         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2278     switch (stoppoint_type)
2279     {
2280         case eBreakpointHardware:  want_breakpoint = true;  break;
2281         case eBreakpointSoftware:  want_breakpoint = true;  break;
2282         case eWatchpointWrite:     want_breakpoint = false; break;
2283         case eWatchpointRead:      want_breakpoint = false; break;
2284         case eWatchpointReadWrite: want_breakpoint = false; break;
2285         default:
2286             return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2287 
2288     }
2289 
2290     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2291         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2292 
2293     // Parse out the stoppoint address.
2294     if (packet.GetBytesLeft() < 1)
2295         return SendIllFormedResponse(packet, "Too short z packet, missing address");
2296     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2297 
2298     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2299         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2300 
2301     /*
2302     // Parse out the stoppoint size (i.e. size hint for opcode size).
2303     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2304     if (size == std::numeric_limits<uint32_t>::max ())
2305         return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2306     */
2307 
2308     if (want_breakpoint)
2309     {
2310         // Try to clear the breakpoint.
2311         const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2312         if (error.Success ())
2313             return SendOKResponse ();
2314         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2315         if (log)
2316             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2317                     " failed to remove breakpoint: %s",
2318                     __FUNCTION__,
2319                     m_debugged_process_sp->GetID (),
2320                     error.AsCString ());
2321         return SendErrorResponse (0x09);
2322     }
2323     else
2324     {
2325         // Try to clear the watchpoint.
2326         const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2327         if (error.Success ())
2328             return SendOKResponse ();
2329         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2330         if (log)
2331             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2332                     " failed to remove watchpoint: %s",
2333                     __FUNCTION__,
2334                     m_debugged_process_sp->GetID (),
2335                     error.AsCString ());
2336         return SendErrorResponse (0x09);
2337     }
2338 }
2339 
2340 GDBRemoteCommunication::PacketResult
2341 GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2342 {
2343     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2344 
2345     // Ensure we have a process.
2346     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2347     {
2348         if (log)
2349             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2350         return SendErrorResponse (0x32);
2351     }
2352 
2353     // We first try to use a continue thread id.  If any one or any all set, use the current thread.
2354     // Bail out if we don't have a thread id.
2355     lldb::tid_t tid = GetContinueThreadID ();
2356     if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2357         tid = GetCurrentThreadID ();
2358     if (tid == LLDB_INVALID_THREAD_ID)
2359         return SendErrorResponse (0x33);
2360 
2361     // Double check that we have such a thread.
2362     // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2363     NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2364     if (!thread_sp || thread_sp->GetID () != tid)
2365         return SendErrorResponse (0x33);
2366 
2367     // Create the step action for the given thread.
2368     ResumeAction action = { tid, eStateStepping, 0 };
2369 
2370     // Setup the actions list.
2371     ResumeActionList actions;
2372     actions.Append (action);
2373 
2374     // All other threads stop while we're single stepping a thread.
2375     actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2376     Error error = m_debugged_process_sp->Resume (actions);
2377     if (error.Fail ())
2378     {
2379         if (log)
2380             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2381         return SendErrorResponse(0x49);
2382     }
2383 
2384     // No response here - the stop or exit will come from the resulting action.
2385     return PacketResult::Success;
2386 }
2387 
2388 GDBRemoteCommunication::PacketResult
2389 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2390 {
2391     // *BSD impls should be able to do this too.
2392 #if defined(__linux__)
2393     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2394 
2395     // Parse out the offset.
2396     packet.SetFilePos (strlen("qXfer:auxv:read::"));
2397     if (packet.GetBytesLeft () < 1)
2398         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2399 
2400     const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2401     if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2402         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2403 
2404     // Parse out comma.
2405     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2406         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2407 
2408     // Parse out the length.
2409     const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2410     if (auxv_length == std::numeric_limits<uint64_t>::max ())
2411         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2412 
2413     // Grab the auxv data if we need it.
2414     if (!m_active_auxv_buffer_sp)
2415     {
2416         // Make sure we have a valid process.
2417         if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2418         {
2419             if (log)
2420                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2421             return SendErrorResponse (0x10);
2422         }
2423 
2424         // Grab the auxv data.
2425         m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2426         if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () ==  0)
2427         {
2428             // Hmm, no auxv data, call that an error.
2429             if (log)
2430                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2431             m_active_auxv_buffer_sp.reset ();
2432             return SendErrorResponse (0x11);
2433         }
2434     }
2435 
2436     // FIXME find out if/how I lock the stream here.
2437 
2438     StreamGDBRemote response;
2439     bool done_with_buffer = false;
2440 
2441     if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2442     {
2443         // We have nothing left to send.  Mark the buffer as complete.
2444         response.PutChar ('l');
2445         done_with_buffer = true;
2446     }
2447     else
2448     {
2449         // Figure out how many bytes are available starting at the given offset.
2450         const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2451 
2452         // Figure out how many bytes we're going to read.
2453         const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2454 
2455         // Mark the response type according to whether we're reading the remainder of the auxv data.
2456         if (bytes_to_read >= bytes_remaining)
2457         {
2458             // There will be nothing left to read after this
2459             response.PutChar ('l');
2460             done_with_buffer = true;
2461         }
2462         else
2463         {
2464             // There will still be bytes to read after this request.
2465             response.PutChar ('m');
2466         }
2467 
2468         // Now write the data in encoded binary form.
2469         response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2470     }
2471 
2472     if (done_with_buffer)
2473         m_active_auxv_buffer_sp.reset ();
2474 
2475     return SendPacketNoLock(response.GetData(), response.GetSize());
2476 #else
2477     return SendUnimplementedResponse ("not implemented on this platform");
2478 #endif
2479 }
2480 
2481 GDBRemoteCommunication::PacketResult
2482 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2483 {
2484     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2485 
2486     // Move past packet name.
2487     packet.SetFilePos (strlen ("QSaveRegisterState"));
2488 
2489     // Get the thread to use.
2490     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2491     if (!thread_sp)
2492     {
2493         if (m_thread_suffix_supported)
2494             return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2495         else
2496             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2497     }
2498 
2499     // Grab the register context for the thread.
2500     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2501     if (!reg_context_sp)
2502     {
2503         if (log)
2504             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 ());
2505         return SendErrorResponse (0x15);
2506     }
2507 
2508     // Save registers to a buffer.
2509     DataBufferSP register_data_sp;
2510     Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2511     if (error.Fail ())
2512     {
2513         if (log)
2514             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2515         return SendErrorResponse (0x75);
2516     }
2517 
2518     // Allocate a new save id.
2519     const uint32_t save_id = GetNextSavedRegistersID ();
2520     assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2521 
2522     // Save the register data buffer under the save id.
2523     {
2524         Mutex::Locker locker (m_saved_registers_mutex);
2525         m_saved_registers_map[save_id] = register_data_sp;
2526     }
2527 
2528     // Write the response.
2529     StreamGDBRemote response;
2530     response.Printf ("%" PRIu32, save_id);
2531     return SendPacketNoLock(response.GetData(), response.GetSize());
2532 }
2533 
2534 GDBRemoteCommunication::PacketResult
2535 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2536 {
2537     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2538 
2539     // Parse out save id.
2540     packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2541     if (packet.GetBytesLeft () < 1)
2542         return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2543 
2544     const uint32_t save_id = packet.GetU32 (0);
2545     if (save_id == 0)
2546     {
2547         if (log)
2548             log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2549         return SendErrorResponse (0x76);
2550     }
2551 
2552     // Get the thread to use.
2553     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2554     if (!thread_sp)
2555     {
2556         if (m_thread_suffix_supported)
2557             return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2558         else
2559             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2560     }
2561 
2562     // Grab the register context for the thread.
2563     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2564     if (!reg_context_sp)
2565     {
2566         if (log)
2567             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 ());
2568         return SendErrorResponse (0x15);
2569     }
2570 
2571     // Retrieve register state buffer, then remove from the list.
2572     DataBufferSP register_data_sp;
2573     {
2574         Mutex::Locker locker (m_saved_registers_mutex);
2575 
2576         // Find the register set buffer for the given save id.
2577         auto it = m_saved_registers_map.find (save_id);
2578         if (it == m_saved_registers_map.end ())
2579         {
2580             if (log)
2581                 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);
2582             return SendErrorResponse (0x77);
2583         }
2584         register_data_sp = it->second;
2585 
2586         // Remove it from the map.
2587         m_saved_registers_map.erase (it);
2588     }
2589 
2590     Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2591     if (error.Fail ())
2592     {
2593         if (log)
2594             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2595         return SendErrorResponse (0x77);
2596     }
2597 
2598     return SendOKResponse();
2599 }
2600 
2601 GDBRemoteCommunication::PacketResult
2602 GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2603 {
2604     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2605 
2606     // Consume the ';' after vAttach.
2607     packet.SetFilePos (strlen ("vAttach"));
2608     if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2609         return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2610 
2611     // Grab the PID to which we will attach (assume hex encoding).
2612     lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2613     if (pid == LLDB_INVALID_PROCESS_ID)
2614         return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2615 
2616     // Attempt to attach.
2617     if (log)
2618         log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2619 
2620     Error error = AttachToProcess (pid);
2621 
2622     if (error.Fail ())
2623     {
2624         if (log)
2625             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2626         return SendErrorResponse (0x01);
2627     }
2628 
2629     // Notify we attached by sending a stop packet.
2630     return SendStopReasonForState (m_debugged_process_sp->GetState ());
2631 }
2632 
2633 GDBRemoteCommunication::PacketResult
2634 GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2635 {
2636     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2637 
2638     StopSTDIOForwarding();
2639 
2640     // Scope for mutex locker.
2641     Mutex::Locker locker (m_spawned_pids_mutex);
2642 
2643     // Fail if we don't have a current process.
2644     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2645     {
2646         if (log)
2647             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2648         return SendErrorResponse (0x15);
2649     }
2650 
2651     if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end())
2652     {
2653         if (log)
2654             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to find PID %" PRIu64 " in spawned pids list",
2655                          __FUNCTION__, m_debugged_process_sp->GetID ());
2656         return SendErrorResponse (0x1);
2657     }
2658 
2659     lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2660 
2661     // Consume the ';' after D.
2662     packet.SetFilePos (1);
2663     if (packet.GetBytesLeft ())
2664     {
2665         if (packet.GetChar () != ';')
2666             return SendIllFormedResponse (packet, "D missing expected ';'");
2667 
2668         // Grab the PID from which we will detach (assume hex encoding).
2669         pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2670         if (pid == LLDB_INVALID_PROCESS_ID)
2671             return SendIllFormedResponse (packet, "D failed to parse the process id");
2672     }
2673 
2674     if (pid != LLDB_INVALID_PROCESS_ID &&
2675         m_debugged_process_sp->GetID () != pid)
2676     {
2677         return SendIllFormedResponse (packet, "Invalid pid");
2678     }
2679 
2680     const Error error = m_debugged_process_sp->Detach ();
2681     if (error.Fail ())
2682     {
2683         if (log)
2684             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2685                          __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2686         return SendErrorResponse (0x01);
2687     }
2688 
2689     m_spawned_pids.erase (m_debugged_process_sp->GetID ());
2690     return SendOKResponse ();
2691 }
2692 
2693 GDBRemoteCommunication::PacketResult
2694 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2695 {
2696     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2697 
2698     packet.SetFilePos (strlen("qThreadStopInfo"));
2699     const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2700     if (tid == LLDB_INVALID_THREAD_ID)
2701     {
2702         if (log)
2703             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2704         return SendErrorResponse (0x15);
2705     }
2706     return SendStopReplyPacketForThread (tid);
2707 }
2708 
2709 GDBRemoteCommunication::PacketResult
2710 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2711 {
2712     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2713 
2714     // Ensure we have a debugged process.
2715     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2716         return SendErrorResponse (50);
2717 
2718     if (log)
2719         log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2720                 __FUNCTION__, m_debugged_process_sp->GetID());
2721 
2722     JSONArray threads_array;
2723 
2724     // Ensure we can get info on the given thread.
2725     uint32_t thread_idx = 0;
2726     for ( NativeThreadProtocolSP thread_sp;
2727           (thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_idx)) != nullptr;
2728           ++thread_idx)
2729     {
2730 
2731         JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
2732 
2733         lldb::tid_t tid = thread_sp->GetID();
2734 
2735         // Grab the reason this thread stopped.
2736         struct ThreadStopInfo tid_stop_info;
2737         std::string description;
2738         if (!thread_sp->GetStopReason (tid_stop_info, description))
2739             return SendErrorResponse (52);
2740 
2741         const int signum = tid_stop_info.details.signal.signo;
2742         if (log)
2743         {
2744             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
2745                     __FUNCTION__,
2746                     m_debugged_process_sp->GetID (),
2747                     tid,
2748                     signum,
2749                     tid_stop_info.reason,
2750                     tid_stop_info.details.exception.type);
2751         }
2752 
2753         thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
2754         if (signum != LLDB_INVALID_SIGNAL_NUMBER)
2755             thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(uint64_t(signum)));
2756 
2757         const std::string thread_name = thread_sp->GetName ();
2758         if (! thread_name.empty())
2759             thread_obj_sp->SetObject("name", std::make_shared<JSONString>(thread_name));
2760 
2761         if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
2762             thread_obj_sp->SetObject("registers", registers_sp);
2763 
2764         if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
2765             thread_obj_sp->SetObject("reason", std::make_shared<JSONString>(stop_reason_str));
2766 
2767         if (! description.empty())
2768             thread_obj_sp->SetObject("description", std::make_shared<JSONString>(description));
2769 
2770         if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
2771         {
2772             thread_obj_sp->SetObject("metype",
2773                     std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
2774 
2775             JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
2776             for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
2777             {
2778                 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
2779                             tid_stop_info.details.exception.data[i]));
2780             }
2781             thread_obj_sp->SetObject("medata", medata_array_sp);
2782         }
2783 
2784         threads_array.AppendObject(thread_obj_sp);
2785     }
2786     // TODO: Expedite interesting regions of inferior memory
2787 
2788     StreamString response;
2789     threads_array.Write(response);
2790     StreamGDBRemote escaped_response;
2791     escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2792     return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2793 }
2794 
2795 GDBRemoteCommunication::PacketResult
2796 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2797 {
2798     // Fail if we don't have a current process.
2799     if (!m_debugged_process_sp ||
2800             m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2801         return SendErrorResponse (68);
2802 
2803     packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2804     if (packet.GetBytesLeft() == 0)
2805         return SendOKResponse();
2806     if (packet.GetChar() != ':')
2807         return SendErrorResponse(67);
2808 
2809     uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2810     StreamGDBRemote response;
2811     response.Printf ("num:%d;", num);
2812     return SendPacketNoLock(response.GetData(), response.GetSize());
2813 }
2814 
2815 GDBRemoteCommunication::PacketResult
2816 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2817 {
2818     // Fail if we don't have a current process.
2819     if (!m_debugged_process_sp ||
2820             m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2821         return SendErrorResponse(67);
2822 
2823     packet.SetFilePos(strlen("qFileLoadAddress:"));
2824     if (packet.GetBytesLeft() == 0)
2825         return SendErrorResponse(68);
2826 
2827     std::string file_name;
2828     packet.GetHexByteString(file_name);
2829 
2830     lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2831     Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2832     if (error.Fail())
2833         return SendErrorResponse(69);
2834 
2835     if (file_load_address == LLDB_INVALID_ADDRESS)
2836         return SendErrorResponse(1); // File not loaded
2837 
2838     StreamGDBRemote response;
2839     response.PutHex64(file_load_address);
2840     return SendPacketNoLock(response.GetData(), response.GetSize());
2841 }
2842 
2843 void
2844 GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2845 {
2846     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2847 
2848     Mutex::Locker locker(m_stdio_communication_mutex);
2849     // Tell the stdio connection to shut down.
2850     if (m_stdio_communication.IsConnected())
2851     {
2852         auto connection = m_stdio_communication.GetConnection();
2853         if (connection)
2854         {
2855             Error error;
2856             connection->Disconnect (&error);
2857 
2858             if (error.Success ())
2859             {
2860                 if (log)
2861                     log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2862             }
2863             else
2864             {
2865                 if (log)
2866                     log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2867             }
2868         }
2869     }
2870 }
2871 
2872 
2873 NativeThreadProtocolSP
2874 GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2875 {
2876     NativeThreadProtocolSP thread_sp;
2877 
2878     // We have no thread if we don't have a process.
2879     if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2880         return thread_sp;
2881 
2882     // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2883     // Use the current thread in that case.
2884     if (!m_thread_suffix_supported)
2885     {
2886         const lldb::tid_t current_tid = GetCurrentThreadID ();
2887         if (current_tid == LLDB_INVALID_THREAD_ID)
2888             return thread_sp;
2889         else if (current_tid == 0)
2890         {
2891             // Pick a thread.
2892             return m_debugged_process_sp->GetThreadAtIndex (0);
2893         }
2894         else
2895             return m_debugged_process_sp->GetThreadByID (current_tid);
2896     }
2897 
2898     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2899 
2900     // Parse out the ';'.
2901     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2902     {
2903         if (log)
2904             log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2905         return thread_sp;
2906     }
2907 
2908     if (!packet.GetBytesLeft ())
2909         return thread_sp;
2910 
2911     // Parse out thread: portion.
2912     if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2913     {
2914         if (log)
2915             log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2916         return thread_sp;
2917     }
2918     packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2919     const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2920     if (tid != 0)
2921         return m_debugged_process_sp->GetThreadByID (tid);
2922 
2923     return thread_sp;
2924 }
2925 
2926 lldb::tid_t
2927 GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2928 {
2929     if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2930     {
2931         // Use whatever the debug process says is the current thread id
2932         // since the protocol either didn't specify or specified we want
2933         // any/all threads marked as the current thread.
2934         if (!m_debugged_process_sp)
2935             return LLDB_INVALID_THREAD_ID;
2936         return m_debugged_process_sp->GetCurrentThreadID ();
2937     }
2938     // Use the specific current thread id set by the gdb remote protocol.
2939     return m_current_tid;
2940 }
2941 
2942 uint32_t
2943 GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2944 {
2945     Mutex::Locker locker (m_saved_registers_mutex);
2946     return m_next_saved_registers_id++;
2947 }
2948 
2949 void
2950 GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2951 {
2952     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2953     if (log)
2954         log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2955 
2956     // Clear any auxv cached data.
2957     // *BSD impls should be able to do this too.
2958 #if defined(__linux__)
2959     if (log)
2960         log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2961                      __FUNCTION__,
2962                      m_active_auxv_buffer_sp ? "was set" : "was not set");
2963     m_active_auxv_buffer_sp.reset ();
2964 #endif
2965 }
2966 
2967 FileSpec
2968 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2969                                                  const ArchSpec& arch)
2970 {
2971     if (m_debugged_process_sp)
2972     {
2973         FileSpec file_spec;
2974         if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2975         {
2976             if (file_spec.Exists())
2977                 return file_spec;
2978         }
2979     }
2980 
2981     return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
2982 }
2983