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