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