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