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