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