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