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