xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp (revision 1ef7b2c89794d6644a8a7fe1bad944e4ed1652e3)
1 //===-- GDBRemoteCommunicationServer.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 "GDBRemoteCommunicationServer.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/Debugger.h"
27 #include "lldb/Core/Log.h"
28 #include "lldb/Core/State.h"
29 #include "lldb/Core/StreamString.h"
30 #include "lldb/Host/ConnectionFileDescriptor.h"
31 #include "lldb/Host/Debug.h"
32 #include "lldb/Host/Endian.h"
33 #include "lldb/Host/File.h"
34 #include "lldb/Host/FileSystem.h"
35 #include "lldb/Host/Host.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Host/StringConvert.h"
38 #include "lldb/Host/TimeValue.h"
39 #include "lldb/Target/FileAction.h"
40 #include "lldb/Target/Platform.h"
41 #include "lldb/Target/Process.h"
42 #include "lldb/Host/common/NativeRegisterContext.h"
43 #include "lldb/Host/common/NativeProcessProtocol.h"
44 #include "lldb/Host/common/NativeThreadProtocol.h"
45 
46 // Project includes
47 #include "Utility/StringExtractorGDBRemote.h"
48 #include "Utility/UriParser.h"
49 #include "ProcessGDBRemote.h"
50 #include "ProcessGDBRemoteLog.h"
51 
52 using namespace lldb;
53 using namespace lldb_private;
54 
55 //----------------------------------------------------------------------
56 // GDBRemote Errors
57 //----------------------------------------------------------------------
58 
59 namespace
60 {
61     enum GDBRemoteServerError
62     {
63         // Set to the first unused error number in literal form below
64         eErrorFirst = 29,
65         eErrorNoProcess = eErrorFirst,
66         eErrorResume,
67         eErrorExitStatus
68     };
69 }
70 
71 //----------------------------------------------------------------------
72 // GDBRemoteCommunicationServer constructor
73 //----------------------------------------------------------------------
74 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
75     GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
76     m_platform_sp (Platform::GetHostPlatform ()),
77     m_async_thread (LLDB_INVALID_HOST_THREAD),
78     m_process_launch_info (),
79     m_process_launch_error (),
80     m_spawned_pids (),
81     m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
82     m_proc_infos (),
83     m_proc_infos_index (0),
84     m_port_map (),
85     m_port_offset(0),
86     m_current_tid (LLDB_INVALID_THREAD_ID),
87     m_continue_tid (LLDB_INVALID_THREAD_ID),
88     m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
89     m_debugged_process_sp (),
90     m_debugger_sp (),
91     m_stdio_communication ("process.stdio"),
92     m_exit_now (false),
93     m_inferior_prev_state (StateType::eStateInvalid),
94     m_thread_suffix_supported (false),
95     m_list_threads_in_stop_reply (false),
96     m_active_auxv_buffer_sp (),
97     m_saved_registers_mutex (),
98     m_saved_registers_map (),
99     m_next_saved_registers_id (1)
100 {
101     assert(is_platform && "must be lldb-platform if debugger is not specified");
102 }
103 
104 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
105                                                            const lldb::PlatformSP& platform_sp,
106                                                            lldb::DebuggerSP &debugger_sp) :
107     GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
108     m_platform_sp (platform_sp),
109     m_async_thread (LLDB_INVALID_HOST_THREAD),
110     m_process_launch_info (),
111     m_process_launch_error (),
112     m_spawned_pids (),
113     m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
114     m_proc_infos (),
115     m_proc_infos_index (0),
116     m_port_map (),
117     m_port_offset(0),
118     m_current_tid (LLDB_INVALID_THREAD_ID),
119     m_continue_tid (LLDB_INVALID_THREAD_ID),
120     m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
121     m_debugged_process_sp (),
122     m_debugger_sp (debugger_sp),
123     m_stdio_communication ("process.stdio"),
124     m_exit_now (false),
125     m_inferior_prev_state (StateType::eStateInvalid),
126     m_thread_suffix_supported (false),
127     m_list_threads_in_stop_reply (false),
128     m_active_auxv_buffer_sp (),
129     m_saved_registers_mutex (),
130     m_saved_registers_map (),
131     m_next_saved_registers_id (1)
132 {
133     assert(platform_sp);
134     assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
135 }
136 
137 //----------------------------------------------------------------------
138 // Destructor
139 //----------------------------------------------------------------------
140 GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
141 {
142 }
143 
144 GDBRemoteCommunication::PacketResult
145 GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
146                                                         Error &error,
147                                                         bool &interrupt,
148                                                         bool &quit)
149 {
150     StringExtractorGDBRemote packet;
151 
152     PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
153     if (packet_result == PacketResult::Success)
154     {
155         const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
156         switch (packet_type)
157         {
158         case StringExtractorGDBRemote::eServerPacketType_nack:
159         case StringExtractorGDBRemote::eServerPacketType_ack:
160             break;
161 
162         case StringExtractorGDBRemote::eServerPacketType_invalid:
163             error.SetErrorString("invalid packet");
164             quit = true;
165             break;
166 
167         default:
168         case StringExtractorGDBRemote::eServerPacketType_unimplemented:
169             packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
170             break;
171 
172         case StringExtractorGDBRemote::eServerPacketType_A:
173             packet_result = Handle_A (packet);
174             break;
175 
176         case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
177             packet_result = Handle_qfProcessInfo (packet);
178             break;
179 
180         case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
181             packet_result = Handle_qsProcessInfo (packet);
182             break;
183 
184         case StringExtractorGDBRemote::eServerPacketType_qC:
185             packet_result = Handle_qC (packet);
186             break;
187 
188         case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
189             packet_result = Handle_qHostInfo (packet);
190             break;
191 
192         case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
193             packet_result = Handle_qLaunchGDBServer (packet);
194             break;
195 
196         case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
197             packet_result = Handle_qKillSpawnedProcess (packet);
198             break;
199 
200         case StringExtractorGDBRemote::eServerPacketType_k:
201             packet_result = Handle_k (packet);
202             quit = true;
203             break;
204 
205         case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
206             packet_result = Handle_qLaunchSuccess (packet);
207             break;
208 
209         case StringExtractorGDBRemote::eServerPacketType_qGroupName:
210             packet_result = Handle_qGroupName (packet);
211             break;
212 
213         case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
214             packet_result = Handle_qProcessInfo (packet);
215             break;
216 
217         case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
218             packet_result = Handle_qProcessInfoPID (packet);
219             break;
220 
221         case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
222             packet_result = Handle_qSpeedTest (packet);
223             break;
224 
225         case StringExtractorGDBRemote::eServerPacketType_qUserName:
226             packet_result = Handle_qUserName (packet);
227             break;
228 
229         case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
230             packet_result = Handle_qGetWorkingDir(packet);
231             break;
232 
233         case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
234             packet_result = Handle_QEnvironment (packet);
235             break;
236 
237         case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
238             packet_result = Handle_QLaunchArch (packet);
239             break;
240 
241         case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
242             packet_result = Handle_QSetDisableASLR (packet);
243             break;
244 
245         case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
246             packet_result = Handle_QSetDetachOnError (packet);
247             break;
248 
249         case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
250             packet_result = Handle_QSetSTDIN (packet);
251             break;
252 
253         case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
254             packet_result = Handle_QSetSTDOUT (packet);
255             break;
256 
257         case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
258             packet_result = Handle_QSetSTDERR (packet);
259             break;
260 
261         case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
262             packet_result = Handle_QSetWorkingDir (packet);
263             break;
264 
265         case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
266             packet_result = Handle_QStartNoAckMode (packet);
267             break;
268 
269         case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
270             packet_result = Handle_qPlatform_mkdir (packet);
271             break;
272 
273         case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
274             packet_result = Handle_qPlatform_chmod (packet);
275             break;
276 
277         case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
278             packet_result = Handle_qPlatform_shell (packet);
279             break;
280 
281         case StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo:
282             packet_result = Handle_qWatchpointSupportInfo (packet);
283             break;
284 
285         case StringExtractorGDBRemote::eServerPacketType_C:
286             packet_result = Handle_C (packet);
287             break;
288 
289         case StringExtractorGDBRemote::eServerPacketType_c:
290             packet_result = Handle_c (packet);
291             break;
292 
293         case StringExtractorGDBRemote::eServerPacketType_vCont:
294             packet_result = Handle_vCont (packet);
295             break;
296 
297         case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
298             packet_result = Handle_vCont_actions (packet);
299             break;
300 
301         case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
302             packet_result = Handle_stop_reason (packet);
303             break;
304 
305         case StringExtractorGDBRemote::eServerPacketType_vFile_open:
306             packet_result = Handle_vFile_Open (packet);
307             break;
308 
309         case StringExtractorGDBRemote::eServerPacketType_vFile_close:
310             packet_result = Handle_vFile_Close (packet);
311             break;
312 
313         case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
314             packet_result = Handle_vFile_pRead (packet);
315             break;
316 
317         case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
318             packet_result = Handle_vFile_pWrite (packet);
319             break;
320 
321         case StringExtractorGDBRemote::eServerPacketType_vFile_size:
322             packet_result = Handle_vFile_Size (packet);
323             break;
324 
325         case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
326             packet_result = Handle_vFile_Mode (packet);
327             break;
328 
329         case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
330             packet_result = Handle_vFile_Exists (packet);
331             break;
332 
333         case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
334             packet_result = Handle_vFile_Stat (packet);
335             break;
336 
337         case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
338             packet_result = Handle_vFile_MD5 (packet);
339             break;
340 
341         case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
342             packet_result = Handle_vFile_symlink (packet);
343             break;
344 
345         case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
346             packet_result = Handle_vFile_unlink (packet);
347             break;
348 
349         case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
350             packet_result = Handle_qRegisterInfo (packet);
351             break;
352 
353         case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
354             packet_result = Handle_qfThreadInfo (packet);
355             break;
356 
357         case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
358             packet_result = Handle_qsThreadInfo (packet);
359             break;
360 
361         case StringExtractorGDBRemote::eServerPacketType_p:
362             packet_result = Handle_p (packet);
363             break;
364 
365         case StringExtractorGDBRemote::eServerPacketType_P:
366             packet_result = Handle_P (packet);
367             break;
368 
369         case StringExtractorGDBRemote::eServerPacketType_H:
370             packet_result = Handle_H (packet);
371             break;
372 
373         case StringExtractorGDBRemote::eServerPacketType_m:
374             packet_result = Handle_m (packet);
375             break;
376 
377         case StringExtractorGDBRemote::eServerPacketType_M:
378             packet_result = Handle_M (packet);
379             break;
380 
381         case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
382             packet_result = Handle_qMemoryRegionInfoSupported (packet);
383             break;
384 
385         case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
386             packet_result = Handle_qMemoryRegionInfo (packet);
387             break;
388 
389         case StringExtractorGDBRemote::eServerPacketType_interrupt:
390             if (IsGdbServer ())
391                 packet_result = Handle_interrupt (packet);
392             else
393             {
394                 error.SetErrorString("interrupt received");
395                 interrupt = true;
396             }
397             break;
398 
399         case StringExtractorGDBRemote::eServerPacketType_Z:
400             packet_result = Handle_Z (packet);
401             break;
402 
403         case StringExtractorGDBRemote::eServerPacketType_z:
404             packet_result = Handle_z (packet);
405             break;
406 
407         case StringExtractorGDBRemote::eServerPacketType_s:
408             packet_result = Handle_s (packet);
409             break;
410 
411         case StringExtractorGDBRemote::eServerPacketType_qSupported:
412             packet_result = Handle_qSupported (packet);
413             break;
414 
415         case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
416             packet_result = Handle_QThreadSuffixSupported (packet);
417             break;
418 
419         case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
420             packet_result = Handle_QListThreadsInStopReply (packet);
421             break;
422 
423         case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
424             packet_result = Handle_qXfer_auxv_read (packet);
425             break;
426 
427         case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
428             packet_result = Handle_QSaveRegisterState (packet);
429             break;
430 
431         case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
432             packet_result = Handle_QRestoreRegisterState (packet);
433             break;
434 
435         case StringExtractorGDBRemote::eServerPacketType_vAttach:
436             packet_result = Handle_vAttach (packet);
437             break;
438 
439         case StringExtractorGDBRemote::eServerPacketType_D:
440             packet_result = Handle_D (packet);
441             break;
442 
443         case StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo:
444             packet_result = Handle_qThreadStopInfo (packet);
445             break;
446         }
447     }
448     else
449     {
450         if (!IsConnected())
451         {
452             error.SetErrorString("lost connection");
453             quit = true;
454         }
455         else
456         {
457             error.SetErrorString("timeout");
458         }
459     }
460 
461     // Check if anything occurred that would force us to want to exit.
462     if (m_exit_now)
463         quit = true;
464 
465     return packet_result;
466 }
467 
468 lldb_private::Error
469 GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
470 {
471     if ((argc < 1) || !args || !args[0] || !args[0][0])
472         return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
473 
474     m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
475     return lldb_private::Error ();
476 }
477 
478 lldb_private::Error
479 GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
480 {
481     m_process_launch_info.GetFlags ().Set (launch_flags);
482     return lldb_private::Error ();
483 }
484 
485 lldb_private::Error
486 GDBRemoteCommunicationServer::LaunchProcess ()
487 {
488     // FIXME This looks an awful lot like we could override this in
489     // derived classes, one for lldb-platform, the other for lldb-gdbserver.
490     if (IsGdbServer ())
491         return LaunchProcessForDebugging ();
492     else
493         return LaunchPlatformProcess ();
494 }
495 
496 bool
497 GDBRemoteCommunicationServer::ShouldRedirectInferiorOutputOverGdbRemote (const lldb_private::ProcessLaunchInfo &launch_info) const
498 {
499     // Retrieve the file actions specified for stdout and stderr.
500     auto stdout_file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
501     auto stderr_file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
502 
503     // If neither stdout and stderr file actions are specified, we're not doing anything special, so
504     // assume we want to redirect stdout/stderr over gdb-remote $O messages.
505     if ((stdout_file_action == nullptr) && (stderr_file_action == nullptr))
506     {
507         // Send stdout/stderr over the gdb-remote protocol.
508         return true;
509     }
510 
511     // Any other setting for either stdout or stderr implies we are either suppressing
512     // it (with /dev/null) or we've got it set to a PTY.  Either way, we don't want the
513     // output over gdb-remote.
514     return false;
515 }
516 
517 lldb_private::Error
518 GDBRemoteCommunicationServer::LaunchProcessForDebugging ()
519 {
520     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
521 
522     if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
523         return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
524 
525     lldb_private::Error error;
526     {
527         Mutex::Locker locker (m_debugged_process_mutex);
528         assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
529         error = m_platform_sp->LaunchNativeProcess (
530             m_process_launch_info,
531             *this,
532             m_debugged_process_sp);
533     }
534 
535     if (!error.Success ())
536     {
537         fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
538         return error;
539     }
540 
541     // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as needed.
542     // llgs local-process debugging may specify PTYs, which will eliminate the need to reflect inferior
543     // stdout/stderr over the gdb-remote protocol.
544     if (ShouldRedirectInferiorOutputOverGdbRemote (m_process_launch_info))
545     {
546         if (log)
547             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
548 
549         // Setup stdout/stderr mapping from inferior to $O
550         auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
551         if (terminal_fd >= 0)
552         {
553             if (log)
554                 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
555             error = SetSTDIOFileDescriptor (terminal_fd);
556             if (error.Fail ())
557                 return error;
558         }
559         else
560         {
561             if (log)
562                 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
563         }
564     }
565     else
566     {
567         if (log)
568             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
569     }
570 
571     printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
572 
573     // Add to list of spawned processes.
574     lldb::pid_t pid;
575     if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
576     {
577         // add to spawned pids
578         Mutex::Locker locker (m_spawned_pids_mutex);
579         // On an lldb-gdbserver, we would expect there to be only one.
580         assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
581         m_spawned_pids.insert (pid);
582     }
583 
584     return error;
585 }
586 
587 lldb_private::Error
588 GDBRemoteCommunicationServer::LaunchPlatformProcess ()
589 {
590     if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
591         return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
592 
593     // specify the process monitor if not already set.  This should
594     // generally be what happens since we need to reap started
595     // processes.
596     if (!m_process_launch_info.GetMonitorProcessCallback ())
597         m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
598 
599     lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
600     if (!error.Success ())
601     {
602         fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
603         return error;
604     }
605 
606     printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID());
607 
608     // add to list of spawned processes.  On an lldb-gdbserver, we
609     // would expect there to be only one.
610     const auto pid = m_process_launch_info.GetProcessID();
611     if (pid != LLDB_INVALID_PROCESS_ID)
612     {
613         // add to spawned pids
614         Mutex::Locker locker (m_spawned_pids_mutex);
615         m_spawned_pids.insert(pid);
616     }
617 
618     return error;
619 }
620 
621 lldb_private::Error
622 GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
623 {
624     Error error;
625 
626     if (!IsGdbServer ())
627     {
628         error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
629         return error;
630     }
631 
632     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
633     if (log)
634         log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
635 
636     // Scope for mutex locker.
637     {
638         // Before we try to attach, make sure we aren't already monitoring something else.
639         Mutex::Locker locker (m_spawned_pids_mutex);
640         if (!m_spawned_pids.empty ())
641         {
642             error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
643             return error;
644         }
645 
646         // Try to attach.
647         error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
648         if (!error.Success ())
649         {
650             fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
651             return error;
652         }
653 
654         // Setup stdout/stderr mapping from inferior.
655         auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
656         if (terminal_fd >= 0)
657         {
658             if (log)
659                 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
660             error = SetSTDIOFileDescriptor (terminal_fd);
661             if (error.Fail ())
662                 return error;
663         }
664         else
665         {
666             if (log)
667                 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
668         }
669 
670         printf ("Attached to process %" PRIu64 "...\n", pid);
671 
672         // Add to list of spawned processes.
673         assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
674         m_spawned_pids.insert (pid);
675 
676         return error;
677     }
678 }
679 
680 void
681 GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
682 {
683     assert (process && "process cannot be NULL");
684     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
685     if (log)
686     {
687         log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
688                 __FUNCTION__,
689                 process->GetID (),
690                 StateAsCString (process->GetState ()));
691     }
692 }
693 
694 GDBRemoteCommunication::PacketResult
695 GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
696 {
697     assert (process && "process cannot be NULL");
698     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
699 
700     // send W notification
701     ExitType exit_type = ExitType::eExitTypeInvalid;
702     int return_code = 0;
703     std::string exit_description;
704 
705     const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
706     if (!got_exit_info)
707     {
708         if (log)
709             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
710 
711         StreamGDBRemote response;
712         response.PutChar ('E');
713         response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
714         return SendPacketNoLock(response.GetData(), response.GetSize());
715     }
716     else
717     {
718         if (log)
719             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
720 
721         StreamGDBRemote response;
722 
723         char return_type_code;
724         switch (exit_type)
725         {
726             case ExitType::eExitTypeExit:
727                 return_type_code = 'W';
728                 break;
729             case ExitType::eExitTypeSignal:
730                 return_type_code = 'X';
731                 break;
732             case ExitType::eExitTypeStop:
733                 return_type_code = 'S';
734                 break;
735             case ExitType::eExitTypeInvalid:
736                 return_type_code = 'E';
737                 break;
738         }
739         response.PutChar (return_type_code);
740 
741         // POSIX exit status limited to unsigned 8 bits.
742         response.PutHex8 (return_code);
743 
744         return SendPacketNoLock(response.GetData(), response.GetSize());
745     }
746 }
747 
748 static void
749 AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
750 {
751     int64_t i;
752     if (swap)
753     {
754         for (i = buf_size-1; i >= 0; i--)
755             response.PutHex8 (buf[i]);
756     }
757     else
758     {
759         for (i = 0; i < buf_size; i++)
760             response.PutHex8 (buf[i]);
761     }
762 }
763 
764 static void
765 WriteRegisterValueInHexFixedWidth (StreamString &response,
766                                    NativeRegisterContextSP &reg_ctx_sp,
767                                    const RegisterInfo &reg_info,
768                                    const RegisterValue *reg_value_p)
769 {
770     RegisterValue reg_value;
771     if (!reg_value_p)
772     {
773         Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
774         if (error.Success ())
775             reg_value_p = &reg_value;
776         // else log.
777     }
778 
779     if (reg_value_p)
780     {
781         AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
782     }
783     else
784     {
785         // Zero-out any unreadable values.
786         if (reg_info.byte_size > 0)
787         {
788             std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
789             AppendHexValue (response, zeros.data(), zeros.size(), false);
790         }
791     }
792 }
793 
794 // WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
795 
796 
797 static void
798 WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
799                                               NativeRegisterContextSP &reg_ctx_sp,
800                                               const RegisterInfo &reg_info,
801                                               const RegisterValue &reg_value)
802 {
803     // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
804     // gdb register number, and VVVVVVVV is the correct number of hex bytes
805     // as ASCII for the register value.
806     if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
807         return;
808 
809     response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
810     WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
811     response.PutChar (';');
812 }
813 
814 
815 GDBRemoteCommunication::PacketResult
816 GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
817 {
818     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
819 
820     // Ensure we're llgs.
821     if (!IsGdbServer ())
822     {
823         // Only supported on llgs
824         return SendUnimplementedResponse ("");
825     }
826 
827     // Ensure we have a debugged process.
828     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
829         return SendErrorResponse (50);
830 
831     if (log)
832         log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
833                 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
834 
835     // Ensure we can get info on the given thread.
836     NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
837     if (!thread_sp)
838         return SendErrorResponse (51);
839 
840     // Grab the reason this thread stopped.
841     struct ThreadStopInfo tid_stop_info;
842     std::string description;
843     if (!thread_sp->GetStopReason (tid_stop_info, description))
844         return SendErrorResponse (52);
845 
846     // FIXME implement register handling for exec'd inferiors.
847     // if (tid_stop_info.reason == eStopReasonExec)
848     // {
849     //     const bool force = true;
850     //     InitializeRegisters(force);
851     // }
852 
853     StreamString response;
854     // Output the T packet with the thread
855     response.PutChar ('T');
856     int signum = tid_stop_info.details.signal.signo;
857     if (log)
858     {
859         log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
860                 __FUNCTION__,
861                 m_debugged_process_sp->GetID (),
862                 tid,
863                 signum,
864                 tid_stop_info.reason,
865                 tid_stop_info.details.exception.type);
866     }
867 
868     // Print the signal number.
869     response.PutHex8 (signum & 0xff);
870 
871     // Include the tid.
872     response.Printf ("thread:%" PRIx64 ";", tid);
873 
874     // Include the thread name if there is one.
875     const std::string thread_name = thread_sp->GetName ();
876     if (!thread_name.empty ())
877     {
878         size_t thread_name_len = thread_name.length ();
879 
880         if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
881         {
882             response.PutCString ("name:");
883             response.PutCString (thread_name.c_str ());
884         }
885         else
886         {
887             // The thread name contains special chars, send as hex bytes.
888             response.PutCString ("hexname:");
889             response.PutCStringAsRawHex8 (thread_name.c_str ());
890         }
891         response.PutChar (';');
892     }
893 
894     // If a 'QListThreadsInStopReply' was sent to enable this feature, we
895     // will send all thread IDs back in the "threads" key whose value is
896     // a list of hex thread IDs separated by commas:
897     //  "threads:10a,10b,10c;"
898     // This will save the debugger from having to send a pair of qfThreadInfo
899     // and qsThreadInfo packets, but it also might take a lot of room in the
900     // stop reply packet, so it must be enabled only on systems where there
901     // are no limits on packet lengths.
902     if (m_list_threads_in_stop_reply)
903     {
904         response.PutCString ("threads:");
905 
906         uint32_t thread_index = 0;
907         NativeThreadProtocolSP listed_thread_sp;
908         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))
909         {
910             if (thread_index > 0)
911                 response.PutChar (',');
912             response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
913         }
914         response.PutChar (';');
915     }
916 
917     //
918     // Expedite registers.
919     //
920 
921     // Grab the register context.
922     NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
923     if (reg_ctx_sp)
924     {
925         // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
926         const RegisterSet *reg_set_p;
927         if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
928         {
929             if (log)
930                 log->Printf ("GDBRemoteCommunicationServer::%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);
931 
932             for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
933             {
934                 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
935                 if (reg_info_p == nullptr)
936                 {
937                     if (log)
938                         log->Printf ("GDBRemoteCommunicationServer::%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);
939                 }
940                 else if (reg_info_p->value_regs == nullptr)
941                 {
942                     // Only expediate registers that are not contained in other registers.
943                     RegisterValue reg_value;
944                     Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
945                     if (error.Success ())
946                         WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
947                     else
948                     {
949                         if (log)
950                             log->Printf ("GDBRemoteCommunicationServer::%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 ());
951 
952                     }
953                 }
954             }
955         }
956     }
957 
958     const char* reason_str = nullptr;
959     switch (tid_stop_info.reason)
960     {
961     case eStopReasonTrace:
962         reason_str = "trace";
963         break;
964     case eStopReasonBreakpoint:
965         reason_str = "breakpoint";
966         break;
967     case eStopReasonWatchpoint:
968         reason_str = "watchpoint";
969         break;
970     case eStopReasonSignal:
971         reason_str = "signal";
972         break;
973     case eStopReasonException:
974         reason_str = "exception";
975         break;
976     case eStopReasonExec:
977         reason_str = "exec";
978         break;
979     case eStopReasonInstrumentation:
980     case eStopReasonInvalid:
981     case eStopReasonPlanComplete:
982     case eStopReasonThreadExiting:
983     case eStopReasonNone:
984         break;
985     }
986     if (reason_str != nullptr)
987     {
988         response.Printf ("reason:%s;", reason_str);
989     }
990 
991     if (!description.empty())
992     {
993         // Description may contains special chars, send as hex bytes.
994         response.PutCString ("description:");
995         response.PutCStringAsRawHex8 (description.c_str ());
996         response.PutChar (';');
997     }
998     else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
999     {
1000         response.PutCString ("metype:");
1001         response.PutHex64 (tid_stop_info.details.exception.type);
1002         response.PutCString (";mecount:");
1003         response.PutHex32 (tid_stop_info.details.exception.data_count);
1004         response.PutChar (';');
1005 
1006         for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
1007         {
1008             response.PutCString ("medata:");
1009             response.PutHex64 (tid_stop_info.details.exception.data[i]);
1010             response.PutChar (';');
1011         }
1012     }
1013 
1014     return SendPacketNoLock (response.GetData(), response.GetSize());
1015 }
1016 
1017 void
1018 GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
1019 {
1020     assert (process && "process cannot be NULL");
1021 
1022     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1023     if (log)
1024         log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1025 
1026     // Send the exit result, and don't flush output.
1027     // Note: flushing output here would join the inferior stdio reflection thread, which
1028     // would gunk up the waitpid monitor thread that is calling this.
1029     PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
1030     if (result != PacketResult::Success)
1031     {
1032         if (log)
1033             log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1034     }
1035 
1036     // Remove the process from the list of spawned pids.
1037     {
1038         Mutex::Locker locker (m_spawned_pids_mutex);
1039         if (m_spawned_pids.erase (process->GetID ()) < 1)
1040         {
1041             if (log)
1042                 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1043 
1044         }
1045     }
1046 
1047     // FIXME can't do this yet - since process state propagation is currently
1048     // synchronous, it is running off the NativeProcessProtocol's innards and
1049     // will tear down the NPP while it still has code to execute.
1050 #if 0
1051     // Clear the NativeProcessProtocol pointer.
1052     {
1053         Mutex::Locker locker (m_debugged_process_mutex);
1054         m_debugged_process_sp.reset();
1055     }
1056 #endif
1057 
1058     // Close the pipe to the inferior terminal i/o if we launched it
1059     // and set one up.  Otherwise, 'k' and its flush of stdio could
1060     // end up waiting on a thread join that will never end.  Consider
1061     // adding a timeout to the connection thread join call so we
1062     // can avoid that scenario altogether.
1063     MaybeCloseInferiorTerminalConnection ();
1064 
1065     // We are ready to exit the debug monitor.
1066     m_exit_now = true;
1067 }
1068 
1069 void
1070 GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1071 {
1072     assert (process && "process cannot be NULL");
1073 
1074     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1075     if (log)
1076         log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1077 
1078     // Send the stop reason unless this is the stop after the
1079     // launch or attach.
1080     switch (m_inferior_prev_state)
1081     {
1082         case eStateLaunching:
1083         case eStateAttaching:
1084             // Don't send anything per debugserver behavior.
1085             break;
1086         default:
1087             // In all other cases, send the stop reason.
1088             PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1089             if (result != PacketResult::Success)
1090             {
1091                 if (log)
1092                     log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1093             }
1094             break;
1095     }
1096 }
1097 
1098 void
1099 GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1100 {
1101     assert (process && "process cannot be NULL");
1102     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1103     if (log)
1104     {
1105         log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1106                 __FUNCTION__,
1107                 process->GetID (),
1108                 StateAsCString (state));
1109     }
1110 
1111     switch (state)
1112     {
1113     case StateType::eStateExited:
1114         HandleInferiorState_Exited (process);
1115         break;
1116 
1117     case StateType::eStateStopped:
1118         HandleInferiorState_Stopped (process);
1119         break;
1120 
1121     default:
1122         if (log)
1123         {
1124             log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1125                     __FUNCTION__,
1126                     process->GetID (),
1127                     StateAsCString (state));
1128         }
1129         break;
1130     }
1131 
1132     // Remember the previous state reported to us.
1133     m_inferior_prev_state = state;
1134 }
1135 
1136 void
1137 GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1138 {
1139     ClearProcessSpecificData ();
1140 }
1141 
1142 GDBRemoteCommunication::PacketResult
1143 GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1144 {
1145     if ((buffer == nullptr) || (len == 0))
1146     {
1147         // Nothing to send.
1148         return PacketResult::Success;
1149     }
1150 
1151     StreamString response;
1152     response.PutChar ('O');
1153     response.PutBytesAsRawHex8 (buffer, len);
1154 
1155     return SendPacketNoLock (response.GetData (), response.GetSize ());
1156 }
1157 
1158 lldb_private::Error
1159 GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1160 {
1161     Error error;
1162 
1163     // Set up the Read Thread for reading/handling process I/O
1164     std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1165     if (!conn_up)
1166     {
1167         error.SetErrorString ("failed to create ConnectionFileDescriptor");
1168         return error;
1169     }
1170 
1171     m_stdio_communication.SetConnection (conn_up.release());
1172     if (!m_stdio_communication.IsConnected ())
1173     {
1174         error.SetErrorString ("failed to set connection for inferior I/O communication");
1175         return error;
1176     }
1177 
1178     m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1179     m_stdio_communication.StartReadThread();
1180 
1181     return error;
1182 }
1183 
1184 void
1185 GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1186 {
1187     GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1188     static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1189 }
1190 
1191 GDBRemoteCommunication::PacketResult
1192 GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
1193 {
1194     // TODO: Log the packet we aren't handling...
1195     return SendPacketNoLock ("", 0);
1196 }
1197 
1198 
1199 GDBRemoteCommunication::PacketResult
1200 GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1201 {
1202     char packet[16];
1203     int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
1204     assert (packet_len < (int)sizeof(packet));
1205     return SendPacketNoLock (packet, packet_len);
1206 }
1207 
1208 GDBRemoteCommunication::PacketResult
1209 GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1210 {
1211     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1212     if (log)
1213         log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1214     return SendErrorResponse (0x03);
1215 }
1216 
1217 GDBRemoteCommunication::PacketResult
1218 GDBRemoteCommunicationServer::SendOKResponse ()
1219 {
1220     return SendPacketNoLock ("OK", 2);
1221 }
1222 
1223 bool
1224 GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1225 {
1226     return GetAck() == PacketResult::Success;
1227 }
1228 
1229 GDBRemoteCommunication::PacketResult
1230 GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
1231 {
1232     StreamString response;
1233 
1234     // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1235 
1236     ArchSpec host_arch(HostInfo::GetArchitecture());
1237     const llvm::Triple &host_triple = host_arch.GetTriple();
1238     response.PutCString("triple:");
1239     response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
1240     response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
1241 
1242     const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1243     if (distribution_id)
1244     {
1245         response.PutCString("distribution_id:");
1246         response.PutCStringAsRawHex8(distribution_id);
1247         response.PutCString(";");
1248     }
1249 
1250     // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1251 #if defined(__APPLE__)
1252     uint32_t cpu = host_arch.GetMachOCPUType();
1253     uint32_t sub = host_arch.GetMachOCPUSubType();
1254     if (cpu != LLDB_INVALID_CPUTYPE)
1255         response.Printf ("cputype:%u;", cpu);
1256     if (sub != LLDB_INVALID_CPUTYPE)
1257         response.Printf ("cpusubtype:%u;", sub);
1258 
1259     if (cpu == ArchSpec::kCore_arm_any)
1260         response.Printf("watchpoint_exceptions_received:before;");   // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1261     else
1262         response.Printf("watchpoint_exceptions_received:after;");
1263 #else
1264     response.Printf("watchpoint_exceptions_received:after;");
1265 #endif
1266 
1267     switch (lldb::endian::InlHostByteOrder())
1268     {
1269     case eByteOrderBig:     response.PutCString ("endian:big;"); break;
1270     case eByteOrderLittle:  response.PutCString ("endian:little;"); break;
1271     case eByteOrderPDP:     response.PutCString ("endian:pdp;"); break;
1272     default:                response.PutCString ("endian:unknown;"); break;
1273     }
1274 
1275     uint32_t major = UINT32_MAX;
1276     uint32_t minor = UINT32_MAX;
1277     uint32_t update = UINT32_MAX;
1278     if (HostInfo::GetOSVersion(major, minor, update))
1279     {
1280         if (major != UINT32_MAX)
1281         {
1282             response.Printf("os_version:%u", major);
1283             if (minor != UINT32_MAX)
1284             {
1285                 response.Printf(".%u", minor);
1286                 if (update != UINT32_MAX)
1287                     response.Printf(".%u", update);
1288             }
1289             response.PutChar(';');
1290         }
1291     }
1292 
1293     std::string s;
1294     if (HostInfo::GetOSBuildString(s))
1295     {
1296         response.PutCString ("os_build:");
1297         response.PutCStringAsRawHex8(s.c_str());
1298         response.PutChar(';');
1299     }
1300     if (HostInfo::GetOSKernelDescription(s))
1301     {
1302         response.PutCString ("os_kernel:");
1303         response.PutCStringAsRawHex8(s.c_str());
1304         response.PutChar(';');
1305     }
1306 
1307 #if defined(__APPLE__)
1308 
1309 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
1310     // For iOS devices, we are connected through a USB Mux so we never pretend
1311     // to actually have a hostname as far as the remote lldb that is connecting
1312     // to this lldb-platform is concerned
1313     response.PutCString ("hostname:");
1314     response.PutCStringAsRawHex8("127.0.0.1");
1315     response.PutChar(';');
1316 #else   // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
1317     if (HostInfo::GetHostname(s))
1318     {
1319         response.PutCString ("hostname:");
1320         response.PutCStringAsRawHex8(s.c_str());
1321         response.PutChar(';');
1322     }
1323 #endif  // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
1324 
1325 #else   // #if defined(__APPLE__)
1326     if (HostInfo::GetHostname(s))
1327     {
1328         response.PutCString ("hostname:");
1329         response.PutCStringAsRawHex8(s.c_str());
1330         response.PutChar(';');
1331     }
1332 #endif  // #if defined(__APPLE__)
1333 
1334     return SendPacketNoLock (response.GetData(), response.GetSize());
1335 }
1336 
1337 static void
1338 CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
1339 {
1340     response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1341                      proc_info.GetProcessID(),
1342                      proc_info.GetParentProcessID(),
1343                      proc_info.GetUserID(),
1344                      proc_info.GetGroupID(),
1345                      proc_info.GetEffectiveUserID(),
1346                      proc_info.GetEffectiveGroupID());
1347     response.PutCString ("name:");
1348     response.PutCStringAsRawHex8(proc_info.GetName());
1349     response.PutChar(';');
1350     const ArchSpec &proc_arch = proc_info.GetArchitecture();
1351     if (proc_arch.IsValid())
1352     {
1353         const llvm::Triple &proc_triple = proc_arch.GetTriple();
1354         response.PutCString("triple:");
1355         response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1356         response.PutChar(';');
1357     }
1358 }
1359 
1360 static void
1361 CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1362 {
1363     response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1364                      proc_info.GetProcessID(),
1365                      proc_info.GetParentProcessID(),
1366                      proc_info.GetUserID(),
1367                      proc_info.GetGroupID(),
1368                      proc_info.GetEffectiveUserID(),
1369                      proc_info.GetEffectiveGroupID());
1370 
1371     const ArchSpec &proc_arch = proc_info.GetArchitecture();
1372     if (proc_arch.IsValid())
1373     {
1374         const llvm::Triple &proc_triple = proc_arch.GetTriple();
1375 #if defined(__APPLE__)
1376         // We'll send cputype/cpusubtype.
1377         const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1378         if (cpu_type != 0)
1379             response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1380 
1381         const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1382         if (cpu_subtype != 0)
1383             response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
1384 
1385 
1386         const std::string vendor = proc_triple.getVendorName ();
1387         if (!vendor.empty ())
1388             response.Printf ("vendor:%s;", vendor.c_str ());
1389 #else
1390         // We'll send the triple.
1391         response.PutCString("triple:");
1392         response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1393         response.PutChar(';');
1394 
1395 #endif
1396         std::string ostype = proc_triple.getOSName ();
1397         // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1398         if (proc_triple.getVendor () == llvm::Triple::Apple)
1399         {
1400             switch (proc_triple.getArch ())
1401             {
1402                 case llvm::Triple::arm:
1403                 case llvm::Triple::aarch64:
1404                     ostype = "ios";
1405                     break;
1406                 default:
1407                     // No change.
1408                     break;
1409             }
1410         }
1411         response.Printf ("ostype:%s;", ostype.c_str ());
1412 
1413 
1414         switch (proc_arch.GetByteOrder ())
1415         {
1416             case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1417             case lldb::eByteOrderBig:    response.PutCString ("endian:big;");    break;
1418             case lldb::eByteOrderPDP:    response.PutCString ("endian:pdp;");    break;
1419             default:
1420                 // Nothing.
1421                 break;
1422         }
1423 
1424         if (proc_triple.isArch64Bit ())
1425             response.PutCString ("ptrsize:8;");
1426         else if (proc_triple.isArch32Bit ())
1427             response.PutCString ("ptrsize:4;");
1428         else if (proc_triple.isArch16Bit ())
1429             response.PutCString ("ptrsize:2;");
1430     }
1431 
1432 }
1433 
1434 
1435 GDBRemoteCommunication::PacketResult
1436 GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1437 {
1438     lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1439 
1440     if (IsGdbServer ())
1441     {
1442         // Fail if we don't have a current process.
1443         if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1444             return SendErrorResponse (68);
1445 
1446         pid = m_debugged_process_sp->GetID ();
1447     }
1448     else if (m_is_platform)
1449     {
1450         pid = m_process_launch_info.GetProcessID ();
1451     }
1452     else
1453         return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1454 
1455     if (pid == LLDB_INVALID_PROCESS_ID)
1456         return SendErrorResponse (1);
1457 
1458     ProcessInstanceInfo proc_info;
1459     if (!Host::GetProcessInfo (pid, proc_info))
1460         return SendErrorResponse (1);
1461 
1462     StreamString response;
1463     CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1464     return SendPacketNoLock (response.GetData (), response.GetSize ());
1465 }
1466 
1467 GDBRemoteCommunication::PacketResult
1468 GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
1469 {
1470     // Packet format: "qProcessInfoPID:%i" where %i is the pid
1471     packet.SetFilePos(::strlen ("qProcessInfoPID:"));
1472     lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1473     if (pid != LLDB_INVALID_PROCESS_ID)
1474     {
1475         ProcessInstanceInfo proc_info;
1476         if (Host::GetProcessInfo(pid, proc_info))
1477         {
1478             StreamString response;
1479             CreateProcessInfoResponse (proc_info, response);
1480             return SendPacketNoLock (response.GetData(), response.GetSize());
1481         }
1482     }
1483     return SendErrorResponse (1);
1484 }
1485 
1486 GDBRemoteCommunication::PacketResult
1487 GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1488 {
1489     m_proc_infos_index = 0;
1490     m_proc_infos.Clear();
1491 
1492     ProcessInstanceInfoMatch match_info;
1493     packet.SetFilePos(::strlen ("qfProcessInfo"));
1494     if (packet.GetChar() == ':')
1495     {
1496 
1497         std::string key;
1498         std::string value;
1499         while (packet.GetNameColonValue(key, value))
1500         {
1501             bool success = true;
1502             if (key.compare("name") == 0)
1503             {
1504                 StringExtractor extractor;
1505                 extractor.GetStringRef().swap(value);
1506                 extractor.GetHexByteString (value);
1507                 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
1508             }
1509             else if (key.compare("name_match") == 0)
1510             {
1511                 if (value.compare("equals") == 0)
1512                 {
1513                     match_info.SetNameMatchType (eNameMatchEquals);
1514                 }
1515                 else if (value.compare("starts_with") == 0)
1516                 {
1517                     match_info.SetNameMatchType (eNameMatchStartsWith);
1518                 }
1519                 else if (value.compare("ends_with") == 0)
1520                 {
1521                     match_info.SetNameMatchType (eNameMatchEndsWith);
1522                 }
1523                 else if (value.compare("contains") == 0)
1524                 {
1525                     match_info.SetNameMatchType (eNameMatchContains);
1526                 }
1527                 else if (value.compare("regex") == 0)
1528                 {
1529                     match_info.SetNameMatchType (eNameMatchRegularExpression);
1530                 }
1531                 else
1532                 {
1533                     success = false;
1534                 }
1535             }
1536             else if (key.compare("pid") == 0)
1537             {
1538                 match_info.GetProcessInfo().SetProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1539             }
1540             else if (key.compare("parent_pid") == 0)
1541             {
1542                 match_info.GetProcessInfo().SetParentProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1543             }
1544             else if (key.compare("uid") == 0)
1545             {
1546                 match_info.GetProcessInfo().SetUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1547             }
1548             else if (key.compare("gid") == 0)
1549             {
1550                 match_info.GetProcessInfo().SetGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1551             }
1552             else if (key.compare("euid") == 0)
1553             {
1554                 match_info.GetProcessInfo().SetEffectiveUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1555             }
1556             else if (key.compare("egid") == 0)
1557             {
1558                 match_info.GetProcessInfo().SetEffectiveGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1559             }
1560             else if (key.compare("all_users") == 0)
1561             {
1562                 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1563             }
1564             else if (key.compare("triple") == 0)
1565             {
1566                 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
1567             }
1568             else
1569             {
1570                 success = false;
1571             }
1572 
1573             if (!success)
1574                 return SendErrorResponse (2);
1575         }
1576     }
1577 
1578     if (Host::FindProcesses (match_info, m_proc_infos))
1579     {
1580         // We found something, return the first item by calling the get
1581         // subsequent process info packet handler...
1582         return Handle_qsProcessInfo (packet);
1583     }
1584     return SendErrorResponse (3);
1585 }
1586 
1587 GDBRemoteCommunication::PacketResult
1588 GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1589 {
1590     if (m_proc_infos_index < m_proc_infos.GetSize())
1591     {
1592         StreamString response;
1593         CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1594         ++m_proc_infos_index;
1595         return SendPacketNoLock (response.GetData(), response.GetSize());
1596     }
1597     return SendErrorResponse (4);
1598 }
1599 
1600 GDBRemoteCommunication::PacketResult
1601 GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1602 {
1603 #if !defined(LLDB_DISABLE_POSIX)
1604     // Packet format: "qUserName:%i" where %i is the uid
1605     packet.SetFilePos(::strlen ("qUserName:"));
1606     uint32_t uid = packet.GetU32 (UINT32_MAX);
1607     if (uid != UINT32_MAX)
1608     {
1609         std::string name;
1610         if (HostInfo::LookupUserName(uid, name))
1611         {
1612             StreamString response;
1613             response.PutCStringAsRawHex8 (name.c_str());
1614             return SendPacketNoLock (response.GetData(), response.GetSize());
1615         }
1616     }
1617 #endif
1618     return SendErrorResponse (5);
1619 
1620 }
1621 
1622 GDBRemoteCommunication::PacketResult
1623 GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1624 {
1625 #if !defined(LLDB_DISABLE_POSIX)
1626     // Packet format: "qGroupName:%i" where %i is the gid
1627     packet.SetFilePos(::strlen ("qGroupName:"));
1628     uint32_t gid = packet.GetU32 (UINT32_MAX);
1629     if (gid != UINT32_MAX)
1630     {
1631         std::string name;
1632         if (HostInfo::LookupGroupName(gid, name))
1633         {
1634             StreamString response;
1635             response.PutCStringAsRawHex8 (name.c_str());
1636             return SendPacketNoLock (response.GetData(), response.GetSize());
1637         }
1638     }
1639 #endif
1640     return SendErrorResponse (6);
1641 }
1642 
1643 GDBRemoteCommunication::PacketResult
1644 GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1645 {
1646     packet.SetFilePos(::strlen ("qSpeedTest:"));
1647 
1648     std::string key;
1649     std::string value;
1650     bool success = packet.GetNameColonValue(key, value);
1651     if (success && key.compare("response_size") == 0)
1652     {
1653         uint32_t response_size = StringConvert::ToUInt32(value.c_str(), 0, 0, &success);
1654         if (success)
1655         {
1656             if (response_size == 0)
1657                 return SendOKResponse();
1658             StreamString response;
1659             uint32_t bytes_left = response_size;
1660             response.PutCString("data:");
1661             while (bytes_left > 0)
1662             {
1663                 if (bytes_left >= 26)
1664                 {
1665                     response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1666                     bytes_left -= 26;
1667                 }
1668                 else
1669                 {
1670                     response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1671                     bytes_left = 0;
1672                 }
1673             }
1674             return SendPacketNoLock (response.GetData(), response.GetSize());
1675         }
1676     }
1677     return SendErrorResponse (7);
1678 }
1679 
1680 //
1681 //static bool
1682 //WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1683 //{
1684 //    const int time_delta_usecs = 100000;
1685 //    const int num_retries = timeout_in_seconds/time_delta_usecs;
1686 //    for (int i=0; i<num_retries; i++)
1687 //    {
1688 //        struct proc_bsdinfo bsd_info;
1689 //        int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1690 //                                    (uint64_t) 0,
1691 //                                    &bsd_info,
1692 //                                    PROC_PIDTBSDINFO_SIZE);
1693 //
1694 //        switch (error)
1695 //        {
1696 //            case EINVAL:
1697 //            case ENOTSUP:
1698 //            case ESRCH:
1699 //            case EPERM:
1700 //                return false;
1701 //
1702 //            default:
1703 //                break;
1704 //
1705 //            case 0:
1706 //                if (bsd_info.pbi_status == SSTOP)
1707 //                    return true;
1708 //        }
1709 //        ::usleep (time_delta_usecs);
1710 //    }
1711 //    return false;
1712 //}
1713 
1714 GDBRemoteCommunication::PacketResult
1715 GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1716 {
1717     // The 'A' packet is the most over designed packet ever here with
1718     // redundant argument indexes, redundant argument lengths and needed hex
1719     // encoded argument string values. Really all that is needed is a comma
1720     // separated hex encoded argument value list, but we will stay true to the
1721     // documented version of the 'A' packet here...
1722 
1723     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1724     int actual_arg_index = 0;
1725 
1726     packet.SetFilePos(1); // Skip the 'A'
1727     bool success = true;
1728     while (success && packet.GetBytesLeft() > 0)
1729     {
1730         // Decode the decimal argument string length. This length is the
1731         // number of hex nibbles in the argument string value.
1732         const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1733         if (arg_len == UINT32_MAX)
1734             success = false;
1735         else
1736         {
1737             // Make sure the argument hex string length is followed by a comma
1738             if (packet.GetChar() != ',')
1739                 success = false;
1740             else
1741             {
1742                 // Decode the argument index. We ignore this really because
1743                 // who would really send down the arguments in a random order???
1744                 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1745                 if (arg_idx == UINT32_MAX)
1746                     success = false;
1747                 else
1748                 {
1749                     // Make sure the argument index is followed by a comma
1750                     if (packet.GetChar() != ',')
1751                         success = false;
1752                     else
1753                     {
1754                         // Decode the argument string value from hex bytes
1755                         // back into a UTF8 string and make sure the length
1756                         // matches the one supplied in the packet
1757                         std::string arg;
1758                         if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
1759                             success = false;
1760                         else
1761                         {
1762                             // If there are any bytes left
1763                             if (packet.GetBytesLeft())
1764                             {
1765                                 if (packet.GetChar() != ',')
1766                                     success = false;
1767                             }
1768 
1769                             if (success)
1770                             {
1771                                 if (arg_idx == 0)
1772                                     m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1773                                 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
1774                                 if (log)
1775                                     log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1776                                 ++actual_arg_index;
1777                             }
1778                         }
1779                     }
1780                 }
1781             }
1782         }
1783     }
1784 
1785     if (success)
1786     {
1787         m_process_launch_error = LaunchProcess ();
1788         if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1789         {
1790             return SendOKResponse ();
1791         }
1792         else
1793         {
1794             Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1795             if (log)
1796                 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1797                         __FUNCTION__,
1798                         m_process_launch_error.AsCString());
1799 
1800         }
1801     }
1802     return SendErrorResponse (8);
1803 }
1804 
1805 GDBRemoteCommunication::PacketResult
1806 GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1807 {
1808     StreamString response;
1809 
1810     if (IsGdbServer ())
1811     {
1812         // Fail if we don't have a current process.
1813         if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1814             return SendErrorResponse (68);
1815 
1816         // Make sure we set the current thread so g and p packets return
1817         // the data the gdb will expect.
1818         lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1819         SetCurrentThreadID (tid);
1820 
1821         NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1822         if (!thread_sp)
1823             return SendErrorResponse (69);
1824 
1825         response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1826     }
1827     else
1828     {
1829         // NOTE: lldb should now be using qProcessInfo for process IDs.  This path here
1830         // should not be used.  It is reporting process id instead of thread id.  The
1831         // correct answer doesn't seem to make much sense for lldb-platform.
1832         // CONSIDER: flip to "unsupported".
1833         lldb::pid_t pid = m_process_launch_info.GetProcessID();
1834         response.Printf("QC%" PRIx64, pid);
1835 
1836         // this should always be platform here
1837         assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1838 
1839         if (m_is_platform)
1840         {
1841             // If we launch a process and this GDB server is acting as a platform,
1842             // then we need to clear the process launch state so we can start
1843             // launching another process. In order to launch a process a bunch or
1844             // packets need to be sent: environment packets, working directory,
1845             // disable ASLR, and many more settings. When we launch a process we
1846             // then need to know when to clear this information. Currently we are
1847             // selecting the 'qC' packet as that packet which seems to make the most
1848             // sense.
1849             if (pid != LLDB_INVALID_PROCESS_ID)
1850             {
1851                 m_process_launch_info.Clear();
1852             }
1853         }
1854     }
1855     return SendPacketNoLock (response.GetData(), response.GetSize());
1856 }
1857 
1858 bool
1859 GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1860 {
1861     Mutex::Locker locker (m_spawned_pids_mutex);
1862     FreePortForProcess(pid);
1863     return m_spawned_pids.erase(pid) > 0;
1864 }
1865 bool
1866 GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1867                                                       lldb::pid_t pid,
1868                                                       bool exited,
1869                                                       int signal,    // Zero for no signal
1870                                                       int status)    // Exit value of process if signal is zero
1871 {
1872     GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1873     server->DebugserverProcessReaped (pid);
1874     return true;
1875 }
1876 
1877 bool
1878 GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1879 {
1880     // reap a process that we were debugging (but not debugserver)
1881     Mutex::Locker locker (m_spawned_pids_mutex);
1882     return m_spawned_pids.erase(pid) > 0;
1883 }
1884 
1885 bool
1886 GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1887                                                    lldb::pid_t pid,
1888                                                    bool exited,
1889                                                    int signal,    // Zero for no signal
1890                                                    int status)    // Exit value of process if signal is zero
1891 {
1892     GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1893     server->DebuggedProcessReaped (pid);
1894     return true;
1895 }
1896 
1897 GDBRemoteCommunication::PacketResult
1898 GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1899 {
1900 #ifdef _WIN32
1901     return SendErrorResponse(9);
1902 #else
1903     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1904 
1905     // Spawn a local debugserver as a platform so we can then attach or launch
1906     // a process...
1907 
1908     if (m_is_platform)
1909     {
1910         if (log)
1911             log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1912 
1913         // Sleep and wait a bit for debugserver to start to listen...
1914         ConnectionFileDescriptor file_conn;
1915         std::string hostname;
1916         // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
1917         // with the TMPDIR environment variable
1918         packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1919         std::string name;
1920         std::string value;
1921         uint16_t port = UINT16_MAX;
1922         while (packet.GetNameColonValue(name, value))
1923         {
1924             if (name.compare ("host") == 0)
1925                 hostname.swap(value);
1926             else if (name.compare ("port") == 0)
1927                 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
1928         }
1929         if (port == UINT16_MAX)
1930             port = GetNextAvailablePort();
1931 
1932         // Spawn a new thread to accept the port that gets bound after
1933         // binding to port 0 (zero).
1934 
1935         // ignore the hostname send from the remote end, just use the ip address
1936         // that we're currently communicating with as the hostname
1937 
1938         // Spawn a debugserver and try to get the port it listens to.
1939         ProcessLaunchInfo debugserver_launch_info;
1940         if (hostname.empty())
1941             hostname = "127.0.0.1";
1942         if (log)
1943             log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1944 
1945         // Do not run in a new session so that it can not linger after the
1946         // platform closes.
1947         debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
1948         debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1949 
1950         std::string platform_scheme;
1951         std::string platform_ip;
1952         int platform_port;
1953         std::string platform_path;
1954         bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), platform_scheme, platform_ip, platform_port, platform_path);
1955         assert(ok);
1956         Error error = StartDebugserverProcess (
1957                                          platform_ip.c_str(),
1958                                          port,
1959                                          debugserver_launch_info,
1960                                          port);
1961 
1962         lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1963 
1964 
1965         if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1966         {
1967             Mutex::Locker locker (m_spawned_pids_mutex);
1968             m_spawned_pids.insert(debugserver_pid);
1969             if (port > 0)
1970                 AssociatePortWithProcess(port, debugserver_pid);
1971         }
1972         else
1973         {
1974             if (port > 0)
1975                 FreePort (port);
1976         }
1977 
1978         if (error.Success())
1979         {
1980             if (log)
1981                 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
1982 
1983             char response[256];
1984             const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1985             assert (response_len < (int)sizeof(response));
1986             PacketResult packet_result = SendPacketNoLock (response, response_len);
1987 
1988             if (packet_result != PacketResult::Success)
1989             {
1990                 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1991                     ::kill (debugserver_pid, SIGINT);
1992             }
1993             return packet_result;
1994         }
1995         else
1996         {
1997             if (log)
1998                 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
1999         }
2000     }
2001     return SendErrorResponse (9);
2002 #endif
2003 }
2004 
2005 bool
2006 GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
2007 {
2008     // make sure we know about this process
2009     {
2010         Mutex::Locker locker (m_spawned_pids_mutex);
2011         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2012             return false;
2013     }
2014 
2015     // first try a SIGTERM (standard kill)
2016     Host::Kill (pid, SIGTERM);
2017 
2018     // check if that worked
2019     for (size_t i=0; i<10; ++i)
2020     {
2021         {
2022             Mutex::Locker locker (m_spawned_pids_mutex);
2023             if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2024             {
2025                 // it is now killed
2026                 return true;
2027             }
2028         }
2029         usleep (10000);
2030     }
2031 
2032     // check one more time after the final usleep
2033     {
2034         Mutex::Locker locker (m_spawned_pids_mutex);
2035         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2036             return true;
2037     }
2038 
2039     // the launched process still lives.  Now try killing it again,
2040     // this time with an unblockable signal.
2041     Host::Kill (pid, SIGKILL);
2042 
2043     for (size_t i=0; i<10; ++i)
2044     {
2045         {
2046             Mutex::Locker locker (m_spawned_pids_mutex);
2047             if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2048             {
2049                 // it is now killed
2050                 return true;
2051             }
2052         }
2053         usleep (10000);
2054     }
2055 
2056     // check one more time after the final usleep
2057     // Scope for locker
2058     {
2059         Mutex::Locker locker (m_spawned_pids_mutex);
2060         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2061             return true;
2062     }
2063 
2064     // no luck - the process still lives
2065     return false;
2066 }
2067 
2068 GDBRemoteCommunication::PacketResult
2069 GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
2070 {
2071     packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
2072 
2073     lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2074 
2075     // verify that we know anything about this pid.
2076     // Scope for locker
2077     {
2078         Mutex::Locker locker (m_spawned_pids_mutex);
2079         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2080         {
2081             // not a pid we know about
2082             return SendErrorResponse (10);
2083         }
2084     }
2085 
2086     // go ahead and attempt to kill the spawned process
2087     if (KillSpawnedProcess (pid))
2088         return SendOKResponse ();
2089     else
2090         return SendErrorResponse (11);
2091 }
2092 
2093 GDBRemoteCommunication::PacketResult
2094 GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2095 {
2096     // ignore for now if we're lldb_platform
2097     if (m_is_platform)
2098         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2099 
2100     // shutdown all spawned processes
2101     std::set<lldb::pid_t> spawned_pids_copy;
2102 
2103     // copy pids
2104     {
2105         Mutex::Locker locker (m_spawned_pids_mutex);
2106         spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2107     }
2108 
2109     // nuke the spawned processes
2110     for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2111     {
2112         lldb::pid_t spawned_pid = *it;
2113         if (!KillSpawnedProcess (spawned_pid))
2114         {
2115             fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2116         }
2117     }
2118 
2119     FlushInferiorOutput ();
2120 
2121     // No OK response for kill packet.
2122     // return SendOKResponse ();
2123     return PacketResult::Success;
2124 }
2125 
2126 GDBRemoteCommunication::PacketResult
2127 GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2128 {
2129     if (m_process_launch_error.Success())
2130         return SendOKResponse();
2131     StreamString response;
2132     response.PutChar('E');
2133     response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
2134     return SendPacketNoLock (response.GetData(), response.GetSize());
2135 }
2136 
2137 GDBRemoteCommunication::PacketResult
2138 GDBRemoteCommunicationServer::Handle_QEnvironment  (StringExtractorGDBRemote &packet)
2139 {
2140     packet.SetFilePos(::strlen ("QEnvironment:"));
2141     const uint32_t bytes_left = packet.GetBytesLeft();
2142     if (bytes_left > 0)
2143     {
2144         m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2145         return SendOKResponse ();
2146     }
2147     return SendErrorResponse (12);
2148 }
2149 
2150 GDBRemoteCommunication::PacketResult
2151 GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2152 {
2153     packet.SetFilePos(::strlen ("QLaunchArch:"));
2154     const uint32_t bytes_left = packet.GetBytesLeft();
2155     if (bytes_left > 0)
2156     {
2157         const char* arch_triple = packet.Peek();
2158         ArchSpec arch_spec(arch_triple,NULL);
2159         m_process_launch_info.SetArchitecture(arch_spec);
2160         return SendOKResponse();
2161     }
2162     return SendErrorResponse(13);
2163 }
2164 
2165 GDBRemoteCommunication::PacketResult
2166 GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2167 {
2168     packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2169     if (packet.GetU32(0))
2170         m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2171     else
2172         m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2173     return SendOKResponse ();
2174 }
2175 
2176 GDBRemoteCommunication::PacketResult
2177 GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2178 {
2179     packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2180     std::string path;
2181     packet.GetHexByteString(path);
2182     if (m_is_platform)
2183     {
2184 #ifdef _WIN32
2185         // Not implemented on Windows
2186         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2187 #else
2188         // If this packet is sent to a platform, then change the current working directory
2189         if (::chdir(path.c_str()) != 0)
2190             return SendErrorResponse(errno);
2191 #endif
2192     }
2193     else
2194     {
2195         m_process_launch_info.SwapWorkingDirectory (path);
2196     }
2197     return SendOKResponse ();
2198 }
2199 
2200 GDBRemoteCommunication::PacketResult
2201 GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2202 {
2203     StreamString response;
2204 
2205     if (m_is_platform)
2206     {
2207         // If this packet is sent to a platform, then change the current working directory
2208         char cwd[PATH_MAX];
2209         if (getcwd(cwd, sizeof(cwd)) == NULL)
2210         {
2211             return SendErrorResponse(errno);
2212         }
2213         else
2214         {
2215             response.PutBytesAsRawHex8(cwd, strlen(cwd));
2216             return SendPacketNoLock(response.GetData(), response.GetSize());
2217         }
2218     }
2219     else
2220     {
2221         const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2222         if (working_dir && working_dir[0])
2223         {
2224             response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2225             return SendPacketNoLock(response.GetData(), response.GetSize());
2226         }
2227         else
2228         {
2229             return SendErrorResponse(14);
2230         }
2231     }
2232 }
2233 
2234 GDBRemoteCommunication::PacketResult
2235 GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2236 {
2237     packet.SetFilePos(::strlen ("QSetSTDIN:"));
2238     FileAction file_action;
2239     std::string path;
2240     packet.GetHexByteString(path);
2241     const bool read = false;
2242     const bool write = true;
2243     if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2244     {
2245         m_process_launch_info.AppendFileAction(file_action);
2246         return SendOKResponse ();
2247     }
2248     return SendErrorResponse (15);
2249 }
2250 
2251 GDBRemoteCommunication::PacketResult
2252 GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2253 {
2254     packet.SetFilePos(::strlen ("QSetSTDOUT:"));
2255     FileAction file_action;
2256     std::string path;
2257     packet.GetHexByteString(path);
2258     const bool read = true;
2259     const bool write = false;
2260     if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2261     {
2262         m_process_launch_info.AppendFileAction(file_action);
2263         return SendOKResponse ();
2264     }
2265     return SendErrorResponse (16);
2266 }
2267 
2268 GDBRemoteCommunication::PacketResult
2269 GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2270 {
2271     packet.SetFilePos(::strlen ("QSetSTDERR:"));
2272     FileAction file_action;
2273     std::string path;
2274     packet.GetHexByteString(path);
2275     const bool read = true;
2276     const bool write = false;
2277     if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2278     {
2279         m_process_launch_info.AppendFileAction(file_action);
2280         return SendOKResponse ();
2281     }
2282     return SendErrorResponse (17);
2283 }
2284 
2285 GDBRemoteCommunication::PacketResult
2286 GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2287 {
2288     if (!IsGdbServer ())
2289         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2290 
2291     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2292     if (log)
2293         log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2294 
2295     // Ensure we have a native process.
2296     if (!m_debugged_process_sp)
2297     {
2298         if (log)
2299             log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2300         return SendErrorResponse (0x36);
2301     }
2302 
2303     // Pull out the signal number.
2304     packet.SetFilePos (::strlen ("C"));
2305     if (packet.GetBytesLeft () < 1)
2306     {
2307         // Shouldn't be using a C without a signal.
2308         return SendIllFormedResponse (packet, "C packet specified without signal.");
2309     }
2310     const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2311     if (signo == std::numeric_limits<uint32_t>::max ())
2312         return SendIllFormedResponse (packet, "failed to parse signal number");
2313 
2314     // Handle optional continue address.
2315     if (packet.GetBytesLeft () > 0)
2316     {
2317         // FIXME add continue at address support for $C{signo}[;{continue-address}].
2318         if (*packet.Peek () == ';')
2319             return SendUnimplementedResponse (packet.GetStringRef().c_str());
2320         else
2321             return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2322     }
2323 
2324     lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2325     Error error;
2326 
2327     // We have two branches: what to do if a continue thread is specified (in which case we target
2328     // sending the signal to that thread), or when we don't have a continue thread set (in which
2329     // case we send a signal to the process).
2330 
2331     // TODO discuss with Greg Clayton, make sure this makes sense.
2332 
2333     lldb::tid_t signal_tid = GetContinueThreadID ();
2334     if (signal_tid != LLDB_INVALID_THREAD_ID)
2335     {
2336         // The resume action for the continue thread (or all threads if a continue thread is not set).
2337         lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2338 
2339         // Add the action for the continue thread (or all threads when the continue thread isn't present).
2340         resume_actions.Append (action);
2341     }
2342     else
2343     {
2344         // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2345         error = m_debugged_process_sp->Signal (signo);
2346         if (error.Fail ())
2347         {
2348             if (log)
2349                 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2350                              __FUNCTION__,
2351                              m_debugged_process_sp->GetID (),
2352                              error.AsCString ());
2353 
2354             return SendErrorResponse (0x52);
2355         }
2356     }
2357 
2358     // Resume the threads.
2359     error = m_debugged_process_sp->Resume (resume_actions);
2360     if (error.Fail ())
2361     {
2362         if (log)
2363             log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2364                          __FUNCTION__,
2365                          m_debugged_process_sp->GetID (),
2366                          error.AsCString ());
2367 
2368         return SendErrorResponse (0x38);
2369     }
2370 
2371     // Don't send an "OK" packet; response is the stopped/exited message.
2372     return PacketResult::Success;
2373 }
2374 
2375 GDBRemoteCommunication::PacketResult
2376 GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2377 {
2378     if (!IsGdbServer ())
2379         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2380 
2381     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2382     if (log)
2383         log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2384 
2385     // We reuse this method in vCont - don't double adjust the file position.
2386     if (!skip_file_pos_adjustment)
2387         packet.SetFilePos (::strlen ("c"));
2388 
2389     // For now just support all continue.
2390     const bool has_continue_address = (packet.GetBytesLeft () > 0);
2391     if (has_continue_address)
2392     {
2393         if (log)
2394             log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2395         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2396     }
2397 
2398     // Ensure we have a native process.
2399     if (!m_debugged_process_sp)
2400     {
2401         if (log)
2402             log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2403         return SendErrorResponse (0x36);
2404     }
2405 
2406     // Build the ResumeActionList
2407     lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2408 
2409     Error error = m_debugged_process_sp->Resume (actions);
2410     if (error.Fail ())
2411     {
2412         if (log)
2413         {
2414             log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2415                          __FUNCTION__,
2416                          m_debugged_process_sp->GetID (),
2417                          error.AsCString ());
2418         }
2419         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2420     }
2421 
2422     if (log)
2423         log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2424 
2425     // No response required from continue.
2426     return PacketResult::Success;
2427 }
2428 
2429 GDBRemoteCommunication::PacketResult
2430 GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2431 {
2432     if (!IsGdbServer ())
2433     {
2434         // only llgs supports $vCont.
2435         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2436     }
2437 
2438     StreamString response;
2439     response.Printf("vCont;c;C;s;S");
2440 
2441     return SendPacketNoLock(response.GetData(), response.GetSize());
2442 }
2443 
2444 GDBRemoteCommunication::PacketResult
2445 GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2446 {
2447     if (!IsGdbServer ())
2448     {
2449         // only llgs supports $vCont
2450         return SendUnimplementedResponse (packet.GetStringRef().c_str());
2451     }
2452 
2453     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2454     if (log)
2455         log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2456 
2457     packet.SetFilePos (::strlen ("vCont"));
2458 
2459     // Check if this is all continue (no options or ";c").
2460     if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2461     {
2462         // Move the packet past the ";c".
2463         if (packet.GetBytesLeft ())
2464             packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2465 
2466         const bool skip_file_pos_adjustment = true;
2467         return Handle_c (packet, skip_file_pos_adjustment);
2468     }
2469     else if (::strcmp (packet.Peek (), ";s") == 0)
2470     {
2471         // Move past the ';', then do a simple 's'.
2472         packet.SetFilePos (packet.GetFilePos () + 1);
2473         return Handle_s (packet);
2474     }
2475 
2476     // Ensure we have a native process.
2477     if (!m_debugged_process_sp)
2478     {
2479         if (log)
2480             log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2481         return SendErrorResponse (0x36);
2482     }
2483 
2484     ResumeActionList thread_actions;
2485 
2486     while (packet.GetBytesLeft () && *packet.Peek () == ';')
2487     {
2488         // Skip the semi-colon.
2489         packet.GetChar ();
2490 
2491         // Build up the thread action.
2492         ResumeAction thread_action;
2493         thread_action.tid = LLDB_INVALID_THREAD_ID;
2494         thread_action.state = eStateInvalid;
2495         thread_action.signal = 0;
2496 
2497         const char action = packet.GetChar ();
2498         switch (action)
2499         {
2500             case 'C':
2501                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2502                 if (thread_action.signal == 0)
2503                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2504                 // Fall through to next case...
2505 
2506             case 'c':
2507                 // Continue
2508                 thread_action.state = eStateRunning;
2509                 break;
2510 
2511             case 'S':
2512                 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2513                 if (thread_action.signal == 0)
2514                     return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2515                 // Fall through to next case...
2516 
2517             case 's':
2518                 // Step
2519                 thread_action.state = eStateStepping;
2520                 break;
2521 
2522             default:
2523                 return SendIllFormedResponse (packet, "Unsupported vCont action");
2524                 break;
2525         }
2526 
2527         // Parse out optional :{thread-id} value.
2528         if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2529         {
2530             // Consume the separator.
2531             packet.GetChar ();
2532 
2533             thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2534             if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2535                 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2536         }
2537 
2538         thread_actions.Append (thread_action);
2539     }
2540 
2541     Error error = m_debugged_process_sp->Resume (thread_actions);
2542     if (error.Fail ())
2543     {
2544         if (log)
2545         {
2546             log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2547                          __FUNCTION__,
2548                          m_debugged_process_sp->GetID (),
2549                          error.AsCString ());
2550         }
2551         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2552     }
2553 
2554     if (log)
2555         log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2556 
2557     // No response required from vCont.
2558     return PacketResult::Success;
2559 }
2560 
2561 GDBRemoteCommunication::PacketResult
2562 GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2563 {
2564     // Send response first before changing m_send_acks to we ack this packet
2565     PacketResult packet_result = SendOKResponse ();
2566     m_send_acks = false;
2567     return packet_result;
2568 }
2569 
2570 GDBRemoteCommunication::PacketResult
2571 GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
2572 {
2573     packet.SetFilePos(::strlen("qPlatform_mkdir:"));
2574     mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
2575     if (packet.GetChar() == ',')
2576     {
2577         std::string path;
2578         packet.GetHexByteString(path);
2579         Error error = FileSystem::MakeDirectory(path.c_str(), mode);
2580         if (error.Success())
2581             return SendPacketNoLock ("OK", 2);
2582         else
2583             return SendErrorResponse(error.GetError());
2584     }
2585     return SendErrorResponse(20);
2586 }
2587 
2588 GDBRemoteCommunication::PacketResult
2589 GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2590 {
2591     packet.SetFilePos(::strlen("qPlatform_chmod:"));
2592 
2593     mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
2594     if (packet.GetChar() == ',')
2595     {
2596         std::string path;
2597         packet.GetHexByteString(path);
2598         Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
2599         if (error.Success())
2600             return SendPacketNoLock ("OK", 2);
2601         else
2602             return SendErrorResponse(error.GetError());
2603     }
2604     return SendErrorResponse(19);
2605 }
2606 
2607 GDBRemoteCommunication::PacketResult
2608 GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2609 {
2610     packet.SetFilePos(::strlen("vFile:open:"));
2611     std::string path;
2612     packet.GetHexByteStringTerminatedBy(path,',');
2613     if (!path.empty())
2614     {
2615         if (packet.GetChar() == ',')
2616         {
2617             uint32_t flags = packet.GetHexMaxU32(false, 0);
2618             if (packet.GetChar() == ',')
2619             {
2620                 mode_t mode = packet.GetHexMaxU32(false, 0600);
2621                 Error error;
2622                 int fd = ::open (path.c_str(), flags, mode);
2623                 const int save_errno = fd == -1 ? errno : 0;
2624                 StreamString response;
2625                 response.PutChar('F');
2626                 response.Printf("%i", fd);
2627                 if (save_errno)
2628                     response.Printf(",%i", save_errno);
2629                 return SendPacketNoLock(response.GetData(), response.GetSize());
2630             }
2631         }
2632     }
2633     return SendErrorResponse(18);
2634 }
2635 
2636 GDBRemoteCommunication::PacketResult
2637 GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2638 {
2639     packet.SetFilePos(::strlen("vFile:close:"));
2640     int fd = packet.GetS32(-1);
2641     Error error;
2642     int err = -1;
2643     int save_errno = 0;
2644     if (fd >= 0)
2645     {
2646         err = close(fd);
2647         save_errno = err == -1 ? errno : 0;
2648     }
2649     else
2650     {
2651         save_errno = EINVAL;
2652     }
2653     StreamString response;
2654     response.PutChar('F');
2655     response.Printf("%i", err);
2656     if (save_errno)
2657         response.Printf(",%i", save_errno);
2658     return SendPacketNoLock(response.GetData(), response.GetSize());
2659 }
2660 
2661 GDBRemoteCommunication::PacketResult
2662 GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2663 {
2664 #ifdef _WIN32
2665     // Not implemented on Windows
2666     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
2667 #else
2668     StreamGDBRemote response;
2669     packet.SetFilePos(::strlen("vFile:pread:"));
2670     int fd = packet.GetS32(-1);
2671     if (packet.GetChar() == ',')
2672     {
2673         uint64_t count = packet.GetU64(UINT64_MAX);
2674         if (packet.GetChar() == ',')
2675         {
2676             uint64_t offset = packet.GetU64(UINT32_MAX);
2677             if (count == UINT64_MAX)
2678             {
2679                 response.Printf("F-1:%i", EINVAL);
2680                 return SendPacketNoLock(response.GetData(), response.GetSize());
2681             }
2682 
2683             std::string buffer(count, 0);
2684             const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2685             const int save_errno = bytes_read == -1 ? errno : 0;
2686             response.PutChar('F');
2687             response.Printf("%zi", bytes_read);
2688             if (save_errno)
2689                 response.Printf(",%i", save_errno);
2690             else
2691             {
2692                 response.PutChar(';');
2693                 response.PutEscapedBytes(&buffer[0], bytes_read);
2694             }
2695             return SendPacketNoLock(response.GetData(), response.GetSize());
2696         }
2697     }
2698     return SendErrorResponse(21);
2699 
2700 #endif
2701 }
2702 
2703 GDBRemoteCommunication::PacketResult
2704 GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2705 {
2706 #ifdef _WIN32
2707     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
2708 #else
2709     packet.SetFilePos(::strlen("vFile:pwrite:"));
2710 
2711     StreamGDBRemote response;
2712     response.PutChar('F');
2713 
2714     int fd = packet.GetU32(UINT32_MAX);
2715     if (packet.GetChar() == ',')
2716     {
2717         off_t offset = packet.GetU64(UINT32_MAX);
2718         if (packet.GetChar() == ',')
2719         {
2720             std::string buffer;
2721             if (packet.GetEscapedBinaryData(buffer))
2722             {
2723                 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2724                 const int save_errno = bytes_written == -1 ? errno : 0;
2725                 response.Printf("%zi", bytes_written);
2726                 if (save_errno)
2727                     response.Printf(",%i", save_errno);
2728             }
2729             else
2730             {
2731                 response.Printf ("-1,%i", EINVAL);
2732             }
2733             return SendPacketNoLock(response.GetData(), response.GetSize());
2734         }
2735     }
2736     return SendErrorResponse(27);
2737 #endif
2738 }
2739 
2740 GDBRemoteCommunication::PacketResult
2741 GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2742 {
2743     packet.SetFilePos(::strlen("vFile:size:"));
2744     std::string path;
2745     packet.GetHexByteString(path);
2746     if (!path.empty())
2747     {
2748         lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
2749         StreamString response;
2750         response.PutChar('F');
2751         response.PutHex64(retcode);
2752         if (retcode == UINT64_MAX)
2753         {
2754             response.PutChar(',');
2755             response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2756         }
2757         return SendPacketNoLock(response.GetData(), response.GetSize());
2758     }
2759     return SendErrorResponse(22);
2760 }
2761 
2762 GDBRemoteCommunication::PacketResult
2763 GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2764 {
2765     packet.SetFilePos(::strlen("vFile:mode:"));
2766     std::string path;
2767     packet.GetHexByteString(path);
2768     if (!path.empty())
2769     {
2770         Error error;
2771         const uint32_t mode = File::GetPermissions(path.c_str(), error);
2772         StreamString response;
2773         response.Printf("F%u", mode);
2774         if (mode == 0 || error.Fail())
2775             response.Printf(",%i", (int)error.GetError());
2776         return SendPacketNoLock(response.GetData(), response.GetSize());
2777     }
2778     return SendErrorResponse(23);
2779 }
2780 
2781 GDBRemoteCommunication::PacketResult
2782 GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2783 {
2784     packet.SetFilePos(::strlen("vFile:exists:"));
2785     std::string path;
2786     packet.GetHexByteString(path);
2787     if (!path.empty())
2788     {
2789         bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
2790         StreamString response;
2791         response.PutChar('F');
2792         response.PutChar(',');
2793         if (retcode)
2794             response.PutChar('1');
2795         else
2796             response.PutChar('0');
2797         return SendPacketNoLock(response.GetData(), response.GetSize());
2798     }
2799     return SendErrorResponse(24);
2800 }
2801 
2802 GDBRemoteCommunication::PacketResult
2803 GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
2804 {
2805     packet.SetFilePos(::strlen("vFile:symlink:"));
2806     std::string dst, src;
2807     packet.GetHexByteStringTerminatedBy(dst, ',');
2808     packet.GetChar(); // Skip ',' char
2809     packet.GetHexByteString(src);
2810     Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
2811     StreamString response;
2812     response.Printf("F%u,%u", error.GetError(), error.GetError());
2813     return SendPacketNoLock(response.GetData(), response.GetSize());
2814 }
2815 
2816 GDBRemoteCommunication::PacketResult
2817 GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2818 {
2819     packet.SetFilePos(::strlen("vFile:unlink:"));
2820     std::string path;
2821     packet.GetHexByteString(path);
2822     Error error = FileSystem::Unlink(path.c_str());
2823     StreamString response;
2824     response.Printf("F%u,%u", error.GetError(), error.GetError());
2825     return SendPacketNoLock(response.GetData(), response.GetSize());
2826 }
2827 
2828 GDBRemoteCommunication::PacketResult
2829 GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2830 {
2831     packet.SetFilePos(::strlen("qPlatform_shell:"));
2832     std::string path;
2833     std::string working_dir;
2834     packet.GetHexByteStringTerminatedBy(path,',');
2835     if (!path.empty())
2836     {
2837         if (packet.GetChar() == ',')
2838         {
2839             // FIXME: add timeout to qPlatform_shell packet
2840             // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2841             uint32_t timeout = 10;
2842             if (packet.GetChar() == ',')
2843                 packet.GetHexByteString(working_dir);
2844             int status, signo;
2845             std::string output;
2846             Error err = Host::RunShellCommand(path.c_str(),
2847                                               working_dir.empty() ? NULL : working_dir.c_str(),
2848                                               &status, &signo, &output, timeout);
2849             StreamGDBRemote response;
2850             if (err.Fail())
2851             {
2852                 response.PutCString("F,");
2853                 response.PutHex32(UINT32_MAX);
2854             }
2855             else
2856             {
2857                 response.PutCString("F,");
2858                 response.PutHex32(status);
2859                 response.PutChar(',');
2860                 response.PutHex32(signo);
2861                 response.PutChar(',');
2862                 response.PutEscapedBytes(output.c_str(), output.size());
2863             }
2864             return SendPacketNoLock(response.GetData(), response.GetSize());
2865         }
2866     }
2867     return SendErrorResponse(24);
2868 }
2869 
2870 void
2871 GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2872 {
2873     assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2874 
2875     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2876     if (log)
2877         log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2878 
2879     m_current_tid = tid;
2880     if (m_debugged_process_sp)
2881         m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2882 }
2883 
2884 void
2885 GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2886 {
2887     assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2888 
2889     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2890     if (log)
2891         log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2892 
2893     m_continue_tid = tid;
2894 }
2895 
2896 GDBRemoteCommunication::PacketResult
2897 GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2898 {
2899     // Handle the $? gdbremote command.
2900     if (!IsGdbServer ())
2901         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2902 
2903     // If no process, indicate error
2904     if (!m_debugged_process_sp)
2905         return SendErrorResponse (02);
2906 
2907     return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2908 }
2909 
2910 GDBRemoteCommunication::PacketResult
2911 GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2912 {
2913     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2914 
2915     switch (process_state)
2916     {
2917         case eStateAttaching:
2918         case eStateLaunching:
2919         case eStateRunning:
2920         case eStateStepping:
2921         case eStateDetached:
2922             // NOTE: gdb protocol doc looks like it should return $OK
2923             // when everything is running (i.e. no stopped result).
2924             return PacketResult::Success;  // Ignore
2925 
2926         case eStateSuspended:
2927         case eStateStopped:
2928         case eStateCrashed:
2929         {
2930             lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2931             // Make sure we set the current thread so g and p packets return
2932             // the data the gdb will expect.
2933             SetCurrentThreadID (tid);
2934             return SendStopReplyPacketForThread (tid);
2935         }
2936 
2937         case eStateInvalid:
2938         case eStateUnloaded:
2939         case eStateExited:
2940             if (flush_on_exit)
2941                 FlushInferiorOutput ();
2942             return SendWResponse(m_debugged_process_sp.get());
2943 
2944         default:
2945             if (log)
2946             {
2947                 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2948                              __FUNCTION__,
2949                              m_debugged_process_sp->GetID (),
2950                              StateAsCString (process_state));
2951             }
2952             break;
2953     }
2954 
2955     return SendErrorResponse (0);
2956 }
2957 
2958 GDBRemoteCommunication::PacketResult
2959 GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2960 {
2961     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
2962 }
2963 
2964 GDBRemoteCommunication::PacketResult
2965 GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2966 {
2967     packet.SetFilePos(::strlen("vFile:MD5:"));
2968     std::string path;
2969     packet.GetHexByteString(path);
2970     if (!path.empty())
2971     {
2972         uint64_t a,b;
2973         StreamGDBRemote response;
2974         if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
2975         {
2976             response.PutCString("F,");
2977             response.PutCString("x");
2978         }
2979         else
2980         {
2981             response.PutCString("F,");
2982             response.PutHex64(a);
2983             response.PutHex64(b);
2984         }
2985         return SendPacketNoLock(response.GetData(), response.GetSize());
2986     }
2987     return SendErrorResponse(25);
2988 }
2989 
2990 GDBRemoteCommunication::PacketResult
2991 GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2992 {
2993     // Ensure we're llgs.
2994     if (!IsGdbServer())
2995         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2996 
2997     // Fail if we don't have a current process.
2998     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2999         return SendErrorResponse (68);
3000 
3001     // Ensure we have a thread.
3002     NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
3003     if (!thread_sp)
3004         return SendErrorResponse (69);
3005 
3006     // Get the register context for the first thread.
3007     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3008     if (!reg_context_sp)
3009         return SendErrorResponse (69);
3010 
3011     // Parse out the register number from the request.
3012     packet.SetFilePos (strlen("qRegisterInfo"));
3013     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3014     if (reg_index == std::numeric_limits<uint32_t>::max ())
3015         return SendErrorResponse (69);
3016 
3017     // Return the end of registers response if we've iterated one past the end of the register set.
3018     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
3019         return SendErrorResponse (69);
3020 
3021     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3022     if (!reg_info)
3023         return SendErrorResponse (69);
3024 
3025     // Build the reginfos response.
3026     StreamGDBRemote response;
3027 
3028     response.PutCString ("name:");
3029     response.PutCString (reg_info->name);
3030     response.PutChar (';');
3031 
3032     if (reg_info->alt_name && reg_info->alt_name[0])
3033     {
3034         response.PutCString ("alt-name:");
3035         response.PutCString (reg_info->alt_name);
3036         response.PutChar (';');
3037     }
3038 
3039     response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
3040 
3041     switch (reg_info->encoding)
3042     {
3043         case eEncodingUint:    response.PutCString ("encoding:uint;"); break;
3044         case eEncodingSint:    response.PutCString ("encoding:sint;"); break;
3045         case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
3046         case eEncodingVector:  response.PutCString ("encoding:vector;"); break;
3047         default: break;
3048     }
3049 
3050     switch (reg_info->format)
3051     {
3052         case eFormatBinary:          response.PutCString ("format:binary;"); break;
3053         case eFormatDecimal:         response.PutCString ("format:decimal;"); break;
3054         case eFormatHex:             response.PutCString ("format:hex;"); break;
3055         case eFormatFloat:           response.PutCString ("format:float;"); break;
3056         case eFormatVectorOfSInt8:   response.PutCString ("format:vector-sint8;"); break;
3057         case eFormatVectorOfUInt8:   response.PutCString ("format:vector-uint8;"); break;
3058         case eFormatVectorOfSInt16:  response.PutCString ("format:vector-sint16;"); break;
3059         case eFormatVectorOfUInt16:  response.PutCString ("format:vector-uint16;"); break;
3060         case eFormatVectorOfSInt32:  response.PutCString ("format:vector-sint32;"); break;
3061         case eFormatVectorOfUInt32:  response.PutCString ("format:vector-uint32;"); break;
3062         case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
3063         case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
3064         default: break;
3065     };
3066 
3067     const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
3068     if (register_set_name)
3069     {
3070         response.PutCString ("set:");
3071         response.PutCString (register_set_name);
3072         response.PutChar (';');
3073     }
3074 
3075     if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3076         response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3077 
3078     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3079         response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3080 
3081     switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3082     {
3083         case LLDB_REGNUM_GENERIC_PC:     response.PutCString("generic:pc;"); break;
3084         case LLDB_REGNUM_GENERIC_SP:     response.PutCString("generic:sp;"); break;
3085         case LLDB_REGNUM_GENERIC_FP:     response.PutCString("generic:fp;"); break;
3086         case LLDB_REGNUM_GENERIC_RA:     response.PutCString("generic:ra;"); break;
3087         case LLDB_REGNUM_GENERIC_FLAGS:  response.PutCString("generic:flags;"); break;
3088         case LLDB_REGNUM_GENERIC_ARG1:   response.PutCString("generic:arg1;"); break;
3089         case LLDB_REGNUM_GENERIC_ARG2:   response.PutCString("generic:arg2;"); break;
3090         case LLDB_REGNUM_GENERIC_ARG3:   response.PutCString("generic:arg3;"); break;
3091         case LLDB_REGNUM_GENERIC_ARG4:   response.PutCString("generic:arg4;"); break;
3092         case LLDB_REGNUM_GENERIC_ARG5:   response.PutCString("generic:arg5;"); break;
3093         case LLDB_REGNUM_GENERIC_ARG6:   response.PutCString("generic:arg6;"); break;
3094         case LLDB_REGNUM_GENERIC_ARG7:   response.PutCString("generic:arg7;"); break;
3095         case LLDB_REGNUM_GENERIC_ARG8:   response.PutCString("generic:arg8;"); break;
3096         default: break;
3097     }
3098 
3099     if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3100     {
3101         response.PutCString ("container-regs:");
3102         int i = 0;
3103         for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3104         {
3105             if (i > 0)
3106                 response.PutChar (',');
3107             response.Printf ("%" PRIx32, *reg_num);
3108         }
3109         response.PutChar (';');
3110     }
3111 
3112     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3113     {
3114         response.PutCString ("invalidate-regs:");
3115         int i = 0;
3116         for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3117         {
3118             if (i > 0)
3119                 response.PutChar (',');
3120             response.Printf ("%" PRIx32, *reg_num);
3121         }
3122         response.PutChar (';');
3123     }
3124 
3125     return SendPacketNoLock(response.GetData(), response.GetSize());
3126 }
3127 
3128 GDBRemoteCommunication::PacketResult
3129 GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3130 {
3131     // Ensure we're llgs.
3132     if (!IsGdbServer())
3133         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3134 
3135     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3136 
3137     // Fail if we don't have a current process.
3138     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3139     {
3140         if (log)
3141             log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3142         return SendOKResponse ();
3143     }
3144 
3145     StreamGDBRemote response;
3146     response.PutChar ('m');
3147 
3148     if (log)
3149         log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3150 
3151     NativeThreadProtocolSP thread_sp;
3152     uint32_t thread_index;
3153     for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3154          thread_sp;
3155          ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3156     {
3157         if (log)
3158             log->Printf ("GDBRemoteCommunicationServer::%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);
3159         if (thread_index > 0)
3160             response.PutChar(',');
3161         response.Printf ("%" PRIx64, thread_sp->GetID ());
3162     }
3163 
3164     if (log)
3165         log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3166 
3167     return SendPacketNoLock(response.GetData(), response.GetSize());
3168 }
3169 
3170 GDBRemoteCommunication::PacketResult
3171 GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3172 {
3173     // Ensure we're llgs.
3174     if (!IsGdbServer())
3175         return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3176 
3177     // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3178     return SendPacketNoLock ("l", 1);
3179 }
3180 
3181 GDBRemoteCommunication::PacketResult
3182 GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3183 {
3184     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3185 
3186     // Ensure we're llgs.
3187     if (!IsGdbServer())
3188         return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3189 
3190     // Parse out the register number from the request.
3191     packet.SetFilePos (strlen("p"));
3192     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3193     if (reg_index == std::numeric_limits<uint32_t>::max ())
3194     {
3195         if (log)
3196             log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3197         return SendErrorResponse (0x15);
3198     }
3199 
3200     // Get the thread to use.
3201     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3202     if (!thread_sp)
3203     {
3204         if (log)
3205             log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3206         return SendErrorResponse (0x15);
3207     }
3208 
3209     // Get the thread's register context.
3210     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3211     if (!reg_context_sp)
3212     {
3213         if (log)
3214             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3215         return SendErrorResponse (0x15);
3216     }
3217 
3218     // Return the end of registers response if we've iterated one past the end of the register set.
3219     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
3220     {
3221         if (log)
3222             log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
3223         return SendErrorResponse (0x15);
3224     }
3225 
3226     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3227     if (!reg_info)
3228     {
3229         if (log)
3230             log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3231         return SendErrorResponse (0x15);
3232     }
3233 
3234     // Build the reginfos response.
3235     StreamGDBRemote response;
3236 
3237     // Retrieve the value
3238     RegisterValue reg_value;
3239     Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3240     if (error.Fail ())
3241     {
3242         if (log)
3243             log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3244         return SendErrorResponse (0x15);
3245     }
3246 
3247     const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3248     if (!data)
3249     {
3250         if (log)
3251             log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3252         return SendErrorResponse (0x15);
3253     }
3254 
3255     // FIXME flip as needed to get data in big/little endian format for this host.
3256     for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3257         response.PutHex8 (data[i]);
3258 
3259     return SendPacketNoLock (response.GetData (), response.GetSize ());
3260 }
3261 
3262 GDBRemoteCommunication::PacketResult
3263 GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3264 {
3265     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3266 
3267     // Ensure we're llgs.
3268     if (!IsGdbServer())
3269         return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3270 
3271     // Ensure there is more content.
3272     if (packet.GetBytesLeft () < 1)
3273         return SendIllFormedResponse (packet, "Empty P packet");
3274 
3275     // Parse out the register number from the request.
3276     packet.SetFilePos (strlen("P"));
3277     const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3278     if (reg_index == std::numeric_limits<uint32_t>::max ())
3279     {
3280         if (log)
3281             log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3282         return SendErrorResponse (0x29);
3283     }
3284 
3285     // Note debugserver would send an E30 here.
3286     if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3287         return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3288 
3289     // Get process architecture.
3290     ArchSpec process_arch;
3291     if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3292     {
3293         if (log)
3294             log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3295         return SendErrorResponse (0x49);
3296     }
3297 
3298     // Parse out the value.
3299     uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
3300     size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
3301 
3302     // Get the thread to use.
3303     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3304     if (!thread_sp)
3305     {
3306         if (log)
3307             log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3308         return SendErrorResponse (0x28);
3309     }
3310 
3311     // Get the thread's register context.
3312     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3313     if (!reg_context_sp)
3314     {
3315         if (log)
3316             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3317         return SendErrorResponse (0x15);
3318     }
3319 
3320     const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
3321     if (!reg_info)
3322     {
3323         if (log)
3324             log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3325         return SendErrorResponse (0x48);
3326     }
3327 
3328     // Return the end of registers response if we've iterated one past the end of the register set.
3329     if (reg_index >= reg_context_sp->GetUserRegisterCount ())
3330     {
3331         if (log)
3332             log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
3333         return SendErrorResponse (0x47);
3334     }
3335 
3336     if (reg_size != reg_info->byte_size)
3337     {
3338         return SendIllFormedResponse (packet, "P packet register size is incorrect");
3339     }
3340 
3341     // Build the reginfos response.
3342     StreamGDBRemote response;
3343 
3344     RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
3345     Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
3346     if (error.Fail ())
3347     {
3348         if (log)
3349             log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3350         return SendErrorResponse (0x32);
3351     }
3352 
3353     return SendOKResponse();
3354 }
3355 
3356 GDBRemoteCommunicationServer::PacketResult
3357 GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3358 {
3359     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3360 
3361     // Ensure we're llgs.
3362     if (!IsGdbServer())
3363         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3364 
3365     // Fail if we don't have a current process.
3366     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3367     {
3368         if (log)
3369             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3370         return SendErrorResponse (0x15);
3371     }
3372 
3373     // Parse out which variant of $H is requested.
3374     packet.SetFilePos (strlen("H"));
3375     if (packet.GetBytesLeft () < 1)
3376     {
3377         if (log)
3378             log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3379         return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3380     }
3381 
3382     const char h_variant = packet.GetChar ();
3383     switch (h_variant)
3384     {
3385         case 'g':
3386             break;
3387 
3388         case 'c':
3389             break;
3390 
3391         default:
3392             if (log)
3393                 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3394             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3395     }
3396 
3397     // Parse out the thread number.
3398     // FIXME return a parse success/fail value.  All values are valid here.
3399     const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3400 
3401     // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3402     if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3403     {
3404         NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3405         if (!thread_sp)
3406         {
3407             if (log)
3408                 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3409             return SendErrorResponse (0x15);
3410         }
3411     }
3412 
3413     // Now switch the given thread type.
3414     switch (h_variant)
3415     {
3416         case 'g':
3417             SetCurrentThreadID (tid);
3418             break;
3419 
3420         case 'c':
3421             SetContinueThreadID (tid);
3422             break;
3423 
3424         default:
3425             assert (false && "unsupported $H variant - shouldn't get here");
3426             return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3427     }
3428 
3429     return SendOKResponse();
3430 }
3431 
3432 GDBRemoteCommunicationServer::PacketResult
3433 GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3434 {
3435     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3436 
3437     // Ensure we're llgs.
3438     if (!IsGdbServer())
3439     {
3440         // Only supported on llgs
3441         return SendUnimplementedResponse ("");
3442     }
3443 
3444     // Fail if we don't have a current process.
3445     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3446     {
3447         if (log)
3448             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3449         return SendErrorResponse (0x15);
3450     }
3451 
3452     // Interrupt the process.
3453     Error error = m_debugged_process_sp->Interrupt ();
3454     if (error.Fail ())
3455     {
3456         if (log)
3457         {
3458             log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3459                          __FUNCTION__,
3460                          m_debugged_process_sp->GetID (),
3461                          error.AsCString ());
3462         }
3463         return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3464     }
3465 
3466     if (log)
3467         log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3468 
3469     // No response required from stop all.
3470     return PacketResult::Success;
3471 }
3472 
3473 GDBRemoteCommunicationServer::PacketResult
3474 GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3475 {
3476     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3477 
3478     // Ensure we're llgs.
3479     if (!IsGdbServer())
3480     {
3481         // Only supported on llgs
3482         return SendUnimplementedResponse ("");
3483     }
3484 
3485     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3486     {
3487         if (log)
3488             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3489         return SendErrorResponse (0x15);
3490     }
3491 
3492     // Parse out the memory address.
3493     packet.SetFilePos (strlen("m"));
3494     if (packet.GetBytesLeft() < 1)
3495         return SendIllFormedResponse(packet, "Too short m packet");
3496 
3497     // Read the address.  Punting on validation.
3498     // FIXME replace with Hex U64 read with no default value that fails on failed read.
3499     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3500 
3501     // Validate comma.
3502     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3503         return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3504 
3505     // Get # bytes to read.
3506     if (packet.GetBytesLeft() < 1)
3507         return SendIllFormedResponse(packet, "Length missing in m packet");
3508 
3509     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3510     if (byte_count == 0)
3511     {
3512         if (log)
3513             log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3514         return PacketResult::Success;
3515     }
3516 
3517     // Allocate the response buffer.
3518     std::string buf(byte_count, '\0');
3519     if (buf.empty())
3520         return SendErrorResponse (0x78);
3521 
3522 
3523     // Retrieve the process memory.
3524     lldb::addr_t bytes_read = 0;
3525     lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3526     if (error.Fail ())
3527     {
3528         if (log)
3529             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3530         return SendErrorResponse (0x08);
3531     }
3532 
3533     if (bytes_read == 0)
3534     {
3535         if (log)
3536             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, bytes_read, byte_count);
3537         return SendErrorResponse (0x08);
3538     }
3539 
3540     StreamGDBRemote response;
3541     for (lldb::addr_t i = 0; i < bytes_read; ++i)
3542         response.PutHex8(buf[i]);
3543 
3544     return SendPacketNoLock(response.GetData(), response.GetSize());
3545 }
3546 
3547 GDBRemoteCommunication::PacketResult
3548 GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3549 {
3550     packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3551     if (packet.GetU32(0))
3552         m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3553     else
3554         m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3555     return SendOKResponse ();
3556 }
3557 
3558 GDBRemoteCommunicationServer::PacketResult
3559 GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3560 {
3561     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3562 
3563     // Ensure we're llgs.
3564     if (!IsGdbServer())
3565     {
3566         // Only supported on llgs
3567         return SendUnimplementedResponse ("");
3568     }
3569 
3570     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3571     {
3572         if (log)
3573             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3574         return SendErrorResponse (0x15);
3575     }
3576 
3577     // Parse out the memory address.
3578     packet.SetFilePos (strlen("M"));
3579     if (packet.GetBytesLeft() < 1)
3580         return SendIllFormedResponse(packet, "Too short M packet");
3581 
3582     // Read the address.  Punting on validation.
3583     // FIXME replace with Hex U64 read with no default value that fails on failed read.
3584     const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3585 
3586     // Validate comma.
3587     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3588         return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3589 
3590     // Get # bytes to read.
3591     if (packet.GetBytesLeft() < 1)
3592         return SendIllFormedResponse(packet, "Length missing in M packet");
3593 
3594     const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3595     if (byte_count == 0)
3596     {
3597         if (log)
3598             log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3599         return PacketResult::Success;
3600     }
3601 
3602     // Validate colon.
3603     if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3604         return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3605 
3606     // Allocate the conversion buffer.
3607     std::vector<uint8_t> buf(byte_count, 0);
3608     if (buf.empty())
3609         return SendErrorResponse (0x78);
3610 
3611     // Convert the hex memory write contents to bytes.
3612     StreamGDBRemote response;
3613     const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3614     if (convert_count != byte_count)
3615     {
3616         if (log)
3617             log->Printf ("GDBRemoteCommunicationServer::%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);
3618         return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3619     }
3620 
3621     // Write the process memory.
3622     lldb::addr_t bytes_written = 0;
3623     lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3624     if (error.Fail ())
3625     {
3626         if (log)
3627             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3628         return SendErrorResponse (0x09);
3629     }
3630 
3631     if (bytes_written == 0)
3632     {
3633         if (log)
3634             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, bytes_written, byte_count);
3635         return SendErrorResponse (0x09);
3636     }
3637 
3638     return SendOKResponse ();
3639 }
3640 
3641 GDBRemoteCommunicationServer::PacketResult
3642 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3643 {
3644     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3645 
3646     // We don't support if we're not llgs.
3647     if (!IsGdbServer())
3648         return SendUnimplementedResponse ("");
3649 
3650     // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3651     // request, but we're not guaranteed to be attached to a process.  For now we'll assume the
3652     // client only asks this when a process is being debugged.
3653 
3654     // Ensure we have a process running; otherwise, we can't figure this out
3655     // since we won't have a NativeProcessProtocol.
3656     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3657     {
3658         if (log)
3659             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3660         return SendErrorResponse (0x15);
3661     }
3662 
3663     // Test if we can get any region back when asking for the region around NULL.
3664     MemoryRegionInfo region_info;
3665     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3666     if (error.Fail ())
3667     {
3668         // We don't support memory region info collection for this NativeProcessProtocol.
3669         return SendUnimplementedResponse ("");
3670     }
3671 
3672     return SendOKResponse();
3673 }
3674 
3675 GDBRemoteCommunicationServer::PacketResult
3676 GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3677 {
3678     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3679 
3680     // We don't support if we're not llgs.
3681     if (!IsGdbServer())
3682         return SendUnimplementedResponse ("");
3683 
3684     // Ensure we have a process.
3685     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3686     {
3687         if (log)
3688             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3689         return SendErrorResponse (0x15);
3690     }
3691 
3692     // Parse out the memory address.
3693     packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3694     if (packet.GetBytesLeft() < 1)
3695         return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3696 
3697     // Read the address.  Punting on validation.
3698     const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3699 
3700     StreamGDBRemote response;
3701 
3702     // Get the memory region info for the target address.
3703     MemoryRegionInfo region_info;
3704     const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3705     if (error.Fail ())
3706     {
3707         // Return the error message.
3708 
3709         response.PutCString ("error:");
3710         response.PutCStringAsRawHex8 (error.AsCString ());
3711         response.PutChar (';');
3712     }
3713     else
3714     {
3715         // Range start and size.
3716         response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3717 
3718         // Permissions.
3719         if (region_info.GetReadable () ||
3720             region_info.GetWritable () ||
3721             region_info.GetExecutable ())
3722         {
3723             // Write permissions info.
3724             response.PutCString ("permissions:");
3725 
3726             if (region_info.GetReadable ())
3727                 response.PutChar ('r');
3728             if (region_info.GetWritable ())
3729                 response.PutChar('w');
3730             if (region_info.GetExecutable())
3731                 response.PutChar ('x');
3732 
3733             response.PutChar (';');
3734         }
3735     }
3736 
3737     return SendPacketNoLock(response.GetData(), response.GetSize());
3738 }
3739 
3740 GDBRemoteCommunicationServer::PacketResult
3741 GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3742 {
3743     // We don't support if we're not llgs.
3744     if (!IsGdbServer())
3745         return SendUnimplementedResponse ("");
3746 
3747     // Ensure we have a process.
3748     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3749     {
3750         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3751         if (log)
3752             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3753         return SendErrorResponse (0x15);
3754     }
3755 
3756     // Parse out software or hardware breakpoint or watchpoint requested.
3757     packet.SetFilePos (strlen("Z"));
3758     if (packet.GetBytesLeft() < 1)
3759         return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3760 
3761     bool want_breakpoint = true;
3762     bool want_hardware = false;
3763 
3764     const GDBStoppointType stoppoint_type =
3765         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
3766     switch (stoppoint_type)
3767     {
3768         case eBreakpointSoftware:
3769             want_hardware = false; want_breakpoint = true;  break;
3770         case eBreakpointHardware:
3771             want_hardware = true;  want_breakpoint = true;  break;
3772         case eWatchpointWrite:
3773             want_hardware = true;  want_breakpoint = false; break;
3774         case eWatchpointRead:
3775             want_hardware = true;  want_breakpoint = false; break;
3776         case eWatchpointReadWrite:
3777             want_hardware = true;  want_breakpoint = false; break;
3778         case eStoppointInvalid:
3779             return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3780 
3781     }
3782 
3783     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3784         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
3785 
3786     // Parse out the stoppoint address.
3787     if (packet.GetBytesLeft() < 1)
3788         return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3789     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3790 
3791     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3792         return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3793 
3794     // Parse out the stoppoint size (i.e. size hint for opcode size).
3795     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3796     if (size == std::numeric_limits<uint32_t>::max ())
3797         return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
3798 
3799     if (want_breakpoint)
3800     {
3801         // Try to set the breakpoint.
3802         const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
3803         if (error.Success ())
3804             return SendOKResponse ();
3805         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3806         if (log)
3807             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64
3808                     " failed to set breakpoint: %s",
3809                     __FUNCTION__,
3810                     m_debugged_process_sp->GetID (),
3811                     error.AsCString ());
3812         return SendErrorResponse (0x09);
3813     }
3814     else
3815     {
3816         uint32_t watch_flags =
3817             stoppoint_type == eWatchpointWrite
3818             ? watch_flags = 0x1  // Write
3819             : watch_flags = 0x3; // ReadWrite
3820 
3821         // Try to set the watchpoint.
3822         const Error error = m_debugged_process_sp->SetWatchpoint (
3823                 addr, size, watch_flags, want_hardware);
3824         if (error.Success ())
3825             return SendOKResponse ();
3826         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
3827         if (log)
3828             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64
3829                     " failed to set watchpoint: %s",
3830                     __FUNCTION__,
3831                     m_debugged_process_sp->GetID (),
3832                     error.AsCString ());
3833         return SendErrorResponse (0x09);
3834     }
3835 }
3836 
3837 GDBRemoteCommunicationServer::PacketResult
3838 GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3839 {
3840     // We don't support if we're not llgs.
3841     if (!IsGdbServer())
3842         return SendUnimplementedResponse ("");
3843 
3844     // Ensure we have a process.
3845     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3846     {
3847         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3848         if (log)
3849             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3850         return SendErrorResponse (0x15);
3851     }
3852 
3853     // Parse out software or hardware breakpoint or watchpoint requested.
3854     packet.SetFilePos (strlen("z"));
3855     if (packet.GetBytesLeft() < 1)
3856         return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3857 
3858     bool want_breakpoint = true;
3859 
3860     const GDBStoppointType stoppoint_type =
3861         GDBStoppointType(packet.GetS32 (eStoppointInvalid));
3862     switch (stoppoint_type)
3863     {
3864         case eBreakpointHardware:  want_breakpoint = true;  break;
3865         case eBreakpointSoftware:  want_breakpoint = true;  break;
3866         case eWatchpointWrite:     want_breakpoint = false; break;
3867         case eWatchpointRead:      want_breakpoint = false; break;
3868         case eWatchpointReadWrite: want_breakpoint = false; break;
3869         default:
3870             return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3871 
3872     }
3873 
3874     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3875         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
3876 
3877     // Parse out the stoppoint address.
3878     if (packet.GetBytesLeft() < 1)
3879         return SendIllFormedResponse(packet, "Too short z packet, missing address");
3880     const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
3881 
3882     if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3883         return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3884 
3885     /*
3886     // Parse out the stoppoint size (i.e. size hint for opcode size).
3887     const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3888     if (size == std::numeric_limits<uint32_t>::max ())
3889         return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
3890     */
3891 
3892     if (want_breakpoint)
3893     {
3894         // Try to clear the breakpoint.
3895         const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
3896         if (error.Success ())
3897             return SendOKResponse ();
3898         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3899         if (log)
3900             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64
3901                     " failed to remove breakpoint: %s",
3902                     __FUNCTION__,
3903                     m_debugged_process_sp->GetID (),
3904                     error.AsCString ());
3905         return SendErrorResponse (0x09);
3906     }
3907     else
3908     {
3909         // Try to clear the watchpoint.
3910         const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
3911         if (error.Success ())
3912             return SendOKResponse ();
3913         Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
3914         if (log)
3915             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64
3916                     " failed to remove watchpoint: %s",
3917                     __FUNCTION__,
3918                     m_debugged_process_sp->GetID (),
3919                     error.AsCString ());
3920         return SendErrorResponse (0x09);
3921     }
3922 }
3923 
3924 GDBRemoteCommunicationServer::PacketResult
3925 GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3926 {
3927     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3928 
3929     // We don't support if we're not llgs.
3930     if (!IsGdbServer())
3931         return SendUnimplementedResponse ("");
3932 
3933     // Ensure we have a process.
3934     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3935     {
3936         if (log)
3937             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3938         return SendErrorResponse (0x32);
3939     }
3940 
3941     // We first try to use a continue thread id.  If any one or any all set, use the current thread.
3942     // Bail out if we don't have a thread id.
3943     lldb::tid_t tid = GetContinueThreadID ();
3944     if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3945         tid = GetCurrentThreadID ();
3946     if (tid == LLDB_INVALID_THREAD_ID)
3947         return SendErrorResponse (0x33);
3948 
3949     // Double check that we have such a thread.
3950     // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3951     NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3952     if (!thread_sp || thread_sp->GetID () != tid)
3953         return SendErrorResponse (0x33);
3954 
3955     // Create the step action for the given thread.
3956     lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3957 
3958     // Setup the actions list.
3959     lldb_private::ResumeActionList actions;
3960     actions.Append (action);
3961 
3962     // All other threads stop while we're single stepping a thread.
3963     actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3964     Error error = m_debugged_process_sp->Resume (actions);
3965     if (error.Fail ())
3966     {
3967         if (log)
3968             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3969         return SendErrorResponse(0x49);
3970     }
3971 
3972     // No response here - the stop or exit will come from the resulting action.
3973     return PacketResult::Success;
3974 }
3975 
3976 GDBRemoteCommunicationServer::PacketResult
3977 GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3978 {
3979     StreamGDBRemote response;
3980 
3981     // Features common to lldb-platform and llgs.
3982     uint32_t max_packet_size = 128 * 1024;  // 128KBytes is a reasonable max packet size--debugger can always use less
3983     response.Printf ("PacketSize=%x", max_packet_size);
3984 
3985     response.PutCString (";QStartNoAckMode+");
3986     response.PutCString (";QThreadSuffixSupported+");
3987     response.PutCString (";QListThreadsInStopReply+");
3988 #if defined(__linux__)
3989     response.PutCString (";qXfer:auxv:read+");
3990 #endif
3991 
3992     return SendPacketNoLock(response.GetData(), response.GetSize());
3993 }
3994 
3995 GDBRemoteCommunicationServer::PacketResult
3996 GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3997 {
3998     m_thread_suffix_supported = true;
3999     return SendOKResponse();
4000 }
4001 
4002 GDBRemoteCommunicationServer::PacketResult
4003 GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
4004 {
4005     m_list_threads_in_stop_reply = true;
4006     return SendOKResponse();
4007 }
4008 
4009 GDBRemoteCommunicationServer::PacketResult
4010 GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
4011 {
4012     // We don't support if we're not llgs.
4013     if (!IsGdbServer())
4014         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4015 
4016     // *BSD impls should be able to do this too.
4017 #if defined(__linux__)
4018     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4019 
4020     // Parse out the offset.
4021     packet.SetFilePos (strlen("qXfer:auxv:read::"));
4022     if (packet.GetBytesLeft () < 1)
4023         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
4024 
4025     const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
4026     if (auxv_offset == std::numeric_limits<uint64_t>::max ())
4027         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
4028 
4029     // Parse out comma.
4030     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
4031         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
4032 
4033     // Parse out the length.
4034     const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
4035     if (auxv_length == std::numeric_limits<uint64_t>::max ())
4036         return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
4037 
4038     // Grab the auxv data if we need it.
4039     if (!m_active_auxv_buffer_sp)
4040     {
4041         // Make sure we have a valid process.
4042         if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
4043         {
4044             if (log)
4045                 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
4046             return SendErrorResponse (0x10);
4047         }
4048 
4049         // Grab the auxv data.
4050         m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
4051         if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () ==  0)
4052         {
4053             // Hmm, no auxv data, call that an error.
4054             if (log)
4055                 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
4056             m_active_auxv_buffer_sp.reset ();
4057             return SendErrorResponse (0x11);
4058         }
4059     }
4060 
4061     // FIXME find out if/how I lock the stream here.
4062 
4063     StreamGDBRemote response;
4064     bool done_with_buffer = false;
4065 
4066     if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
4067     {
4068         // We have nothing left to send.  Mark the buffer as complete.
4069         response.PutChar ('l');
4070         done_with_buffer = true;
4071     }
4072     else
4073     {
4074         // Figure out how many bytes are available starting at the given offset.
4075         const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
4076 
4077         // Figure out how many bytes we're going to read.
4078         const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
4079 
4080         // Mark the response type according to whether we're reading the remainder of the auxv data.
4081         if (bytes_to_read >= bytes_remaining)
4082         {
4083             // There will be nothing left to read after this
4084             response.PutChar ('l');
4085             done_with_buffer = true;
4086         }
4087         else
4088         {
4089             // There will still be bytes to read after this request.
4090             response.PutChar ('m');
4091         }
4092 
4093         // Now write the data in encoded binary form.
4094         response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
4095     }
4096 
4097     if (done_with_buffer)
4098         m_active_auxv_buffer_sp.reset ();
4099 
4100     return SendPacketNoLock(response.GetData(), response.GetSize());
4101 #else
4102     return SendUnimplementedResponse ("not implemented on this platform");
4103 #endif
4104 }
4105 
4106 GDBRemoteCommunicationServer::PacketResult
4107 GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4108 {
4109     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4110 
4111     // We don't support if we're not llgs.
4112     if (!IsGdbServer())
4113         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4114 
4115     // Move past packet name.
4116     packet.SetFilePos (strlen ("QSaveRegisterState"));
4117 
4118     // Get the thread to use.
4119     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4120     if (!thread_sp)
4121     {
4122         if (m_thread_suffix_supported)
4123             return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4124         else
4125             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4126     }
4127 
4128     // Grab the register context for the thread.
4129     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4130     if (!reg_context_sp)
4131     {
4132         if (log)
4133             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4134         return SendErrorResponse (0x15);
4135     }
4136 
4137     // Save registers to a buffer.
4138     DataBufferSP register_data_sp;
4139     Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4140     if (error.Fail ())
4141     {
4142         if (log)
4143             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4144         return SendErrorResponse (0x75);
4145     }
4146 
4147     // Allocate a new save id.
4148     const uint32_t save_id = GetNextSavedRegistersID ();
4149     assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4150 
4151     // Save the register data buffer under the save id.
4152     {
4153         Mutex::Locker locker (m_saved_registers_mutex);
4154         m_saved_registers_map[save_id] = register_data_sp;
4155     }
4156 
4157     // Write the response.
4158     StreamGDBRemote response;
4159     response.Printf ("%" PRIu32, save_id);
4160     return SendPacketNoLock(response.GetData(), response.GetSize());
4161 }
4162 
4163 GDBRemoteCommunicationServer::PacketResult
4164 GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4165 {
4166     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4167 
4168     // We don't support if we're not llgs.
4169     if (!IsGdbServer())
4170         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4171 
4172     // Parse out save id.
4173     packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4174     if (packet.GetBytesLeft () < 1)
4175         return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4176 
4177     const uint32_t save_id = packet.GetU32 (0);
4178     if (save_id == 0)
4179     {
4180         if (log)
4181             log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4182         return SendErrorResponse (0x76);
4183     }
4184 
4185     // Get the thread to use.
4186     NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4187     if (!thread_sp)
4188     {
4189         if (m_thread_suffix_supported)
4190             return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4191         else
4192             return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4193     }
4194 
4195     // Grab the register context for the thread.
4196     NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4197     if (!reg_context_sp)
4198     {
4199         if (log)
4200             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4201         return SendErrorResponse (0x15);
4202     }
4203 
4204     // Retrieve register state buffer, then remove from the list.
4205     DataBufferSP register_data_sp;
4206     {
4207         Mutex::Locker locker (m_saved_registers_mutex);
4208 
4209         // Find the register set buffer for the given save id.
4210         auto it = m_saved_registers_map.find (save_id);
4211         if (it == m_saved_registers_map.end ())
4212         {
4213             if (log)
4214                 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
4215             return SendErrorResponse (0x77);
4216         }
4217         register_data_sp = it->second;
4218 
4219         // Remove it from the map.
4220         m_saved_registers_map.erase (it);
4221     }
4222 
4223     Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4224     if (error.Fail ())
4225     {
4226         if (log)
4227             log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4228         return SendErrorResponse (0x77);
4229     }
4230 
4231     return SendOKResponse();
4232 }
4233 
4234 GDBRemoteCommunicationServer::PacketResult
4235 GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4236 {
4237     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4238 
4239     // We don't support if we're not llgs.
4240     if (!IsGdbServer())
4241         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4242 
4243     // Consume the ';' after vAttach.
4244     packet.SetFilePos (strlen ("vAttach"));
4245     if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4246         return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4247 
4248     // Grab the PID to which we will attach (assume hex encoding).
4249     lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4250     if (pid == LLDB_INVALID_PROCESS_ID)
4251         return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4252 
4253     // Attempt to attach.
4254     if (log)
4255         log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4256 
4257     Error error = AttachToProcess (pid);
4258 
4259     if (error.Fail ())
4260     {
4261         if (log)
4262             log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4263         return SendErrorResponse (0x01);
4264     }
4265 
4266     // Notify we attached by sending a stop packet.
4267     return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4268 }
4269 
4270 GDBRemoteCommunicationServer::PacketResult
4271 GDBRemoteCommunicationServer::Handle_D (StringExtractorGDBRemote &packet)
4272 {
4273     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
4274 
4275     // We don't support if we're not llgs.
4276     if (!IsGdbServer())
4277         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4278 
4279     // Scope for mutex locker.
4280     Mutex::Locker locker (m_spawned_pids_mutex);
4281 
4282     // Fail if we don't have a current process.
4283     if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
4284     {
4285         if (log)
4286             log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
4287         return SendErrorResponse (0x15);
4288     }
4289 
4290     if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end())
4291     {
4292         if (log)
4293             log->Printf ("GDBRemoteCommunicationServer::%s failed to find PID %" PRIu64 " in spawned pids list",
4294                          __FUNCTION__, m_debugged_process_sp->GetID ());
4295         return SendErrorResponse (0x1);
4296     }
4297 
4298     lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
4299 
4300     // Consume the ';' after D.
4301     packet.SetFilePos (1);
4302     if (packet.GetBytesLeft ())
4303     {
4304         if (packet.GetChar () != ';')
4305             return SendIllFormedResponse (packet, "D missing expected ';'");
4306 
4307         // Grab the PID from which we will detach (assume hex encoding).
4308         pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4309         if (pid == LLDB_INVALID_PROCESS_ID)
4310             return SendIllFormedResponse (packet, "D failed to parse the process id");
4311     }
4312 
4313     if (pid != LLDB_INVALID_PROCESS_ID &&
4314         m_debugged_process_sp->GetID () != pid)
4315     {
4316         return SendIllFormedResponse (packet, "Invalid pid");
4317     }
4318 
4319     if (m_stdio_communication.IsConnected ())
4320     {
4321         m_stdio_communication.StopReadThread ();
4322     }
4323 
4324     const Error error = m_debugged_process_sp->Detach ();
4325     if (error.Fail ())
4326     {
4327         if (log)
4328             log->Printf ("GDBRemoteCommunicationServer::%s failed to detach from pid %" PRIu64 ": %s\n",
4329                          __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4330         return SendErrorResponse (0x01);
4331     }
4332 
4333     m_spawned_pids.erase (m_debugged_process_sp->GetID ());
4334     return SendOKResponse ();
4335 }
4336 
4337 GDBRemoteCommunicationServer::PacketResult
4338 GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
4339 {
4340     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4341 
4342     // We don't support if we're not llgs.
4343     if (!IsGdbServer())
4344         return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4345 
4346     packet.SetFilePos (strlen("qThreadStopInfo"));
4347     const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
4348     if (tid == LLDB_INVALID_THREAD_ID)
4349     {
4350         if (log)
4351             log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
4352         return SendErrorResponse (0x15);
4353     }
4354     return SendStopReplyPacketForThread (tid);
4355 }
4356 
4357 GDBRemoteCommunicationServer::PacketResult
4358 GDBRemoteCommunicationServer::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
4359 {
4360     // Only the gdb server handles this.
4361     if (!IsGdbServer ())
4362         return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
4363 
4364     // Fail if we don't have a current process.
4365     if (!m_debugged_process_sp ||
4366             m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4367         return SendErrorResponse (68);
4368 
4369     packet.SetFilePos(strlen("qWatchpointSupportInfo"));
4370     if (packet.GetBytesLeft() == 0)
4371         return SendOKResponse();
4372     if (packet.GetChar() != ':')
4373         return SendErrorResponse(67);
4374 
4375     uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
4376     StreamGDBRemote response;
4377     response.Printf ("num:%d;", num);
4378     return SendPacketNoLock(response.GetData(), response.GetSize());
4379 }
4380 
4381 void
4382 GDBRemoteCommunicationServer::FlushInferiorOutput ()
4383 {
4384     // If we're not monitoring an inferior's terminal, ignore this.
4385     if (!m_stdio_communication.IsConnected())
4386         return;
4387 
4388     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4389     if (log)
4390         log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4391 
4392     // FIXME implement a timeout on the join.
4393     m_stdio_communication.JoinReadThread();
4394 }
4395 
4396 void
4397 GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4398 {
4399     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4400 
4401     // Tell the stdio connection to shut down.
4402     if (m_stdio_communication.IsConnected())
4403     {
4404         auto connection = m_stdio_communication.GetConnection();
4405         if (connection)
4406         {
4407             Error error;
4408             connection->Disconnect (&error);
4409 
4410             if (error.Success ())
4411             {
4412                 if (log)
4413                     log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4414             }
4415             else
4416             {
4417                 if (log)
4418                     log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4419             }
4420         }
4421     }
4422 }
4423 
4424 
4425 lldb_private::NativeThreadProtocolSP
4426 GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4427 {
4428     NativeThreadProtocolSP thread_sp;
4429 
4430     // We have no thread if we don't have a process.
4431     if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4432         return thread_sp;
4433 
4434     // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4435     // Use the current thread in that case.
4436     if (!m_thread_suffix_supported)
4437     {
4438         const lldb::tid_t current_tid = GetCurrentThreadID ();
4439         if (current_tid == LLDB_INVALID_THREAD_ID)
4440             return thread_sp;
4441         else if (current_tid == 0)
4442         {
4443             // Pick a thread.
4444             return m_debugged_process_sp->GetThreadAtIndex (0);
4445         }
4446         else
4447             return m_debugged_process_sp->GetThreadByID (current_tid);
4448     }
4449 
4450     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4451 
4452     // Parse out the ';'.
4453     if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4454     {
4455         if (log)
4456             log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4457         return thread_sp;
4458     }
4459 
4460     if (!packet.GetBytesLeft ())
4461         return thread_sp;
4462 
4463     // Parse out thread: portion.
4464     if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4465     {
4466         if (log)
4467             log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4468         return thread_sp;
4469     }
4470     packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4471     const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4472     if (tid != 0)
4473         return m_debugged_process_sp->GetThreadByID (tid);
4474 
4475     return thread_sp;
4476 }
4477 
4478 lldb::tid_t
4479 GDBRemoteCommunicationServer::GetCurrentThreadID () const
4480 {
4481     if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4482     {
4483         // Use whatever the debug process says is the current thread id
4484         // since the protocol either didn't specify or specified we want
4485         // any/all threads marked as the current thread.
4486         if (!m_debugged_process_sp)
4487             return LLDB_INVALID_THREAD_ID;
4488         return m_debugged_process_sp->GetCurrentThreadID ();
4489     }
4490     // Use the specific current thread id set by the gdb remote protocol.
4491     return m_current_tid;
4492 }
4493 
4494 uint32_t
4495 GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4496 {
4497     Mutex::Locker locker (m_saved_registers_mutex);
4498     return m_next_saved_registers_id++;
4499 }
4500 
4501 void
4502 GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4503 {
4504     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4505     if (log)
4506         log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4507 
4508     // Clear any auxv cached data.
4509     // *BSD impls should be able to do this too.
4510 #if defined(__linux__)
4511     if (log)
4512         log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4513                      __FUNCTION__,
4514                      m_active_auxv_buffer_sp ? "was set" : "was not set");
4515     m_active_auxv_buffer_sp.reset ();
4516 #endif
4517 }
4518