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