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