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