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