]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
Vendor import of stripped lldb trunk r256633:
[FreeBSD/FreeBSD.git] / source / Plugins / Process / gdb-remote / GDBRemoteCommunicationServerLLGS.cpp
1 //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include <errno.h>
11
12 #include "lldb/Host/Config.h"
13
14 #include "GDBRemoteCommunicationServerLLGS.h"
15 #include "lldb/Core/StreamGDBRemote.h"
16
17 // C Includes
18 // C++ Includes
19 #include <cstring>
20 #include <chrono>
21 #include <thread>
22
23 // Other libraries and framework includes
24 #include "llvm/ADT/Triple.h"
25 #include "lldb/Interpreter/Args.h"
26 #include "lldb/Core/DataBuffer.h"
27 #include "lldb/Core/Log.h"
28 #include "lldb/Core/RegisterValue.h"
29 #include "lldb/Core/State.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Host/ConnectionFileDescriptor.h"
32 #include "lldb/Host/Debug.h"
33 #include "lldb/Host/Endian.h"
34 #include "lldb/Host/File.h"
35 #include "lldb/Host/FileSystem.h"
36 #include "lldb/Host/Host.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Host/StringConvert.h"
39 #include "lldb/Host/TimeValue.h"
40 #include "lldb/Target/FileAction.h"
41 #include "lldb/Target/MemoryRegionInfo.h"
42 #include "lldb/Target/Platform.h"
43 #include "lldb/Host/common/NativeRegisterContext.h"
44 #include "lldb/Host/common/NativeProcessProtocol.h"
45 #include "lldb/Host/common/NativeThreadProtocol.h"
46 #include "lldb/Utility/JSON.h"
47 #include "lldb/Utility/LLDBAssert.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(
80         const lldb::PlatformSP& platform_sp,
81         MainLoop &mainloop) :
82     GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
83     m_platform_sp (platform_sp),
84     m_mainloop (mainloop),
85     m_current_tid (LLDB_INVALID_THREAD_ID),
86     m_continue_tid (LLDB_INVALID_THREAD_ID),
87     m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
88     m_debugged_process_sp (),
89     m_stdio_communication ("process.stdio"),
90     m_inferior_prev_state (StateType::eStateInvalid),
91     m_active_auxv_buffer_sp (),
92     m_saved_registers_mutex (),
93     m_saved_registers_map (),
94     m_next_saved_registers_id (1),
95     m_handshake_completed (false)
96 {
97     assert(platform_sp);
98     RegisterPacketHandlers();
99 }
100
101 void
102 GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
103 {
104     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
105                                   &GDBRemoteCommunicationServerLLGS::Handle_C);
106     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
107                                   &GDBRemoteCommunicationServerLLGS::Handle_c);
108     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
109                                   &GDBRemoteCommunicationServerLLGS::Handle_D);
110     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
111                                   &GDBRemoteCommunicationServerLLGS::Handle_H);
112     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
113                                   &GDBRemoteCommunicationServerLLGS::Handle_I);
114     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
115                                   &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
116     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
117                                   &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
118     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
119                                   &GDBRemoteCommunicationServerLLGS::Handle_M);
120     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
121                                   &GDBRemoteCommunicationServerLLGS::Handle_p);
122     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
123                                   &GDBRemoteCommunicationServerLLGS::Handle_P);
124     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
125                                   &GDBRemoteCommunicationServerLLGS::Handle_qC);
126     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
127                                   &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
128     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
129                                   &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
130     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
131                                   &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
132     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
133                                   &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
134     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
135                                   &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
136     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
137                                   &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
138     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
139                                   &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
140     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
141                                   &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
142     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
143                                   &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
144     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
145                                   &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
146     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
147                                   &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
148     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
149                                   &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
150     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151                                   &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
153                                   &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
154     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
155                                   &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
156     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
157                                   &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
158     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
159                                   &GDBRemoteCommunicationServerLLGS::Handle_s);
160     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
161                                   &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
162     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
163                                   &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
164     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
165                                   &GDBRemoteCommunicationServerLLGS::Handle_vCont);
166     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
167                                   &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
168     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_x,
169                                   &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
170     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
171                                   &GDBRemoteCommunicationServerLLGS::Handle_Z);
172     RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
173                                   &GDBRemoteCommunicationServerLLGS::Handle_z);
174
175     RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
176                           [this](StringExtractorGDBRemote packet,
177                                  Error &error,
178                                  bool &interrupt,
179                                  bool &quit)
180                           {
181                               quit = true;
182                               return this->Handle_k (packet);
183                           });
184 }
185
186 Error
187 GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
188 {
189     if ((argc < 1) || !args || !args[0] || !args[0][0])
190         return Error ("%s: no process command line specified to launch", __FUNCTION__);
191
192     m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
193     return Error ();
194 }
195
196 Error
197 GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
198 {
199     m_process_launch_info.GetFlags ().Set (launch_flags);
200     return Error ();
201 }
202
203 Error
204 GDBRemoteCommunicationServerLLGS::LaunchProcess ()
205 {
206     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
207
208     if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
209         return Error ("%s: no process command line specified to launch", __FUNCTION__);
210
211     Error error;
212     {
213         Mutex::Locker locker (m_debugged_process_mutex);
214         assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
215         error = NativeProcessProtocol::Launch(
216             m_process_launch_info,
217             *this,
218             m_mainloop,
219             m_debugged_process_sp);
220     }
221
222     if (!error.Success ())
223     {
224         fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
225         return error;
226     }
227
228     // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
229     // as needed.
230     // llgs local-process debugging may specify PTY paths, which will make these
231     // file actions non-null
232     // process launch -i/e/o will also make these file actions non-null
233     // nullptr means that the traffic is expected to flow over gdb-remote protocol
234     if (
235         m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr  ||
236         m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr  ||
237         m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
238         )
239     {
240         // nullptr means it's not redirected to file or pty (in case of LLGS local)
241         // at least one of stdio will be transferred pty<->gdb-remote
242         // we need to give the pty master handle to this object to read and/or write
243         if (log)
244             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
245
246         // Setup stdout/stderr mapping from inferior to $O
247         auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
248         if (terminal_fd >= 0)
249         {
250             if (log)
251                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
252             error = SetSTDIOFileDescriptor (terminal_fd);
253             if (error.Fail ())
254                 return error;
255         }
256         else
257         {
258             if (log)
259                 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
260         }
261     }
262     else
263     {
264         if (log)
265             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 ());
266     }
267
268     printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
269
270     return error;
271 }
272
273 Error
274 GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
275 {
276     Error error;
277
278     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
279     if (log)
280         log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
281
282     // Before we try to attach, make sure we aren't already monitoring something else.
283     if (m_debugged_process_sp  && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
284         return Error("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, m_debugged_process_sp->GetID());
285
286     // Try to attach.
287     error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
288     if (!error.Success ())
289     {
290         fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
291         return error;
292     }
293
294     // Setup stdout/stderr mapping from inferior.
295     auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
296     if (terminal_fd >= 0)
297     {
298         if (log)
299             log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
300         error = SetSTDIOFileDescriptor (terminal_fd);
301         if (error.Fail ())
302             return error;
303     }
304     else
305     {
306         if (log)
307             log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
308     }
309
310     printf ("Attached to process %" PRIu64 "...\n", pid);
311
312     return error;
313 }
314
315 void
316 GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
317 {
318     assert (process && "process cannot be NULL");
319     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
320     if (log)
321     {
322         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
323                 __FUNCTION__,
324                 process->GetID (),
325                 StateAsCString (process->GetState ()));
326     }
327 }
328
329 GDBRemoteCommunication::PacketResult
330 GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
331 {
332     assert (process && "process cannot be NULL");
333     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
334
335     // send W notification
336     ExitType exit_type = ExitType::eExitTypeInvalid;
337     int return_code = 0;
338     std::string exit_description;
339
340     const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
341     if (!got_exit_info)
342     {
343         if (log)
344             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
345
346         StreamGDBRemote response;
347         response.PutChar ('E');
348         response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
349         return SendPacketNoLock(response.GetData(), response.GetSize());
350     }
351     else
352     {
353         if (log)
354             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 ());
355
356         StreamGDBRemote response;
357
358         char return_type_code;
359         switch (exit_type)
360         {
361             case ExitType::eExitTypeExit:
362                 return_type_code = 'W';
363                 break;
364             case ExitType::eExitTypeSignal:
365                 return_type_code = 'X';
366                 break;
367             case ExitType::eExitTypeStop:
368                 return_type_code = 'S';
369                 break;
370             case ExitType::eExitTypeInvalid:
371                 return_type_code = 'E';
372                 break;
373         }
374         response.PutChar (return_type_code);
375
376         // POSIX exit status limited to unsigned 8 bits.
377         response.PutHex8 (return_code);
378
379         return SendPacketNoLock(response.GetData(), response.GetSize());
380     }
381 }
382
383 static void
384 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
385 {
386     int64_t i;
387     if (swap)
388     {
389         for (i = buf_size-1; i >= 0; i--)
390             response.PutHex8 (buf[i]);
391     }
392     else
393     {
394         for (i = 0; i < buf_size; i++)
395             response.PutHex8 (buf[i]);
396     }
397 }
398
399 static void
400 WriteRegisterValueInHexFixedWidth (StreamString &response,
401                                    NativeRegisterContextSP &reg_ctx_sp,
402                                    const RegisterInfo &reg_info,
403                                    const RegisterValue *reg_value_p)
404 {
405     RegisterValue reg_value;
406     if (!reg_value_p)
407     {
408         Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
409         if (error.Success ())
410             reg_value_p = &reg_value;
411         // else log.
412     }
413
414     if (reg_value_p)
415     {
416         AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
417     }
418     else
419     {
420         // Zero-out any unreadable values.
421         if (reg_info.byte_size > 0)
422         {
423             std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
424             AppendHexValue (response, zeros.data(), zeros.size(), false);
425         }
426     }
427 }
428
429 static JSONObject::SP
430 GetRegistersAsJSON(NativeThreadProtocol &thread, bool abridged)
431 {
432     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
433
434     NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
435     if (! reg_ctx_sp)
436         return nullptr;
437
438     JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
439
440 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
441     // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
442     const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
443     if (! reg_set_p)
444         return nullptr;
445     for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
446     {
447         uint32_t reg_num = *reg_num_p;
448 #else
449     // Expedite only a couple of registers until we figure out why sending registers is
450     // expensive.
451     static const uint32_t k_expedited_registers[] = {
452         LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM
453     };
454     static const uint32_t k_abridged_expedited_registers[] = {
455         LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM
456     };
457
458     for (const uint32_t *generic_reg_p = abridged ? k_abridged_expedited_registers : k_expedited_registers;
459          *generic_reg_p != LLDB_INVALID_REGNUM;
460          ++generic_reg_p)
461     {
462         uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, *generic_reg_p);
463         if (reg_num == LLDB_INVALID_REGNUM)
464             continue; // Target does not support the given register.
465 #endif
466
467         const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
468         if (reg_info_p == nullptr)
469         {
470             if (log)
471                 log->Printf("%s failed to get register info for register index %" PRIu32,
472                         __FUNCTION__, reg_num);
473             continue;
474         }
475
476         if (reg_info_p->value_regs != nullptr)
477             continue; // Only expedite registers that are not contained in other registers.
478
479         RegisterValue reg_value;
480         Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
481         if (error.Fail())
482         {
483             if (log)
484                 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
485                         reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
486                         error.AsCString ());
487             continue;
488         }
489
490         StreamString stream;
491         WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, &reg_value);
492
493         register_object_sp->SetObject(std::to_string(reg_num),
494                 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     // llgs local-process debugging may specify PTY paths, which will make these
1007     // file actions non-null
1008     // process launch -e/o will also make these file actions non-null
1009     // nullptr means that the traffic is expected to flow over gdb-remote protocol
1010     if ( m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) &&
1011          m_process_launch_info.GetFileActionForFD(STDERR_FILENO))
1012         return;
1013
1014     Error error;
1015     lldbassert(! m_stdio_handle_up);
1016     m_stdio_handle_up = m_mainloop.RegisterReadObject(
1017             m_stdio_communication.GetConnection()->GetReadObject(),
1018             [this] (MainLoopBase &) { SendProcessOutput(); }, error);
1019
1020     if (! m_stdio_handle_up)
1021     {
1022         // Not much we can do about the failure. Log it and continue without forwarding.
1023         if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1024             log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio forwarding: %s",
1025                         __FUNCTION__, error.AsCString());
1026     }
1027 }
1028
1029 void
1030 GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
1031 {
1032     m_stdio_handle_up.reset();
1033 }
1034
1035 void
1036 GDBRemoteCommunicationServerLLGS::SendProcessOutput()
1037 {
1038     char buffer[1024];
1039     ConnectionStatus status;
1040     Error error;
1041     while (true)
1042     {
1043         size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1044         switch (status)
1045         {
1046         case eConnectionStatusSuccess:
1047             SendONotification(buffer, bytes_read);
1048             break;
1049         case eConnectionStatusLostConnection:
1050         case eConnectionStatusEndOfFile:
1051         case eConnectionStatusError:
1052         case eConnectionStatusNoConnection:
1053             if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1054                 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
1055             m_stdio_handle_up.reset();
1056             return;
1057
1058         case eConnectionStatusInterrupted:
1059         case eConnectionStatusTimedOut:
1060             return;
1061         }
1062     }
1063 }
1064
1065 GDBRemoteCommunication::PacketResult
1066 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1067 {
1068     // Fail if we don't have a current process.
1069     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1070         return SendErrorResponse (68);
1071
1072     lldb::pid_t pid = m_debugged_process_sp->GetID ();
1073
1074     if (pid == LLDB_INVALID_PROCESS_ID)
1075         return SendErrorResponse (1);
1076
1077     ProcessInstanceInfo proc_info;
1078     if (!Host::GetProcessInfo (pid, proc_info))
1079         return SendErrorResponse (1);
1080
1081     StreamString response;
1082     CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1083     return SendPacketNoLock (response.GetData (), response.GetSize ());
1084 }
1085
1086 GDBRemoteCommunication::PacketResult
1087 GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
1088 {
1089     // Fail if we don't have a current process.
1090     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1091         return SendErrorResponse (68);
1092
1093     // Make sure we set the current thread so g and p packets return
1094     // the data the gdb will expect.
1095     lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1096     SetCurrentThreadID (tid);
1097
1098     NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1099     if (!thread_sp)
1100         return SendErrorResponse (69);
1101
1102     StreamString response;
1103     response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1104
1105     return SendPacketNoLock (response.GetData(), response.GetSize());
1106 }
1107
1108 GDBRemoteCommunication::PacketResult
1109 GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1110 {
1111     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1112
1113     StopSTDIOForwarding();
1114
1115     if (! m_debugged_process_sp)
1116     {
1117         if (log)
1118             log->Printf("GDBRemoteCommunicationServerLLGS::%s No debugged process found.", __FUNCTION__);
1119         return PacketResult::Success;
1120     }
1121
1122     Error error = m_debugged_process_sp->Kill();
1123     if (error.Fail() && log)
1124         log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged process %" PRIu64 ": %s",
1125                 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1126
1127     // No OK response for kill packet.
1128     // return SendOKResponse ();
1129     return PacketResult::Success;
1130 }
1131
1132 GDBRemoteCommunication::PacketResult
1133 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1134 {
1135     packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1136     if (packet.GetU32(0))
1137         m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1138     else
1139         m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1140     return SendOKResponse ();
1141 }
1142
1143 GDBRemoteCommunication::PacketResult
1144 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1145 {
1146     packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1147     std::string path;
1148     packet.GetHexByteString (path);
1149     m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1150     return SendOKResponse ();
1151 }
1152
1153 GDBRemoteCommunication::PacketResult
1154 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1155 {
1156     FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1157     if (working_dir)
1158     {
1159         StreamString response;
1160         response.PutCStringAsRawHex8(working_dir.GetCString());
1161         return SendPacketNoLock(response.GetData(), response.GetSize());
1162     }
1163
1164     return SendErrorResponse(14);
1165 }
1166
1167 GDBRemoteCommunication::PacketResult
1168 GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1169 {
1170     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1171     if (log)
1172         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1173
1174     // Ensure we have a native process.
1175     if (!m_debugged_process_sp)
1176     {
1177         if (log)
1178             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1179         return SendErrorResponse (0x36);
1180     }
1181
1182     // Pull out the signal number.
1183     packet.SetFilePos (::strlen ("C"));
1184     if (packet.GetBytesLeft () < 1)
1185     {
1186         // Shouldn't be using a C without a signal.
1187         return SendIllFormedResponse (packet, "C packet specified without signal.");
1188     }
1189     const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1190     if (signo == std::numeric_limits<uint32_t>::max ())
1191         return SendIllFormedResponse (packet, "failed to parse signal number");
1192
1193     // Handle optional continue address.
1194     if (packet.GetBytesLeft () > 0)
1195     {
1196         // FIXME add continue at address support for $C{signo}[;{continue-address}].
1197         if (*packet.Peek () == ';')
1198             return SendUnimplementedResponse (packet.GetStringRef().c_str());
1199         else
1200             return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1201     }
1202
1203     ResumeActionList resume_actions (StateType::eStateRunning, 0);
1204     Error error;
1205
1206     // We have two branches: what to do if a continue thread is specified (in which case we target
1207     // sending the signal to that thread), or when we don't have a continue thread set (in which
1208     // case we send a signal to the process).
1209
1210     // TODO discuss with Greg Clayton, make sure this makes sense.
1211
1212     lldb::tid_t signal_tid = GetContinueThreadID ();
1213     if (signal_tid != LLDB_INVALID_THREAD_ID)
1214     {
1215         // The resume action for the continue thread (or all threads if a continue thread is not set).
1216         ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
1217
1218         // Add the action for the continue thread (or all threads when the continue thread isn't present).
1219         resume_actions.Append (action);
1220     }
1221     else
1222     {
1223         // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1224         error = m_debugged_process_sp->Signal (signo);
1225         if (error.Fail ())
1226         {
1227             if (log)
1228                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1229                              __FUNCTION__,
1230                              m_debugged_process_sp->GetID (),
1231                              error.AsCString ());
1232
1233             return SendErrorResponse (0x52);
1234         }
1235     }
1236
1237     // Resume the threads.
1238     error = m_debugged_process_sp->Resume (resume_actions);
1239     if (error.Fail ())
1240     {
1241         if (log)
1242             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1243                          __FUNCTION__,
1244                          m_debugged_process_sp->GetID (),
1245                          error.AsCString ());
1246
1247         return SendErrorResponse (0x38);
1248     }
1249
1250     // Don't send an "OK" packet; response is the stopped/exited message.
1251     return PacketResult::Success;
1252 }
1253
1254 GDBRemoteCommunication::PacketResult
1255 GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1256 {
1257     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1258     if (log)
1259         log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1260
1261     packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1262
1263     // For now just support all continue.
1264     const bool has_continue_address = (packet.GetBytesLeft () > 0);
1265     if (has_continue_address)
1266     {
1267         if (log)
1268             log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1269         return SendUnimplementedResponse (packet.GetStringRef().c_str());
1270     }
1271
1272     // Ensure we have a native process.
1273     if (!m_debugged_process_sp)
1274     {
1275         if (log)
1276             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1277         return SendErrorResponse (0x36);
1278     }
1279
1280     // Build the ResumeActionList
1281     ResumeActionList actions (StateType::eStateRunning, 0);
1282
1283     Error error = m_debugged_process_sp->Resume (actions);
1284     if (error.Fail ())
1285     {
1286         if (log)
1287         {
1288             log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1289                          __FUNCTION__,
1290                          m_debugged_process_sp->GetID (),
1291                          error.AsCString ());
1292         }
1293         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1294     }
1295
1296     if (log)
1297         log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1298
1299     // No response required from continue.
1300     return PacketResult::Success;
1301 }
1302
1303 GDBRemoteCommunication::PacketResult
1304 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1305 {
1306     StreamString response;
1307     response.Printf("vCont;c;C;s;S");
1308
1309     return SendPacketNoLock(response.GetData(), response.GetSize());
1310 }
1311
1312 GDBRemoteCommunication::PacketResult
1313 GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1314 {
1315     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1316     if (log)
1317         log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1318
1319     packet.SetFilePos (::strlen ("vCont"));
1320
1321     if (packet.GetBytesLeft() == 0)
1322     {
1323         if (log)
1324             log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1325         return SendIllFormedResponse (packet, "Missing action from vCont package");
1326     }
1327
1328     // Check if this is all continue (no options or ";c").
1329     if (::strcmp (packet.Peek (), ";c") == 0)
1330     {
1331         // Move past the ';', then do a simple 'c'.
1332         packet.SetFilePos (packet.GetFilePos () + 1);
1333         return Handle_c (packet);
1334     }
1335     else if (::strcmp (packet.Peek (), ";s") == 0)
1336     {
1337         // Move past the ';', then do a simple 's'.
1338         packet.SetFilePos (packet.GetFilePos () + 1);
1339         return Handle_s (packet);
1340     }
1341
1342     // Ensure we have a native process.
1343     if (!m_debugged_process_sp)
1344     {
1345         if (log)
1346             log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1347         return SendErrorResponse (0x36);
1348     }
1349
1350     ResumeActionList thread_actions;
1351
1352     while (packet.GetBytesLeft () && *packet.Peek () == ';')
1353     {
1354         // Skip the semi-colon.
1355         packet.GetChar ();
1356
1357         // Build up the thread action.
1358         ResumeAction thread_action;
1359         thread_action.tid = LLDB_INVALID_THREAD_ID;
1360         thread_action.state = eStateInvalid;
1361         thread_action.signal = 0;
1362
1363         const char action = packet.GetChar ();
1364         switch (action)
1365         {
1366             case 'C':
1367                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1368                 if (thread_action.signal == 0)
1369                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1370                 // Fall through to next case...
1371
1372             case 'c':
1373                 // Continue
1374                 thread_action.state = eStateRunning;
1375                 break;
1376
1377             case 'S':
1378                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1379                 if (thread_action.signal == 0)
1380                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1381                 // Fall through to next case...
1382
1383             case 's':
1384                 // Step
1385                 thread_action.state = eStateStepping;
1386                 break;
1387
1388             default:
1389                 return SendIllFormedResponse (packet, "Unsupported vCont action");
1390                 break;
1391         }
1392
1393         // Parse out optional :{thread-id} value.
1394         if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1395         {
1396             // Consume the separator.
1397             packet.GetChar ();
1398
1399             thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1400             if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1401                 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1402         }
1403
1404         thread_actions.Append (thread_action);
1405     }
1406
1407     Error error = m_debugged_process_sp->Resume (thread_actions);
1408     if (error.Fail ())
1409     {
1410         if (log)
1411         {
1412             log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1413                          __FUNCTION__,
1414                          m_debugged_process_sp->GetID (),
1415                          error.AsCString ());
1416         }
1417         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1418     }
1419
1420     if (log)
1421         log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1422
1423     // No response required from vCont.
1424     return PacketResult::Success;
1425 }
1426
1427 void
1428 GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1429 {
1430     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1431     if (log)
1432         log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1433
1434     m_current_tid = tid;
1435     if (m_debugged_process_sp)
1436         m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1437 }
1438
1439 void
1440 GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1441 {
1442     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1443     if (log)
1444         log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1445
1446     m_continue_tid = tid;
1447 }
1448
1449 GDBRemoteCommunication::PacketResult
1450 GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1451 {
1452     // Handle the $? gdbremote command.
1453
1454     // If no process, indicate error
1455     if (!m_debugged_process_sp)
1456         return SendErrorResponse (02);
1457
1458     return SendStopReasonForState (m_debugged_process_sp->GetState());
1459 }
1460
1461 GDBRemoteCommunication::PacketResult
1462 GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
1463 {
1464     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1465
1466     switch (process_state)
1467     {
1468         case eStateAttaching:
1469         case eStateLaunching:
1470         case eStateRunning:
1471         case eStateStepping:
1472         case eStateDetached:
1473             // NOTE: gdb protocol doc looks like it should return $OK
1474             // when everything is running (i.e. no stopped result).
1475             return PacketResult::Success;  // Ignore
1476
1477         case eStateSuspended:
1478         case eStateStopped:
1479         case eStateCrashed:
1480         {
1481             lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1482             // Make sure we set the current thread so g and p packets return
1483             // the data the gdb will expect.
1484             SetCurrentThreadID (tid);
1485             return SendStopReplyPacketForThread (tid);
1486         }
1487
1488         case eStateInvalid:
1489         case eStateUnloaded:
1490         case eStateExited:
1491             return SendWResponse(m_debugged_process_sp.get());
1492
1493         default:
1494             if (log)
1495             {
1496                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1497                              __FUNCTION__,
1498                              m_debugged_process_sp->GetID (),
1499                              StateAsCString (process_state));
1500             }
1501             break;
1502     }
1503     
1504     return SendErrorResponse (0);
1505 }
1506
1507 GDBRemoteCommunication::PacketResult
1508 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1509 {
1510     // Fail if we don't have a current process.
1511     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1512         return SendErrorResponse (68);
1513
1514     // Ensure we have a thread.
1515     NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1516     if (!thread_sp)
1517         return SendErrorResponse (69);
1518
1519     // Get the register context for the first thread.
1520     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1521     if (!reg_context_sp)
1522         return SendErrorResponse (69);
1523
1524     // Parse out the register number from the request.
1525     packet.SetFilePos (strlen("qRegisterInfo"));
1526     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1527     if (reg_index == std::numeric_limits<uint32_t>::max ())
1528         return SendErrorResponse (69);
1529
1530     // Return the end of registers response if we've iterated one past the end of the register set.
1531     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1532         return SendErrorResponse (69);
1533
1534     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1535     if (!reg_info)
1536         return SendErrorResponse (69);
1537
1538     // Build the reginfos response.
1539     StreamGDBRemote response;
1540
1541     response.PutCString ("name:");
1542     response.PutCString (reg_info->name);
1543     response.PutChar (';');
1544
1545     if (reg_info->alt_name && reg_info->alt_name[0])
1546     {
1547         response.PutCString ("alt-name:");
1548         response.PutCString (reg_info->alt_name);
1549         response.PutChar (';');
1550     }
1551
1552     response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1553
1554     switch (reg_info->encoding)
1555     {
1556         case eEncodingUint:    response.PutCString ("encoding:uint;"); break;
1557         case eEncodingSint:    response.PutCString ("encoding:sint;"); break;
1558         case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1559         case eEncodingVector:  response.PutCString ("encoding:vector;"); break;
1560         default: break;
1561     }
1562
1563     switch (reg_info->format)
1564     {
1565         case eFormatBinary:          response.PutCString ("format:binary;"); break;
1566         case eFormatDecimal:         response.PutCString ("format:decimal;"); break;
1567         case eFormatHex:             response.PutCString ("format:hex;"); break;
1568         case eFormatFloat:           response.PutCString ("format:float;"); break;
1569         case eFormatVectorOfSInt8:   response.PutCString ("format:vector-sint8;"); break;
1570         case eFormatVectorOfUInt8:   response.PutCString ("format:vector-uint8;"); break;
1571         case eFormatVectorOfSInt16:  response.PutCString ("format:vector-sint16;"); break;
1572         case eFormatVectorOfUInt16:  response.PutCString ("format:vector-uint16;"); break;
1573         case eFormatVectorOfSInt32:  response.PutCString ("format:vector-sint32;"); break;
1574         case eFormatVectorOfUInt32:  response.PutCString ("format:vector-uint32;"); break;
1575         case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1576         case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1577         default: break;
1578     };
1579
1580     const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1581     if (register_set_name)
1582     {
1583         response.PutCString ("set:");
1584         response.PutCString (register_set_name);
1585         response.PutChar (';');
1586     }
1587
1588     if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
1589         response.Printf ("ehframe:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1590
1591     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1592         response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1593
1594     switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1595     {
1596         case LLDB_REGNUM_GENERIC_PC:     response.PutCString("generic:pc;"); break;
1597         case LLDB_REGNUM_GENERIC_SP:     response.PutCString("generic:sp;"); break;
1598         case LLDB_REGNUM_GENERIC_FP:     response.PutCString("generic:fp;"); break;
1599         case LLDB_REGNUM_GENERIC_RA:     response.PutCString("generic:ra;"); break;
1600         case LLDB_REGNUM_GENERIC_FLAGS:  response.PutCString("generic:flags;"); break;
1601         case LLDB_REGNUM_GENERIC_ARG1:   response.PutCString("generic:arg1;"); break;
1602         case LLDB_REGNUM_GENERIC_ARG2:   response.PutCString("generic:arg2;"); break;
1603         case LLDB_REGNUM_GENERIC_ARG3:   response.PutCString("generic:arg3;"); break;
1604         case LLDB_REGNUM_GENERIC_ARG4:   response.PutCString("generic:arg4;"); break;
1605         case LLDB_REGNUM_GENERIC_ARG5:   response.PutCString("generic:arg5;"); break;
1606         case LLDB_REGNUM_GENERIC_ARG6:   response.PutCString("generic:arg6;"); break;
1607         case LLDB_REGNUM_GENERIC_ARG7:   response.PutCString("generic:arg7;"); break;
1608         case LLDB_REGNUM_GENERIC_ARG8:   response.PutCString("generic:arg8;"); break;
1609         default: break;
1610     }
1611
1612     if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1613     {
1614         response.PutCString ("container-regs:");
1615         int i = 0;
1616         for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1617         {
1618             if (i > 0)
1619                 response.PutChar (',');
1620             response.Printf ("%" PRIx32, *reg_num);
1621         }
1622         response.PutChar (';');
1623     }
1624
1625     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1626     {
1627         response.PutCString ("invalidate-regs:");
1628         int i = 0;
1629         for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1630         {
1631             if (i > 0)
1632                 response.PutChar (',');
1633             response.Printf ("%" PRIx32, *reg_num);
1634         }
1635         response.PutChar (';');
1636     }
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     if (reg_size != reg_info->byte_size)
1834     {
1835         return SendIllFormedResponse (packet, "P packet register size is incorrect");
1836     }
1837
1838     // Build the reginfos response.
1839     StreamGDBRemote response;
1840
1841     RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1842     Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1843     if (error.Fail ())
1844     {
1845         if (log)
1846             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1847         return SendErrorResponse (0x32);
1848     }
1849
1850     return SendOKResponse();
1851 }
1852
1853 GDBRemoteCommunication::PacketResult
1854 GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1855 {
1856     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1857
1858     // Fail if we don't have a current process.
1859     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1860     {
1861         if (log)
1862             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1863         return SendErrorResponse (0x15);
1864     }
1865
1866     // Parse out which variant of $H is requested.
1867     packet.SetFilePos (strlen("H"));
1868     if (packet.GetBytesLeft () < 1)
1869     {
1870         if (log)
1871             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1872         return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1873     }
1874
1875     const char h_variant = packet.GetChar ();
1876     switch (h_variant)
1877     {
1878         case 'g':
1879             break;
1880
1881         case 'c':
1882             break;
1883
1884         default:
1885             if (log)
1886                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1887             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1888     }
1889
1890     // Parse out the thread number.
1891     // FIXME return a parse success/fail value.  All values are valid here.
1892     const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1893
1894     // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1895     if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1896     {
1897         NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1898         if (!thread_sp)
1899         {
1900             if (log)
1901                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1902             return SendErrorResponse (0x15);
1903         }
1904     }
1905
1906     // Now switch the given thread type.
1907     switch (h_variant)
1908     {
1909         case 'g':
1910             SetCurrentThreadID (tid);
1911             break;
1912
1913         case 'c':
1914             SetContinueThreadID (tid);
1915             break;
1916
1917         default:
1918             assert (false && "unsupported $H variant - shouldn't get here");
1919             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1920     }
1921
1922     return SendOKResponse();
1923 }
1924
1925 GDBRemoteCommunication::PacketResult
1926 GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1927 {
1928     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1929
1930     // Fail if we don't have a current process.
1931     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1932     {
1933         if (log)
1934             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1935         return SendErrorResponse (0x15);
1936     }
1937
1938     packet.SetFilePos (::strlen("I"));
1939     char tmp[4096];
1940     for (;;)
1941     {
1942         size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1943         if (read == 0)
1944         {
1945             break;
1946         }
1947         // write directly to stdin *this might block if stdin buffer is full*
1948         // TODO: enqueue this block in circular buffer and send window size to remote host
1949         ConnectionStatus status;
1950         Error error;
1951         m_stdio_communication.Write(tmp, read, status, &error);
1952         if (error.Fail())
1953         {
1954             return SendErrorResponse (0x15);
1955         }
1956     }
1957
1958     return SendOKResponse();
1959 }
1960
1961 GDBRemoteCommunication::PacketResult
1962 GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1963 {
1964     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1965
1966     // Fail if we don't have a current process.
1967     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1968     {
1969         if (log)
1970             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1971         return SendErrorResponse (0x15);
1972     }
1973
1974     // Interrupt the process.
1975     Error error = m_debugged_process_sp->Interrupt ();
1976     if (error.Fail ())
1977     {
1978         if (log)
1979         {
1980             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1981                          __FUNCTION__,
1982                          m_debugged_process_sp->GetID (),
1983                          error.AsCString ());
1984         }
1985         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1986     }
1987
1988     if (log)
1989         log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1990
1991     // No response required from stop all.
1992     return PacketResult::Success;
1993 }
1994
1995 GDBRemoteCommunication::PacketResult
1996 GDBRemoteCommunicationServerLLGS::Handle_memory_read(StringExtractorGDBRemote &packet)
1997 {
1998     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1999
2000     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2001     {
2002         if (log)
2003             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2004         return SendErrorResponse (0x15);
2005     }
2006
2007     // Parse out the memory address.
2008     packet.SetFilePos (strlen("m"));
2009     if (packet.GetBytesLeft() < 1)
2010         return SendIllFormedResponse(packet, "Too short m packet");
2011
2012     // Read the address.  Punting on validation.
2013     // FIXME replace with Hex U64 read with no default value that fails on failed read.
2014     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2015
2016     // Validate comma.
2017     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2018         return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2019
2020     // Get # bytes to read.
2021     if (packet.GetBytesLeft() < 1)
2022         return SendIllFormedResponse(packet, "Length missing in m packet");
2023
2024     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2025     if (byte_count == 0)
2026     {
2027         if (log)
2028             log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
2029         return SendOKResponse();
2030     }
2031
2032     // Allocate the response buffer.
2033     std::string buf(byte_count, '\0');
2034     if (buf.empty())
2035         return SendErrorResponse (0x78);
2036
2037
2038     // Retrieve the process memory.
2039     size_t bytes_read = 0;
2040     Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
2041     if (error.Fail ())
2042     {
2043         if (log)
2044             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2045         return SendErrorResponse (0x08);
2046     }
2047
2048     if (bytes_read == 0)
2049     {
2050         if (log)
2051             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);
2052         return SendErrorResponse (0x08);
2053     }
2054
2055     StreamGDBRemote response;
2056     packet.SetFilePos(0);
2057     char kind = packet.GetChar('?');
2058     if (kind == 'x')
2059         response.PutEscapedBytes(buf.data(), byte_count);
2060     else
2061     {
2062         assert(kind == 'm');
2063         for (size_t i = 0; i < bytes_read; ++i)
2064             response.PutHex8(buf[i]);
2065     }
2066
2067     return SendPacketNoLock(response.GetData(), response.GetSize());
2068 }
2069
2070 GDBRemoteCommunication::PacketResult
2071 GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2072 {
2073     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2074
2075     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2076     {
2077         if (log)
2078             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2079         return SendErrorResponse (0x15);
2080     }
2081
2082     // Parse out the memory address.
2083     packet.SetFilePos (strlen("M"));
2084     if (packet.GetBytesLeft() < 1)
2085         return SendIllFormedResponse(packet, "Too short M packet");
2086
2087     // Read the address.  Punting on validation.
2088     // FIXME replace with Hex U64 read with no default value that fails on failed read.
2089     const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2090
2091     // Validate comma.
2092     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2093         return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2094
2095     // Get # bytes to read.
2096     if (packet.GetBytesLeft() < 1)
2097         return SendIllFormedResponse(packet, "Length missing in M packet");
2098
2099     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2100     if (byte_count == 0)
2101     {
2102         if (log)
2103             log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2104         return PacketResult::Success;
2105     }
2106
2107     // Validate colon.
2108     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2109         return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2110
2111     // Allocate the conversion buffer.
2112     std::vector<uint8_t> buf(byte_count, 0);
2113     if (buf.empty())
2114         return SendErrorResponse (0x78);
2115
2116     // Convert the hex memory write contents to bytes.
2117     StreamGDBRemote response;
2118     const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
2119     if (convert_count != byte_count)
2120     {
2121         if (log)
2122             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);
2123         return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2124     }
2125
2126     // Write the process memory.
2127     size_t bytes_written = 0;
2128     Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
2129     if (error.Fail ())
2130     {
2131         if (log)
2132             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2133         return SendErrorResponse (0x09);
2134     }
2135
2136     if (bytes_written == 0)
2137     {
2138         if (log)
2139             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);
2140         return SendErrorResponse (0x09);
2141     }
2142
2143     return SendOKResponse ();
2144 }
2145
2146 GDBRemoteCommunication::PacketResult
2147 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2148 {
2149     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2150
2151     // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2152     // request, but we're not guaranteed to be attached to a process.  For now we'll assume the
2153     // client only asks this when a process is being debugged.
2154
2155     // Ensure we have a process running; otherwise, we can't figure this out
2156     // since we won't have a NativeProcessProtocol.
2157     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2158     {
2159         if (log)
2160             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2161         return SendErrorResponse (0x15);
2162     }
2163
2164     // Test if we can get any region back when asking for the region around NULL.
2165     MemoryRegionInfo region_info;
2166     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2167     if (error.Fail ())
2168     {
2169         // We don't support memory region info collection for this NativeProcessProtocol.
2170         return SendUnimplementedResponse ("");
2171     }
2172
2173     return SendOKResponse();
2174 }
2175
2176 GDBRemoteCommunication::PacketResult
2177 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2178 {
2179     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2180
2181     // Ensure we have a process.
2182     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2183     {
2184         if (log)
2185             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2186         return SendErrorResponse (0x15);
2187     }
2188
2189     // Parse out the memory address.
2190     packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2191     if (packet.GetBytesLeft() < 1)
2192         return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2193
2194     // Read the address.  Punting on validation.
2195     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2196
2197     StreamGDBRemote response;
2198
2199     // Get the memory region info for the target address.
2200     MemoryRegionInfo region_info;
2201     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2202     if (error.Fail ())
2203     {
2204         // Return the error message.
2205
2206         response.PutCString ("error:");
2207         response.PutCStringAsRawHex8 (error.AsCString ());
2208         response.PutChar (';');
2209     }
2210     else
2211     {
2212         // Range start and size.
2213         response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2214
2215         // Permissions.
2216         if (region_info.GetReadable () ||
2217             region_info.GetWritable () ||
2218             region_info.GetExecutable ())
2219         {
2220             // Write permissions info.
2221             response.PutCString ("permissions:");
2222
2223             if (region_info.GetReadable ())
2224                 response.PutChar ('r');
2225             if (region_info.GetWritable ())
2226                 response.PutChar('w');
2227             if (region_info.GetExecutable())
2228                 response.PutChar ('x');
2229
2230             response.PutChar (';');
2231         }
2232     }
2233
2234     return SendPacketNoLock(response.GetData(), response.GetSize());
2235 }
2236
2237 GDBRemoteCommunication::PacketResult
2238 GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2239 {
2240     // Ensure we have a process.
2241     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2242     {
2243         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2244         if (log)
2245             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2246         return SendErrorResponse (0x15);
2247     }
2248
2249     // Parse out software or hardware breakpoint or watchpoint requested.
2250     packet.SetFilePos (strlen("Z"));
2251     if (packet.GetBytesLeft() < 1)
2252         return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2253
2254     bool want_breakpoint = true;
2255     bool want_hardware = false;
2256     uint32_t watch_flags = 0;
2257
2258     const GDBStoppointType stoppoint_type =
2259         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2260     switch (stoppoint_type)
2261     {
2262         case eBreakpointSoftware:
2263             want_hardware = false; want_breakpoint = true;  break;
2264         case eBreakpointHardware:
2265             want_hardware = true;  want_breakpoint = true;  break;
2266         case eWatchpointWrite:
2267             watch_flags = 1;
2268             want_hardware = true;  want_breakpoint = false; break;
2269         case eWatchpointRead:
2270             watch_flags = 2;
2271             want_hardware = true;  want_breakpoint = false; break;
2272         case eWatchpointReadWrite:
2273             watch_flags = 3;
2274             want_hardware = true;  want_breakpoint = false; break;
2275         case eStoppointInvalid:
2276             return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2277
2278     }
2279
2280     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2281         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2282
2283     // Parse out the stoppoint address.
2284     if (packet.GetBytesLeft() < 1)
2285         return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2286     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2287
2288     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2289         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2290
2291     // Parse out the stoppoint size (i.e. size hint for opcode size).
2292     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2293     if (size == std::numeric_limits<uint32_t>::max ())
2294         return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2295
2296     if (want_breakpoint)
2297     {
2298         // Try to set the breakpoint.
2299         const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2300         if (error.Success ())
2301             return SendOKResponse ();
2302         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2303         if (log)
2304             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2305                     " failed to set breakpoint: %s",
2306                     __FUNCTION__,
2307                     m_debugged_process_sp->GetID (),
2308                     error.AsCString ());
2309         return SendErrorResponse (0x09);
2310     }
2311     else
2312     {
2313         // Try to set the watchpoint.
2314         const Error error = m_debugged_process_sp->SetWatchpoint (
2315                 addr, size, watch_flags, want_hardware);
2316         if (error.Success ())
2317             return SendOKResponse ();
2318         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2319         if (log)
2320             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2321                     " failed to set watchpoint: %s",
2322                     __FUNCTION__,
2323                     m_debugged_process_sp->GetID (),
2324                     error.AsCString ());
2325         return SendErrorResponse (0x09);
2326     }
2327 }
2328
2329 GDBRemoteCommunication::PacketResult
2330 GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2331 {
2332     // Ensure we have a process.
2333     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2334     {
2335         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2336         if (log)
2337             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2338         return SendErrorResponse (0x15);
2339     }
2340
2341     // Parse out software or hardware breakpoint or watchpoint requested.
2342     packet.SetFilePos (strlen("z"));
2343     if (packet.GetBytesLeft() < 1)
2344         return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2345
2346     bool want_breakpoint = true;
2347
2348     const GDBStoppointType stoppoint_type =
2349         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2350     switch (stoppoint_type)
2351     {
2352         case eBreakpointHardware:  want_breakpoint = true;  break;
2353         case eBreakpointSoftware:  want_breakpoint = true;  break;
2354         case eWatchpointWrite:     want_breakpoint = false; break;
2355         case eWatchpointRead:      want_breakpoint = false; break;
2356         case eWatchpointReadWrite: want_breakpoint = false; break;
2357         default:
2358             return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2359
2360     }
2361
2362     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2363         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2364
2365     // Parse out the stoppoint address.
2366     if (packet.GetBytesLeft() < 1)
2367         return SendIllFormedResponse(packet, "Too short z packet, missing address");
2368     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2369
2370     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2371         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2372
2373     /*
2374     // Parse out the stoppoint size (i.e. size hint for opcode size).
2375     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2376     if (size == std::numeric_limits<uint32_t>::max ())
2377         return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2378     */
2379
2380     if (want_breakpoint)
2381     {
2382         // Try to clear the breakpoint.
2383         const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2384         if (error.Success ())
2385             return SendOKResponse ();
2386         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2387         if (log)
2388             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2389                     " failed to remove breakpoint: %s",
2390                     __FUNCTION__,
2391                     m_debugged_process_sp->GetID (),
2392                     error.AsCString ());
2393         return SendErrorResponse (0x09);
2394     }
2395     else
2396     {
2397         // Try to clear the watchpoint.
2398         const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2399         if (error.Success ())
2400             return SendOKResponse ();
2401         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2402         if (log)
2403             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2404                     " failed to remove watchpoint: %s",
2405                     __FUNCTION__,
2406                     m_debugged_process_sp->GetID (),
2407                     error.AsCString ());
2408         return SendErrorResponse (0x09);
2409     }
2410 }
2411
2412 GDBRemoteCommunication::PacketResult
2413 GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2414 {
2415     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2416
2417     // Ensure we have a process.
2418     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2419     {
2420         if (log)
2421             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2422         return SendErrorResponse (0x32);
2423     }
2424
2425     // We first try to use a continue thread id.  If any one or any all set, use the current thread.
2426     // Bail out if we don't have a thread id.
2427     lldb::tid_t tid = GetContinueThreadID ();
2428     if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2429         tid = GetCurrentThreadID ();
2430     if (tid == LLDB_INVALID_THREAD_ID)
2431         return SendErrorResponse (0x33);
2432
2433     // Double check that we have such a thread.
2434     // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2435     NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2436     if (!thread_sp || thread_sp->GetID () != tid)
2437         return SendErrorResponse (0x33);
2438
2439     // Create the step action for the given thread.
2440     ResumeAction action = { tid, eStateStepping, 0 };
2441
2442     // Setup the actions list.
2443     ResumeActionList actions;
2444     actions.Append (action);
2445
2446     // All other threads stop while we're single stepping a thread.
2447     actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2448     Error error = m_debugged_process_sp->Resume (actions);
2449     if (error.Fail ())
2450     {
2451         if (log)
2452             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2453         return SendErrorResponse(0x49);
2454     }
2455
2456     // No response here - the stop or exit will come from the resulting action.
2457     return PacketResult::Success;
2458 }
2459
2460 GDBRemoteCommunication::PacketResult
2461 GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2462 {
2463     // *BSD impls should be able to do this too.
2464 #if defined(__linux__)
2465     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2466
2467     // Parse out the offset.
2468     packet.SetFilePos (strlen("qXfer:auxv:read::"));
2469     if (packet.GetBytesLeft () < 1)
2470         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2471
2472     const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2473     if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2474         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2475
2476     // Parse out comma.
2477     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2478         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2479
2480     // Parse out the length.
2481     const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2482     if (auxv_length == std::numeric_limits<uint64_t>::max ())
2483         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2484
2485     // Grab the auxv data if we need it.
2486     if (!m_active_auxv_buffer_sp)
2487     {
2488         // Make sure we have a valid process.
2489         if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2490         {
2491             if (log)
2492                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2493             return SendErrorResponse (0x10);
2494         }
2495
2496         // Grab the auxv data.
2497         m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2498         if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () ==  0)
2499         {
2500             // Hmm, no auxv data, call that an error.
2501             if (log)
2502                 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2503             m_active_auxv_buffer_sp.reset ();
2504             return SendErrorResponse (0x11);
2505         }
2506     }
2507
2508     // FIXME find out if/how I lock the stream here.
2509
2510     StreamGDBRemote response;
2511     bool done_with_buffer = false;
2512
2513     if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2514     {
2515         // We have nothing left to send.  Mark the buffer as complete.
2516         response.PutChar ('l');
2517         done_with_buffer = true;
2518     }
2519     else
2520     {
2521         // Figure out how many bytes are available starting at the given offset.
2522         const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2523
2524         // Figure out how many bytes we're going to read.
2525         const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2526
2527         // Mark the response type according to whether we're reading the remainder of the auxv data.
2528         if (bytes_to_read >= bytes_remaining)
2529         {
2530             // There will be nothing left to read after this
2531             response.PutChar ('l');
2532             done_with_buffer = true;
2533         }
2534         else
2535         {
2536             // There will still be bytes to read after this request.
2537             response.PutChar ('m');
2538         }
2539
2540         // Now write the data in encoded binary form.
2541         response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2542     }
2543
2544     if (done_with_buffer)
2545         m_active_auxv_buffer_sp.reset ();
2546
2547     return SendPacketNoLock(response.GetData(), response.GetSize());
2548 #else
2549     return SendUnimplementedResponse ("not implemented on this platform");
2550 #endif
2551 }
2552
2553 GDBRemoteCommunication::PacketResult
2554 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2555 {
2556     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2557
2558     // Move past packet name.
2559     packet.SetFilePos (strlen ("QSaveRegisterState"));
2560
2561     // Get the thread to use.
2562     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2563     if (!thread_sp)
2564     {
2565         if (m_thread_suffix_supported)
2566             return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2567         else
2568             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2569     }
2570
2571     // Grab the register context for the thread.
2572     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2573     if (!reg_context_sp)
2574     {
2575         if (log)
2576             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 ());
2577         return SendErrorResponse (0x15);
2578     }
2579
2580     // Save registers to a buffer.
2581     DataBufferSP register_data_sp;
2582     Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2583     if (error.Fail ())
2584     {
2585         if (log)
2586             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2587         return SendErrorResponse (0x75);
2588     }
2589
2590     // Allocate a new save id.
2591     const uint32_t save_id = GetNextSavedRegistersID ();
2592     assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2593
2594     // Save the register data buffer under the save id.
2595     {
2596         Mutex::Locker locker (m_saved_registers_mutex);
2597         m_saved_registers_map[save_id] = register_data_sp;
2598     }
2599
2600     // Write the response.
2601     StreamGDBRemote response;
2602     response.Printf ("%" PRIu32, save_id);
2603     return SendPacketNoLock(response.GetData(), response.GetSize());
2604 }
2605
2606 GDBRemoteCommunication::PacketResult
2607 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2608 {
2609     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2610
2611     // Parse out save id.
2612     packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2613     if (packet.GetBytesLeft () < 1)
2614         return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2615
2616     const uint32_t save_id = packet.GetU32 (0);
2617     if (save_id == 0)
2618     {
2619         if (log)
2620             log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2621         return SendErrorResponse (0x76);
2622     }
2623
2624     // Get the thread to use.
2625     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2626     if (!thread_sp)
2627     {
2628         if (m_thread_suffix_supported)
2629             return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2630         else
2631             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2632     }
2633
2634     // Grab the register context for the thread.
2635     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2636     if (!reg_context_sp)
2637     {
2638         if (log)
2639             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 ());
2640         return SendErrorResponse (0x15);
2641     }
2642
2643     // Retrieve register state buffer, then remove from the list.
2644     DataBufferSP register_data_sp;
2645     {
2646         Mutex::Locker locker (m_saved_registers_mutex);
2647
2648         // Find the register set buffer for the given save id.
2649         auto it = m_saved_registers_map.find (save_id);
2650         if (it == m_saved_registers_map.end ())
2651         {
2652             if (log)
2653                 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);
2654             return SendErrorResponse (0x77);
2655         }
2656         register_data_sp = it->second;
2657
2658         // Remove it from the map.
2659         m_saved_registers_map.erase (it);
2660     }
2661
2662     Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2663     if (error.Fail ())
2664     {
2665         if (log)
2666             log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2667         return SendErrorResponse (0x77);
2668     }
2669
2670     return SendOKResponse();
2671 }
2672
2673 GDBRemoteCommunication::PacketResult
2674 GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2675 {
2676     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2677
2678     // Consume the ';' after vAttach.
2679     packet.SetFilePos (strlen ("vAttach"));
2680     if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2681         return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2682
2683     // Grab the PID to which we will attach (assume hex encoding).
2684     lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2685     if (pid == LLDB_INVALID_PROCESS_ID)
2686         return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2687
2688     // Attempt to attach.
2689     if (log)
2690         log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2691
2692     Error error = AttachToProcess (pid);
2693
2694     if (error.Fail ())
2695     {
2696         if (log)
2697             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2698         return SendErrorResponse (0x01);
2699     }
2700
2701     // Notify we attached by sending a stop packet.
2702     return SendStopReasonForState (m_debugged_process_sp->GetState ());
2703 }
2704
2705 GDBRemoteCommunication::PacketResult
2706 GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2707 {
2708     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2709
2710     StopSTDIOForwarding();
2711
2712     // Fail if we don't have a current process.
2713     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2714     {
2715         if (log)
2716             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2717         return SendErrorResponse (0x15);
2718     }
2719
2720     lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2721
2722     // Consume the ';' after D.
2723     packet.SetFilePos (1);
2724     if (packet.GetBytesLeft ())
2725     {
2726         if (packet.GetChar () != ';')
2727             return SendIllFormedResponse (packet, "D missing expected ';'");
2728
2729         // Grab the PID from which we will detach (assume hex encoding).
2730         pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2731         if (pid == LLDB_INVALID_PROCESS_ID)
2732             return SendIllFormedResponse (packet, "D failed to parse the process id");
2733     }
2734
2735     if (pid != LLDB_INVALID_PROCESS_ID &&
2736         m_debugged_process_sp->GetID () != pid)
2737     {
2738         return SendIllFormedResponse (packet, "Invalid pid");
2739     }
2740
2741     const Error error = m_debugged_process_sp->Detach ();
2742     if (error.Fail ())
2743     {
2744         if (log)
2745             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2746                          __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2747         return SendErrorResponse (0x01);
2748     }
2749
2750     return SendOKResponse ();
2751 }
2752
2753 GDBRemoteCommunication::PacketResult
2754 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2755 {
2756     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2757
2758     packet.SetFilePos (strlen("qThreadStopInfo"));
2759     const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2760     if (tid == LLDB_INVALID_THREAD_ID)
2761     {
2762         if (log)
2763             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2764         return SendErrorResponse (0x15);
2765     }
2766     return SendStopReplyPacketForThread (tid);
2767 }
2768
2769 GDBRemoteCommunication::PacketResult
2770 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2771 {
2772     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2773
2774     // Ensure we have a debugged process.
2775     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2776         return SendErrorResponse (50);
2777
2778     if (log)
2779         log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2780                 __FUNCTION__, m_debugged_process_sp->GetID());
2781
2782
2783     StreamString response;
2784     const bool threads_with_valid_stop_info_only = false;
2785     JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2786                                                         threads_with_valid_stop_info_only);
2787     if (! threads_array_sp)
2788     {
2789         if (log)
2790             log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2791                     __FUNCTION__, m_debugged_process_sp->GetID());
2792         return SendErrorResponse(52);
2793     }
2794
2795     threads_array_sp->Write(response);
2796     StreamGDBRemote escaped_response;
2797     escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2798     return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2799 }
2800
2801 GDBRemoteCommunication::PacketResult
2802 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2803 {
2804     // Fail if we don't have a current process.
2805     if (!m_debugged_process_sp ||
2806             m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2807         return SendErrorResponse (68);
2808
2809     packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2810     if (packet.GetBytesLeft() == 0)
2811         return SendOKResponse();
2812     if (packet.GetChar() != ':')
2813         return SendErrorResponse(67);
2814
2815     uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2816     StreamGDBRemote response;
2817     response.Printf ("num:%d;", num);
2818     return SendPacketNoLock(response.GetData(), response.GetSize());
2819 }
2820
2821 GDBRemoteCommunication::PacketResult
2822 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2823 {
2824     // Fail if we don't have a current process.
2825     if (!m_debugged_process_sp ||
2826             m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2827         return SendErrorResponse(67);
2828
2829     packet.SetFilePos(strlen("qFileLoadAddress:"));
2830     if (packet.GetBytesLeft() == 0)
2831         return SendErrorResponse(68);
2832
2833     std::string file_name;
2834     packet.GetHexByteString(file_name);
2835
2836     lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2837     Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2838     if (error.Fail())
2839         return SendErrorResponse(69);
2840
2841     if (file_load_address == LLDB_INVALID_ADDRESS)
2842         return SendErrorResponse(1); // File not loaded
2843
2844     StreamGDBRemote response;
2845     response.PutHex64(file_load_address);
2846     return SendPacketNoLock(response.GetData(), response.GetSize());
2847 }
2848
2849 void
2850 GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2851 {
2852     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2853
2854     // Tell the stdio connection to shut down.
2855     if (m_stdio_communication.IsConnected())
2856     {
2857         auto connection = m_stdio_communication.GetConnection();
2858         if (connection)
2859         {
2860             Error error;
2861             connection->Disconnect (&error);
2862
2863             if (error.Success ())
2864             {
2865                 if (log)
2866                     log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2867             }
2868             else
2869             {
2870                 if (log)
2871                     log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2872             }
2873         }
2874     }
2875 }
2876
2877
2878 NativeThreadProtocolSP
2879 GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2880 {
2881     NativeThreadProtocolSP thread_sp;
2882
2883     // We have no thread if we don't have a process.
2884     if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2885         return thread_sp;
2886
2887     // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2888     // Use the current thread in that case.
2889     if (!m_thread_suffix_supported)
2890     {
2891         const lldb::tid_t current_tid = GetCurrentThreadID ();
2892         if (current_tid == LLDB_INVALID_THREAD_ID)
2893             return thread_sp;
2894         else if (current_tid == 0)
2895         {
2896             // Pick a thread.
2897             return m_debugged_process_sp->GetThreadAtIndex (0);
2898         }
2899         else
2900             return m_debugged_process_sp->GetThreadByID (current_tid);
2901     }
2902
2903     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2904
2905     // Parse out the ';'.
2906     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2907     {
2908         if (log)
2909             log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2910         return thread_sp;
2911     }
2912
2913     if (!packet.GetBytesLeft ())
2914         return thread_sp;
2915
2916     // Parse out thread: portion.
2917     if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2918     {
2919         if (log)
2920             log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2921         return thread_sp;
2922     }
2923     packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2924     const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2925     if (tid != 0)
2926         return m_debugged_process_sp->GetThreadByID (tid);
2927
2928     return thread_sp;
2929 }
2930
2931 lldb::tid_t
2932 GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2933 {
2934     if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2935     {
2936         // Use whatever the debug process says is the current thread id
2937         // since the protocol either didn't specify or specified we want
2938         // any/all threads marked as the current thread.
2939         if (!m_debugged_process_sp)
2940             return LLDB_INVALID_THREAD_ID;
2941         return m_debugged_process_sp->GetCurrentThreadID ();
2942     }
2943     // Use the specific current thread id set by the gdb remote protocol.
2944     return m_current_tid;
2945 }
2946
2947 uint32_t
2948 GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2949 {
2950     Mutex::Locker locker (m_saved_registers_mutex);
2951     return m_next_saved_registers_id++;
2952 }
2953
2954 void
2955 GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2956 {
2957     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2958     if (log)
2959         log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2960
2961     // Clear any auxv cached data.
2962     // *BSD impls should be able to do this too.
2963 #if defined(__linux__)
2964     if (log)
2965         log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2966                      __FUNCTION__,
2967                      m_active_auxv_buffer_sp ? "was set" : "was not set");
2968     m_active_auxv_buffer_sp.reset ();
2969 #endif
2970 }
2971
2972 FileSpec
2973 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2974                                                  const ArchSpec& arch)
2975 {
2976     if (m_debugged_process_sp)
2977     {
2978         FileSpec file_spec;
2979         if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2980         {
2981             if (file_spec.Exists())
2982                 return file_spec;
2983         }
2984     }
2985
2986     return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
2987 }