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