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