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