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