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