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