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