xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp (revision d494b29596af5b7fd9a946e6d084bc7b32987c82)
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 "GDBRemoteCommunicationServer.h"
13 #include "lldb/Core/StreamGDBRemote.h"
14 
15 // C Includes
16 // C++ Includes
17 // Other libraries and framework includes
18 #include "llvm/ADT/Triple.h"
19 #include "lldb/Interpreter/Args.h"
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/Endian.h"
25 #include "lldb/Host/File.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Host/TimeValue.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Target/Process.h"
30 
31 // Project includes
32 #include "Utility/StringExtractorGDBRemote.h"
33 #include "ProcessGDBRemote.h"
34 #include "ProcessGDBRemoteLog.h"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 //----------------------------------------------------------------------
40 // GDBRemoteCommunicationServer constructor
41 //----------------------------------------------------------------------
42 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
43     GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
44     m_platform_sp (Platform::GetDefaultPlatform ()),
45     m_async_thread (LLDB_INVALID_HOST_THREAD),
46     m_process_launch_info (),
47     m_process_launch_error (),
48     m_spawned_pids (),
49     m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
50     m_proc_infos (),
51     m_proc_infos_index (0),
52     m_port_map (),
53     m_port_offset(0)
54 {
55 }
56 
57 GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
58                                                            const lldb::PlatformSP& platform_sp) :
59     GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
60     m_platform_sp (platform_sp),
61     m_async_thread (LLDB_INVALID_HOST_THREAD),
62     m_process_launch_info (),
63     m_process_launch_error (),
64     m_spawned_pids (),
65     m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
66     m_proc_infos (),
67     m_proc_infos_index (0),
68     m_port_map (),
69     m_port_offset(0)
70 {
71     assert(platform_sp);
72 }
73 
74 //----------------------------------------------------------------------
75 // Destructor
76 //----------------------------------------------------------------------
77 GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
78 {
79 }
80 
81 
82 //void *
83 //GDBRemoteCommunicationServer::AsyncThread (void *arg)
84 //{
85 //    GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer*) arg;
86 //
87 //    Log *log;// (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
88 //    if (log)
89 //        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
90 //
91 //    StringExtractorGDBRemote packet;
92 //
93 //    while ()
94 //    {
95 //        if (packet.
96 //    }
97 //
98 //    if (log)
99 //        log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
100 //
101 //    process->m_async_thread = LLDB_INVALID_HOST_THREAD;
102 //    return NULL;
103 //}
104 //
105 bool
106 GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
107                                                         Error &error,
108                                                         bool &interrupt,
109                                                         bool &quit)
110 {
111     StringExtractorGDBRemote packet;
112     PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
113     if (packet_result == PacketResult::Success)
114     {
115         const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
116         switch (packet_type)
117         {
118         case StringExtractorGDBRemote::eServerPacketType_nack:
119         case StringExtractorGDBRemote::eServerPacketType_ack:
120             break;
121 
122         case StringExtractorGDBRemote::eServerPacketType_invalid:
123             error.SetErrorString("invalid packet");
124             quit = true;
125             break;
126 
127         case StringExtractorGDBRemote::eServerPacketType_interrupt:
128             error.SetErrorString("interrupt received");
129             interrupt = true;
130             break;
131 
132         default:
133         case StringExtractorGDBRemote::eServerPacketType_unimplemented:
134             packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
135             break;
136 
137         case StringExtractorGDBRemote::eServerPacketType_A:
138             packet_result = Handle_A (packet);
139             break;
140 
141         case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
142             packet_result = Handle_qfProcessInfo (packet);
143             break;
144 
145         case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
146             packet_result = Handle_qsProcessInfo (packet);
147             break;
148 
149         case StringExtractorGDBRemote::eServerPacketType_qC:
150             packet_result = Handle_qC (packet);
151             break;
152 
153         case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
154             packet_result = Handle_qHostInfo (packet);
155             break;
156 
157         case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
158             packet_result = Handle_qLaunchGDBServer (packet);
159             break;
160 
161         case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
162             packet_result = Handle_qKillSpawnedProcess (packet);
163             break;
164 
165         case StringExtractorGDBRemote::eServerPacketType_k:
166             packet_result = Handle_k (packet);
167             break;
168 
169         case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
170             packet_result = Handle_qLaunchSuccess (packet);
171             break;
172 
173         case StringExtractorGDBRemote::eServerPacketType_qGroupName:
174             packet_result = Handle_qGroupName (packet);
175             break;
176 
177         case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
178             packet_result = Handle_qProcessInfoPID (packet);
179             break;
180 
181         case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
182             packet_result = Handle_qSpeedTest (packet);
183             break;
184 
185         case StringExtractorGDBRemote::eServerPacketType_qUserName:
186             packet_result = Handle_qUserName (packet);
187             break;
188 
189         case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
190             packet_result = Handle_qGetWorkingDir(packet);
191             break;
192 
193         case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
194             packet_result = Handle_QEnvironment (packet);
195             break;
196 
197         case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
198             packet_result = Handle_QLaunchArch (packet);
199             break;
200 
201         case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
202             packet_result = Handle_QSetDisableASLR (packet);
203             break;
204 
205         case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
206             packet_result = Handle_QSetSTDIN (packet);
207             break;
208 
209         case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
210             packet_result = Handle_QSetSTDOUT (packet);
211             break;
212 
213         case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
214             packet_result = Handle_QSetSTDERR (packet);
215             break;
216 
217         case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
218             packet_result = Handle_QSetWorkingDir (packet);
219             break;
220 
221         case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
222             packet_result = Handle_QStartNoAckMode (packet);
223             break;
224 
225         case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
226             packet_result = Handle_qPlatform_mkdir (packet);
227             break;
228 
229         case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
230             packet_result = Handle_qPlatform_chmod (packet);
231             break;
232 
233         case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
234             packet_result = Handle_qPlatform_shell (packet);
235             break;
236 
237         case StringExtractorGDBRemote::eServerPacketType_vFile_open:
238             packet_result = Handle_vFile_Open (packet);
239             break;
240 
241         case StringExtractorGDBRemote::eServerPacketType_vFile_close:
242             packet_result = Handle_vFile_Close (packet);
243             break;
244 
245         case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
246             packet_result = Handle_vFile_pRead (packet);
247             break;
248 
249         case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
250             packet_result = Handle_vFile_pWrite (packet);
251             break;
252 
253         case StringExtractorGDBRemote::eServerPacketType_vFile_size:
254             packet_result = Handle_vFile_Size (packet);
255             break;
256 
257         case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
258             packet_result = Handle_vFile_Mode (packet);
259             break;
260 
261         case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
262             packet_result = Handle_vFile_Exists (packet);
263             break;
264 
265         case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
266             packet_result = Handle_vFile_Stat (packet);
267             break;
268 
269         case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
270             packet_result = Handle_vFile_MD5 (packet);
271             break;
272 
273         case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
274             packet_result = Handle_vFile_symlink (packet);
275             break;
276 
277         case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
278             packet_result = Handle_vFile_unlink (packet);
279             break;
280         }
281     }
282     else
283     {
284         if (!IsConnected())
285         {
286             error.SetErrorString("lost connection");
287             quit = true;
288         }
289         else
290         {
291             error.SetErrorString("timeout");
292         }
293     }
294     return packet_result == PacketResult::Success;
295 }
296 
297 lldb_private::Error
298 GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
299 {
300     if ((argc < 1) || !args || !args[0] || !args[0][0])
301         return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
302 
303     m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
304     return lldb_private::Error ();
305 }
306 
307 lldb_private::Error
308 GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
309 {
310     m_process_launch_info.GetFlags ().Set (launch_flags);
311     return lldb_private::Error ();
312 }
313 
314 lldb_private::Error
315 GDBRemoteCommunicationServer::LaunchProcess ()
316 {
317     if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
318         return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
319 
320     // specify the process monitor if not already set.  This should
321     // generally be what happens since we need to reap started
322     // processes.
323     if (!m_process_launch_info.GetMonitorProcessCallback ())
324         m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
325 
326     lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
327     if (!error.Success ())
328     {
329         fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
330         return error;
331     }
332 
333     printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID());
334 
335     // add to list of spawned processes.  On an lldb-gdbserver, we
336     // would expect there to be only one.
337     lldb::pid_t pid;
338     if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
339     {
340         Mutex::Locker locker (m_spawned_pids_mutex);
341         m_spawned_pids.insert(pid);
342     }
343 
344     return error;
345 }
346 
347 GDBRemoteCommunication::PacketResult
348 GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
349 {
350     // TODO: Log the packet we aren't handling...
351     return SendPacketNoLock ("", 0);
352 }
353 
354 GDBRemoteCommunication::PacketResult
355 GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
356 {
357     char packet[16];
358     int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
359     assert (packet_len < (int)sizeof(packet));
360     return SendPacketNoLock (packet, packet_len);
361 }
362 
363 
364 GDBRemoteCommunication::PacketResult
365 GDBRemoteCommunicationServer::SendOKResponse ()
366 {
367     return SendPacketNoLock ("OK", 2);
368 }
369 
370 bool
371 GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
372 {
373     return GetAck() == PacketResult::Success;
374 }
375 
376 GDBRemoteCommunication::PacketResult
377 GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
378 {
379     StreamString response;
380 
381     // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
382 
383     ArchSpec host_arch (Host::GetArchitecture ());
384     const llvm::Triple &host_triple = host_arch.GetTriple();
385     response.PutCString("triple:");
386     response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
387     response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
388 
389     const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
390     if (distribution_id)
391     {
392         response.PutCString("distribution_id:");
393         response.PutCStringAsRawHex8(distribution_id);
394         response.PutCString(";");
395     }
396 
397     uint32_t cpu = host_arch.GetMachOCPUType();
398     uint32_t sub = host_arch.GetMachOCPUSubType();
399     if (cpu != LLDB_INVALID_CPUTYPE)
400         response.Printf ("cputype:%u;", cpu);
401     if (sub != LLDB_INVALID_CPUTYPE)
402         response.Printf ("cpusubtype:%u;", sub);
403 
404     if (cpu == ArchSpec::kCore_arm_any)
405         response.Printf("watchpoint_exceptions_received:before;");   // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
406     else
407         response.Printf("watchpoint_exceptions_received:after;");
408 
409     switch (lldb::endian::InlHostByteOrder())
410     {
411     case eByteOrderBig:     response.PutCString ("endian:big;"); break;
412     case eByteOrderLittle:  response.PutCString ("endian:little;"); break;
413     case eByteOrderPDP:     response.PutCString ("endian:pdp;"); break;
414     default:                response.PutCString ("endian:unknown;"); break;
415     }
416 
417     uint32_t major = UINT32_MAX;
418     uint32_t minor = UINT32_MAX;
419     uint32_t update = UINT32_MAX;
420     if (Host::GetOSVersion (major, minor, update))
421     {
422         if (major != UINT32_MAX)
423         {
424             response.Printf("os_version:%u", major);
425             if (minor != UINT32_MAX)
426             {
427                 response.Printf(".%u", minor);
428                 if (update != UINT32_MAX)
429                     response.Printf(".%u", update);
430             }
431             response.PutChar(';');
432         }
433     }
434 
435     std::string s;
436     if (Host::GetOSBuildString (s))
437     {
438         response.PutCString ("os_build:");
439         response.PutCStringAsRawHex8(s.c_str());
440         response.PutChar(';');
441     }
442     if (Host::GetOSKernelDescription (s))
443     {
444         response.PutCString ("os_kernel:");
445         response.PutCStringAsRawHex8(s.c_str());
446         response.PutChar(';');
447     }
448 #if defined(__APPLE__)
449 
450 #if defined(__arm__)
451     // For iOS devices, we are connected through a USB Mux so we never pretend
452     // to actually have a hostname as far as the remote lldb that is connecting
453     // to this lldb-platform is concerned
454     response.PutCString ("hostname:");
455     response.PutCStringAsRawHex8("127.0.0.1");
456     response.PutChar(';');
457 #else   // #if defined(__arm__)
458     if (Host::GetHostname (s))
459     {
460         response.PutCString ("hostname:");
461         response.PutCStringAsRawHex8(s.c_str());
462         response.PutChar(';');
463     }
464 
465 #endif  // #if defined(__arm__)
466 
467 #else   // #if defined(__APPLE__)
468     if (Host::GetHostname (s))
469     {
470         response.PutCString ("hostname:");
471         response.PutCStringAsRawHex8(s.c_str());
472         response.PutChar(';');
473     }
474 #endif  // #if defined(__APPLE__)
475 
476     return SendPacketNoLock (response.GetData(), response.GetSize());
477 }
478 
479 static void
480 CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
481 {
482     response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
483                      proc_info.GetProcessID(),
484                      proc_info.GetParentProcessID(),
485                      proc_info.GetUserID(),
486                      proc_info.GetGroupID(),
487                      proc_info.GetEffectiveUserID(),
488                      proc_info.GetEffectiveGroupID());
489     response.PutCString ("name:");
490     response.PutCStringAsRawHex8(proc_info.GetName());
491     response.PutChar(';');
492     const ArchSpec &proc_arch = proc_info.GetArchitecture();
493     if (proc_arch.IsValid())
494     {
495         const llvm::Triple &proc_triple = proc_arch.GetTriple();
496         response.PutCString("triple:");
497         response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
498         response.PutChar(';');
499     }
500 }
501 
502 GDBRemoteCommunication::PacketResult
503 GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
504 {
505     // Packet format: "qProcessInfoPID:%i" where %i is the pid
506     packet.SetFilePos(::strlen ("qProcessInfoPID:"));
507     lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
508     if (pid != LLDB_INVALID_PROCESS_ID)
509     {
510         ProcessInstanceInfo proc_info;
511         if (Host::GetProcessInfo(pid, proc_info))
512         {
513             StreamString response;
514             CreateProcessInfoResponse (proc_info, response);
515             return SendPacketNoLock (response.GetData(), response.GetSize());
516         }
517     }
518     return SendErrorResponse (1);
519 }
520 
521 GDBRemoteCommunication::PacketResult
522 GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
523 {
524     m_proc_infos_index = 0;
525     m_proc_infos.Clear();
526 
527     ProcessInstanceInfoMatch match_info;
528     packet.SetFilePos(::strlen ("qfProcessInfo"));
529     if (packet.GetChar() == ':')
530     {
531 
532         std::string key;
533         std::string value;
534         while (packet.GetNameColonValue(key, value))
535         {
536             bool success = true;
537             if (key.compare("name") == 0)
538             {
539                 StringExtractor extractor;
540                 extractor.GetStringRef().swap(value);
541                 extractor.GetHexByteString (value);
542                 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
543             }
544             else if (key.compare("name_match") == 0)
545             {
546                 if (value.compare("equals") == 0)
547                 {
548                     match_info.SetNameMatchType (eNameMatchEquals);
549                 }
550                 else if (value.compare("starts_with") == 0)
551                 {
552                     match_info.SetNameMatchType (eNameMatchStartsWith);
553                 }
554                 else if (value.compare("ends_with") == 0)
555                 {
556                     match_info.SetNameMatchType (eNameMatchEndsWith);
557                 }
558                 else if (value.compare("contains") == 0)
559                 {
560                     match_info.SetNameMatchType (eNameMatchContains);
561                 }
562                 else if (value.compare("regex") == 0)
563                 {
564                     match_info.SetNameMatchType (eNameMatchRegularExpression);
565                 }
566                 else
567                 {
568                     success = false;
569                 }
570             }
571             else if (key.compare("pid") == 0)
572             {
573                 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
574             }
575             else if (key.compare("parent_pid") == 0)
576             {
577                 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
578             }
579             else if (key.compare("uid") == 0)
580             {
581                 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
582             }
583             else if (key.compare("gid") == 0)
584             {
585                 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
586             }
587             else if (key.compare("euid") == 0)
588             {
589                 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
590             }
591             else if (key.compare("egid") == 0)
592             {
593                 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
594             }
595             else if (key.compare("all_users") == 0)
596             {
597                 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
598             }
599             else if (key.compare("triple") == 0)
600             {
601                 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
602             }
603             else
604             {
605                 success = false;
606             }
607 
608             if (!success)
609                 return SendErrorResponse (2);
610         }
611     }
612 
613     if (Host::FindProcesses (match_info, m_proc_infos))
614     {
615         // We found something, return the first item by calling the get
616         // subsequent process info packet handler...
617         return Handle_qsProcessInfo (packet);
618     }
619     return SendErrorResponse (3);
620 }
621 
622 GDBRemoteCommunication::PacketResult
623 GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
624 {
625     if (m_proc_infos_index < m_proc_infos.GetSize())
626     {
627         StreamString response;
628         CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
629         ++m_proc_infos_index;
630         return SendPacketNoLock (response.GetData(), response.GetSize());
631     }
632     return SendErrorResponse (4);
633 }
634 
635 GDBRemoteCommunication::PacketResult
636 GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
637 {
638     // Packet format: "qUserName:%i" where %i is the uid
639     packet.SetFilePos(::strlen ("qUserName:"));
640     uint32_t uid = packet.GetU32 (UINT32_MAX);
641     if (uid != UINT32_MAX)
642     {
643         std::string name;
644         if (Host::GetUserName (uid, name))
645         {
646             StreamString response;
647             response.PutCStringAsRawHex8 (name.c_str());
648             return SendPacketNoLock (response.GetData(), response.GetSize());
649         }
650     }
651     return SendErrorResponse (5);
652 
653 }
654 
655 GDBRemoteCommunication::PacketResult
656 GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
657 {
658     // Packet format: "qGroupName:%i" where %i is the gid
659     packet.SetFilePos(::strlen ("qGroupName:"));
660     uint32_t gid = packet.GetU32 (UINT32_MAX);
661     if (gid != UINT32_MAX)
662     {
663         std::string name;
664         if (Host::GetGroupName (gid, name))
665         {
666             StreamString response;
667             response.PutCStringAsRawHex8 (name.c_str());
668             return SendPacketNoLock (response.GetData(), response.GetSize());
669         }
670     }
671     return SendErrorResponse (6);
672 }
673 
674 GDBRemoteCommunication::PacketResult
675 GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
676 {
677     packet.SetFilePos(::strlen ("qSpeedTest:"));
678 
679     std::string key;
680     std::string value;
681     bool success = packet.GetNameColonValue(key, value);
682     if (success && key.compare("response_size") == 0)
683     {
684         uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
685         if (success)
686         {
687             if (response_size == 0)
688                 return SendOKResponse();
689             StreamString response;
690             uint32_t bytes_left = response_size;
691             response.PutCString("data:");
692             while (bytes_left > 0)
693             {
694                 if (bytes_left >= 26)
695                 {
696                     response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
697                     bytes_left -= 26;
698                 }
699                 else
700                 {
701                     response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
702                     bytes_left = 0;
703                 }
704             }
705             return SendPacketNoLock (response.GetData(), response.GetSize());
706         }
707     }
708     return SendErrorResponse (7);
709 }
710 
711 //
712 //static bool
713 //WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
714 //{
715 //    const int time_delta_usecs = 100000;
716 //    const int num_retries = timeout_in_seconds/time_delta_usecs;
717 //    for (int i=0; i<num_retries; i++)
718 //    {
719 //        struct proc_bsdinfo bsd_info;
720 //        int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
721 //                                    (uint64_t) 0,
722 //                                    &bsd_info,
723 //                                    PROC_PIDTBSDINFO_SIZE);
724 //
725 //        switch (error)
726 //        {
727 //            case EINVAL:
728 //            case ENOTSUP:
729 //            case ESRCH:
730 //            case EPERM:
731 //                return false;
732 //
733 //            default:
734 //                break;
735 //
736 //            case 0:
737 //                if (bsd_info.pbi_status == SSTOP)
738 //                    return true;
739 //        }
740 //        ::usleep (time_delta_usecs);
741 //    }
742 //    return false;
743 //}
744 
745 GDBRemoteCommunication::PacketResult
746 GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
747 {
748     // The 'A' packet is the most over designed packet ever here with
749     // redundant argument indexes, redundant argument lengths and needed hex
750     // encoded argument string values. Really all that is needed is a comma
751     // separated hex encoded argument value list, but we will stay true to the
752     // documented version of the 'A' packet here...
753 
754     packet.SetFilePos(1); // Skip the 'A'
755     bool success = true;
756     while (success && packet.GetBytesLeft() > 0)
757     {
758         // Decode the decimal argument string length. This length is the
759         // number of hex nibbles in the argument string value.
760         const uint32_t arg_len = packet.GetU32(UINT32_MAX);
761         if (arg_len == UINT32_MAX)
762             success = false;
763         else
764         {
765             // Make sure the argument hex string length is followed by a comma
766             if (packet.GetChar() != ',')
767                 success = false;
768             else
769             {
770                 // Decode the argument index. We ignore this really becuase
771                 // who would really send down the arguments in a random order???
772                 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
773                 if (arg_idx == UINT32_MAX)
774                     success = false;
775                 else
776                 {
777                     // Make sure the argument index is followed by a comma
778                     if (packet.GetChar() != ',')
779                         success = false;
780                     else
781                     {
782                         // Decode the argument string value from hex bytes
783                         // back into a UTF8 string and make sure the length
784                         // matches the one supplied in the packet
785                         std::string arg;
786                         if (packet.GetHexByteString(arg) != (arg_len / 2))
787                             success = false;
788                         else
789                         {
790                             // If there are any bytes lft
791                             if (packet.GetBytesLeft())
792                             {
793                                 if (packet.GetChar() != ',')
794                                     success = false;
795                             }
796 
797                             if (success)
798                             {
799                                 if (arg_idx == 0)
800                                     m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
801                                 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
802                             }
803                         }
804                     }
805                 }
806             }
807         }
808     }
809 
810     if (success)
811     {
812         // FIXME: remove linux restriction once eLaunchFlagDebug is supported
813 #if !defined (__linux__)
814         m_process_launch_info.GetFlags().Set (eLaunchFlagDebug);
815 #endif
816         m_process_launch_error = LaunchProcess ();
817         if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
818         {
819             return SendOKResponse ();
820         }
821     }
822     return SendErrorResponse (8);
823 }
824 
825 GDBRemoteCommunication::PacketResult
826 GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
827 {
828     lldb::pid_t pid = m_process_launch_info.GetProcessID();
829     StreamString response;
830     response.Printf("QC%" PRIx64, pid);
831     if (m_is_platform)
832     {
833         // If we launch a process and this GDB server is acting as a platform,
834         // then we need to clear the process launch state so we can start
835         // launching another process. In order to launch a process a bunch or
836         // packets need to be sent: environment packets, working directory,
837         // disable ASLR, and many more settings. When we launch a process we
838         // then need to know when to clear this information. Currently we are
839         // selecting the 'qC' packet as that packet which seems to make the most
840         // sense.
841         if (pid != LLDB_INVALID_PROCESS_ID)
842         {
843             m_process_launch_info.Clear();
844         }
845     }
846     return SendPacketNoLock (response.GetData(), response.GetSize());
847 }
848 
849 bool
850 GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
851 {
852     Mutex::Locker locker (m_spawned_pids_mutex);
853     FreePortForProcess(pid);
854     return m_spawned_pids.erase(pid) > 0;
855 }
856 bool
857 GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
858                                                       lldb::pid_t pid,
859                                                       bool exited,
860                                                       int signal,    // Zero for no signal
861                                                       int status)    // Exit value of process if signal is zero
862 {
863     GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
864     server->DebugserverProcessReaped (pid);
865     return true;
866 }
867 
868 bool
869 GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
870 {
871     // reap a process that we were debugging (but not debugserver)
872     Mutex::Locker locker (m_spawned_pids_mutex);
873     return m_spawned_pids.erase(pid) > 0;
874 }
875 
876 bool
877 GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
878                                                    lldb::pid_t pid,
879                                                    bool exited,
880                                                    int signal,    // Zero for no signal
881                                                    int status)    // Exit value of process if signal is zero
882 {
883     GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
884     server->DebuggedProcessReaped (pid);
885     return true;
886 }
887 
888 GDBRemoteCommunication::PacketResult
889 GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
890 {
891 #ifdef _WIN32
892     return SendErrorResponse(9);
893 #else
894     // Spawn a local debugserver as a platform so we can then attach or launch
895     // a process...
896 
897     if (m_is_platform)
898     {
899         // Sleep and wait a bit for debugserver to start to listen...
900         ConnectionFileDescriptor file_conn;
901         Error error;
902         std::string hostname;
903         // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
904         // with the TMPDIR environnement variable
905         packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
906         std::string name;
907         std::string value;
908         uint16_t port = UINT16_MAX;
909         while (packet.GetNameColonValue(name, value))
910         {
911             if (name.compare ("host") == 0)
912                 hostname.swap(value);
913             else if (name.compare ("port") == 0)
914                 port = Args::StringToUInt32(value.c_str(), 0, 0);
915         }
916         if (port == UINT16_MAX)
917             port = GetNextAvailablePort();
918 
919         // Spawn a new thread to accept the port that gets bound after
920         // binding to port 0 (zero).
921 
922         if (error.Success())
923         {
924             // Spawn a debugserver and try to get the port it listens to.
925             ProcessLaunchInfo debugserver_launch_info;
926             if (hostname.empty())
927                 hostname = "127.0.0.1";
928             Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
929             if (log)
930                 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
931 
932             debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
933 
934             error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
935                                              port,
936                                              debugserver_launch_info,
937                                              port);
938 
939             lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
940 
941 
942             if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
943             {
944                 Mutex::Locker locker (m_spawned_pids_mutex);
945                 m_spawned_pids.insert(debugserver_pid);
946                 if (port > 0)
947                     AssociatePortWithProcess(port, debugserver_pid);
948             }
949             else
950             {
951                 if (port > 0)
952                     FreePort (port);
953             }
954 
955             if (error.Success())
956             {
957                 char response[256];
958                 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
959                 assert (response_len < (int)sizeof(response));
960                 PacketResult packet_result = SendPacketNoLock (response, response_len);
961 
962                 if (packet_result != PacketResult::Success)
963                 {
964                     if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
965                         ::kill (debugserver_pid, SIGINT);
966                 }
967                 return packet_result;
968             }
969         }
970     }
971     return SendErrorResponse (9);
972 #endif
973 }
974 
975 bool
976 GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
977 {
978     // make sure we know about this process
979     {
980         Mutex::Locker locker (m_spawned_pids_mutex);
981         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
982             return false;
983     }
984 
985     // first try a SIGTERM (standard kill)
986     Host::Kill (pid, SIGTERM);
987 
988     // check if that worked
989     for (size_t i=0; i<10; ++i)
990     {
991         {
992             Mutex::Locker locker (m_spawned_pids_mutex);
993             if (m_spawned_pids.find(pid) == m_spawned_pids.end())
994             {
995                 // it is now killed
996                 return true;
997             }
998         }
999         usleep (10000);
1000     }
1001 
1002     // check one more time after the final usleep
1003     {
1004         Mutex::Locker locker (m_spawned_pids_mutex);
1005         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1006             return true;
1007     }
1008 
1009     // the launched process still lives.  Now try killling it again,
1010     // this time with an unblockable signal.
1011     Host::Kill (pid, SIGKILL);
1012 
1013     for (size_t i=0; i<10; ++i)
1014     {
1015         {
1016             Mutex::Locker locker (m_spawned_pids_mutex);
1017             if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1018             {
1019                 // it is now killed
1020                 return true;
1021             }
1022         }
1023         usleep (10000);
1024     }
1025 
1026     // check one more time after the final usleep
1027     // Scope for locker
1028     {
1029         Mutex::Locker locker (m_spawned_pids_mutex);
1030         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1031             return true;
1032     }
1033 
1034     // no luck - the process still lives
1035     return false;
1036 }
1037 
1038 GDBRemoteCommunication::PacketResult
1039 GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
1040 {
1041     packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
1042 
1043     lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
1044 
1045     // verify that we know anything about this pid.
1046     // Scope for locker
1047     {
1048         Mutex::Locker locker (m_spawned_pids_mutex);
1049         if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1050         {
1051             // not a pid we know about
1052             return SendErrorResponse (10);
1053         }
1054     }
1055 
1056     // go ahead and attempt to kill the spawned process
1057     if (KillSpawnedProcess (pid))
1058         return SendOKResponse ();
1059     else
1060         return SendErrorResponse (11);
1061 }
1062 
1063 GDBRemoteCommunication::PacketResult
1064 GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
1065 {
1066     // ignore for now if we're lldb_platform
1067     if (m_is_platform)
1068         return SendUnimplementedResponse (packet.GetStringRef().c_str());
1069 
1070     // shutdown all spawned processes
1071     std::set<lldb::pid_t> spawned_pids_copy;
1072 
1073     // copy pids
1074     {
1075         Mutex::Locker locker (m_spawned_pids_mutex);
1076         spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
1077     }
1078 
1079     // nuke the spawned processes
1080     for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
1081     {
1082         lldb::pid_t spawned_pid = *it;
1083         if (!KillSpawnedProcess (spawned_pid))
1084         {
1085             fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
1086         }
1087     }
1088 
1089     // TODO figure out how to shut down gracefully at this point
1090     return SendOKResponse ();
1091 }
1092 
1093 GDBRemoteCommunication::PacketResult
1094 GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
1095 {
1096     if (m_process_launch_error.Success())
1097         return SendOKResponse();
1098     StreamString response;
1099     response.PutChar('E');
1100     response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
1101     return SendPacketNoLock (response.GetData(), response.GetSize());
1102 }
1103 
1104 GDBRemoteCommunication::PacketResult
1105 GDBRemoteCommunicationServer::Handle_QEnvironment  (StringExtractorGDBRemote &packet)
1106 {
1107     packet.SetFilePos(::strlen ("QEnvironment:"));
1108     const uint32_t bytes_left = packet.GetBytesLeft();
1109     if (bytes_left > 0)
1110     {
1111         m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
1112         return SendOKResponse ();
1113     }
1114     return SendErrorResponse (12);
1115 }
1116 
1117 GDBRemoteCommunication::PacketResult
1118 GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
1119 {
1120     packet.SetFilePos(::strlen ("QLaunchArch:"));
1121     const uint32_t bytes_left = packet.GetBytesLeft();
1122     if (bytes_left > 0)
1123     {
1124         const char* arch_triple = packet.Peek();
1125         ArchSpec arch_spec(arch_triple,NULL);
1126         m_process_launch_info.SetArchitecture(arch_spec);
1127         return SendOKResponse();
1128     }
1129     return SendErrorResponse(13);
1130 }
1131 
1132 GDBRemoteCommunication::PacketResult
1133 GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1134 {
1135     packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1136     if (packet.GetU32(0))
1137         m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1138     else
1139         m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1140     return SendOKResponse ();
1141 }
1142 
1143 GDBRemoteCommunication::PacketResult
1144 GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1145 {
1146     packet.SetFilePos(::strlen ("QSetWorkingDir:"));
1147     std::string path;
1148     packet.GetHexByteString(path);
1149     if (m_is_platform)
1150     {
1151 #ifdef _WIN32
1152         // Not implemented on Windows
1153         return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
1154 #else
1155         // If this packet is sent to a platform, then change the current working directory
1156         if (::chdir(path.c_str()) != 0)
1157             return SendErrorResponse(errno);
1158 #endif
1159     }
1160     else
1161     {
1162         m_process_launch_info.SwapWorkingDirectory (path);
1163     }
1164     return SendOKResponse ();
1165 }
1166 
1167 GDBRemoteCommunication::PacketResult
1168 GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1169 {
1170     StreamString response;
1171 
1172     if (m_is_platform)
1173     {
1174         // If this packet is sent to a platform, then change the current working directory
1175         char cwd[PATH_MAX];
1176         if (getcwd(cwd, sizeof(cwd)) == NULL)
1177         {
1178             return SendErrorResponse(errno);
1179         }
1180         else
1181         {
1182             response.PutBytesAsRawHex8(cwd, strlen(cwd));
1183             return SendPacketNoLock(response.GetData(), response.GetSize());
1184         }
1185     }
1186     else
1187     {
1188         const char *working_dir = m_process_launch_info.GetWorkingDirectory();
1189         if (working_dir && working_dir[0])
1190         {
1191             response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
1192             return SendPacketNoLock(response.GetData(), response.GetSize());
1193         }
1194         else
1195         {
1196             return SendErrorResponse(14);
1197         }
1198     }
1199 }
1200 
1201 GDBRemoteCommunication::PacketResult
1202 GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
1203 {
1204     packet.SetFilePos(::strlen ("QSetSTDIN:"));
1205     ProcessLaunchInfo::FileAction file_action;
1206     std::string path;
1207     packet.GetHexByteString(path);
1208     const bool read = false;
1209     const bool write = true;
1210     if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
1211     {
1212         m_process_launch_info.AppendFileAction(file_action);
1213         return SendOKResponse ();
1214     }
1215     return SendErrorResponse (15);
1216 }
1217 
1218 GDBRemoteCommunication::PacketResult
1219 GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
1220 {
1221     packet.SetFilePos(::strlen ("QSetSTDOUT:"));
1222     ProcessLaunchInfo::FileAction file_action;
1223     std::string path;
1224     packet.GetHexByteString(path);
1225     const bool read = true;
1226     const bool write = false;
1227     if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
1228     {
1229         m_process_launch_info.AppendFileAction(file_action);
1230         return SendOKResponse ();
1231     }
1232     return SendErrorResponse (16);
1233 }
1234 
1235 GDBRemoteCommunication::PacketResult
1236 GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
1237 {
1238     packet.SetFilePos(::strlen ("QSetSTDERR:"));
1239     ProcessLaunchInfo::FileAction file_action;
1240     std::string path;
1241     packet.GetHexByteString(path);
1242     const bool read = true;
1243     const bool write = false;
1244     if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
1245     {
1246         m_process_launch_info.AppendFileAction(file_action);
1247         return SendOKResponse ();
1248     }
1249     return SendErrorResponse (17);
1250 }
1251 
1252 GDBRemoteCommunication::PacketResult
1253 GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
1254 {
1255     // Send response first before changing m_send_acks to we ack this packet
1256     PacketResult packet_result = SendOKResponse ();
1257     m_send_acks = false;
1258     return packet_result;
1259 }
1260 
1261 GDBRemoteCommunication::PacketResult
1262 GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
1263 {
1264     packet.SetFilePos(::strlen("qPlatform_mkdir:"));
1265     mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
1266     if (packet.GetChar() == ',')
1267     {
1268         std::string path;
1269         packet.GetHexByteString(path);
1270         Error error = Host::MakeDirectory(path.c_str(),mode);
1271         if (error.Success())
1272             return SendPacketNoLock ("OK", 2);
1273         else
1274             return SendErrorResponse(error.GetError());
1275     }
1276     return SendErrorResponse(20);
1277 }
1278 
1279 GDBRemoteCommunication::PacketResult
1280 GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
1281 {
1282     packet.SetFilePos(::strlen("qPlatform_chmod:"));
1283 
1284     mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
1285     if (packet.GetChar() == ',')
1286     {
1287         std::string path;
1288         packet.GetHexByteString(path);
1289         Error error = Host::SetFilePermissions (path.c_str(), mode);
1290         if (error.Success())
1291             return SendPacketNoLock ("OK", 2);
1292         else
1293             return SendErrorResponse(error.GetError());
1294     }
1295     return SendErrorResponse(19);
1296 }
1297 
1298 GDBRemoteCommunication::PacketResult
1299 GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
1300 {
1301     packet.SetFilePos(::strlen("vFile:open:"));
1302     std::string path;
1303     packet.GetHexByteStringTerminatedBy(path,',');
1304     if (!path.empty())
1305     {
1306         if (packet.GetChar() == ',')
1307         {
1308             uint32_t flags = packet.GetHexMaxU32(false, 0);
1309             if (packet.GetChar() == ',')
1310             {
1311                 mode_t mode = packet.GetHexMaxU32(false, 0600);
1312                 Error error;
1313                 int fd = ::open (path.c_str(), flags, mode);
1314                 const int save_errno = fd == -1 ? errno : 0;
1315                 StreamString response;
1316                 response.PutChar('F');
1317                 response.Printf("%i", fd);
1318                 if (save_errno)
1319                     response.Printf(",%i", save_errno);
1320                 return SendPacketNoLock(response.GetData(), response.GetSize());
1321             }
1322         }
1323     }
1324     return SendErrorResponse(18);
1325 }
1326 
1327 GDBRemoteCommunication::PacketResult
1328 GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
1329 {
1330     packet.SetFilePos(::strlen("vFile:close:"));
1331     int fd = packet.GetS32(-1);
1332     Error error;
1333     int err = -1;
1334     int save_errno = 0;
1335     if (fd >= 0)
1336     {
1337         err = close(fd);
1338         save_errno = err == -1 ? errno : 0;
1339     }
1340     else
1341     {
1342         save_errno = EINVAL;
1343     }
1344     StreamString response;
1345     response.PutChar('F');
1346     response.Printf("%i", err);
1347     if (save_errno)
1348         response.Printf(",%i", save_errno);
1349     return SendPacketNoLock(response.GetData(), response.GetSize());
1350 }
1351 
1352 GDBRemoteCommunication::PacketResult
1353 GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
1354 {
1355 #ifdef _WIN32
1356     // Not implemented on Windows
1357     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
1358 #else
1359     StreamGDBRemote response;
1360     packet.SetFilePos(::strlen("vFile:pread:"));
1361     int fd = packet.GetS32(-1);
1362     if (packet.GetChar() == ',')
1363     {
1364         uint64_t count = packet.GetU64(UINT64_MAX);
1365         if (packet.GetChar() == ',')
1366         {
1367             uint64_t offset = packet.GetU64(UINT32_MAX);
1368             if (count == UINT64_MAX)
1369             {
1370                 response.Printf("F-1:%i", EINVAL);
1371                 return SendPacketNoLock(response.GetData(), response.GetSize());
1372             }
1373 
1374             std::string buffer(count, 0);
1375             const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
1376             const int save_errno = bytes_read == -1 ? errno : 0;
1377             response.PutChar('F');
1378             response.Printf("%zi", bytes_read);
1379             if (save_errno)
1380                 response.Printf(",%i", save_errno);
1381             else
1382             {
1383                 response.PutChar(';');
1384                 response.PutEscapedBytes(&buffer[0], bytes_read);
1385             }
1386             return SendPacketNoLock(response.GetData(), response.GetSize());
1387         }
1388     }
1389     return SendErrorResponse(21);
1390 
1391 #endif
1392 }
1393 
1394 GDBRemoteCommunication::PacketResult
1395 GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
1396 {
1397 #ifdef _WIN32
1398     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
1399 #else
1400     packet.SetFilePos(::strlen("vFile:pwrite:"));
1401 
1402     StreamGDBRemote response;
1403     response.PutChar('F');
1404 
1405     int fd = packet.GetU32(UINT32_MAX);
1406     if (packet.GetChar() == ',')
1407     {
1408         off_t offset = packet.GetU64(UINT32_MAX);
1409         if (packet.GetChar() == ',')
1410         {
1411             std::string buffer;
1412             if (packet.GetEscapedBinaryData(buffer))
1413             {
1414                 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
1415                 const int save_errno = bytes_written == -1 ? errno : 0;
1416                 response.Printf("%zi", bytes_written);
1417                 if (save_errno)
1418                     response.Printf(",%i", save_errno);
1419             }
1420             else
1421             {
1422                 response.Printf ("-1,%i", EINVAL);
1423             }
1424             return SendPacketNoLock(response.GetData(), response.GetSize());
1425         }
1426     }
1427     return SendErrorResponse(27);
1428 #endif
1429 }
1430 
1431 GDBRemoteCommunication::PacketResult
1432 GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
1433 {
1434     packet.SetFilePos(::strlen("vFile:size:"));
1435     std::string path;
1436     packet.GetHexByteString(path);
1437     if (!path.empty())
1438     {
1439         lldb::user_id_t retcode = Host::GetFileSize(FileSpec(path.c_str(), false));
1440         StreamString response;
1441         response.PutChar('F');
1442         response.PutHex64(retcode);
1443         if (retcode == UINT64_MAX)
1444         {
1445             response.PutChar(',');
1446             response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
1447         }
1448         return SendPacketNoLock(response.GetData(), response.GetSize());
1449     }
1450     return SendErrorResponse(22);
1451 }
1452 
1453 GDBRemoteCommunication::PacketResult
1454 GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
1455 {
1456     packet.SetFilePos(::strlen("vFile:mode:"));
1457     std::string path;
1458     packet.GetHexByteString(path);
1459     if (!path.empty())
1460     {
1461         Error error;
1462         const uint32_t mode = File::GetPermissions(path.c_str(), error);
1463         StreamString response;
1464         response.Printf("F%u", mode);
1465         if (mode == 0 || error.Fail())
1466             response.Printf(",%i", (int)error.GetError());
1467         return SendPacketNoLock(response.GetData(), response.GetSize());
1468     }
1469     return SendErrorResponse(23);
1470 }
1471 
1472 GDBRemoteCommunication::PacketResult
1473 GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
1474 {
1475     packet.SetFilePos(::strlen("vFile:exists:"));
1476     std::string path;
1477     packet.GetHexByteString(path);
1478     if (!path.empty())
1479     {
1480         bool retcode = Host::GetFileExists(FileSpec(path.c_str(), false));
1481         StreamString response;
1482         response.PutChar('F');
1483         response.PutChar(',');
1484         if (retcode)
1485             response.PutChar('1');
1486         else
1487             response.PutChar('0');
1488         return SendPacketNoLock(response.GetData(), response.GetSize());
1489     }
1490     return SendErrorResponse(24);
1491 }
1492 
1493 GDBRemoteCommunication::PacketResult
1494 GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
1495 {
1496     packet.SetFilePos(::strlen("vFile:symlink:"));
1497     std::string dst, src;
1498     packet.GetHexByteStringTerminatedBy(dst, ',');
1499     packet.GetChar(); // Skip ',' char
1500     packet.GetHexByteString(src);
1501     Error error = Host::Symlink(src.c_str(), dst.c_str());
1502     StreamString response;
1503     response.Printf("F%u,%u", error.GetError(), error.GetError());
1504     return SendPacketNoLock(response.GetData(), response.GetSize());
1505 }
1506 
1507 GDBRemoteCommunication::PacketResult
1508 GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
1509 {
1510     packet.SetFilePos(::strlen("vFile:unlink:"));
1511     std::string path;
1512     packet.GetHexByteString(path);
1513     Error error = Host::Unlink(path.c_str());
1514     StreamString response;
1515     response.Printf("F%u,%u", error.GetError(), error.GetError());
1516     return SendPacketNoLock(response.GetData(), response.GetSize());
1517 }
1518 
1519 GDBRemoteCommunication::PacketResult
1520 GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
1521 {
1522     packet.SetFilePos(::strlen("qPlatform_shell:"));
1523     std::string path;
1524     std::string working_dir;
1525     packet.GetHexByteStringTerminatedBy(path,',');
1526     if (!path.empty())
1527     {
1528         if (packet.GetChar() == ',')
1529         {
1530             // FIXME: add timeout to qPlatform_shell packet
1531             // uint32_t timeout = packet.GetHexMaxU32(false, 32);
1532             uint32_t timeout = 10;
1533             if (packet.GetChar() == ',')
1534                 packet.GetHexByteString(working_dir);
1535             int status, signo;
1536             std::string output;
1537             Error err = Host::RunShellCommand(path.c_str(),
1538                                               working_dir.empty() ? NULL : working_dir.c_str(),
1539                                               &status, &signo, &output, timeout);
1540             StreamGDBRemote response;
1541             if (err.Fail())
1542             {
1543                 response.PutCString("F,");
1544                 response.PutHex32(UINT32_MAX);
1545             }
1546             else
1547             {
1548                 response.PutCString("F,");
1549                 response.PutHex32(status);
1550                 response.PutChar(',');
1551                 response.PutHex32(signo);
1552                 response.PutChar(',');
1553                 response.PutEscapedBytes(output.c_str(), output.size());
1554             }
1555             return SendPacketNoLock(response.GetData(), response.GetSize());
1556         }
1557     }
1558     return SendErrorResponse(24);
1559 }
1560 
1561 GDBRemoteCommunication::PacketResult
1562 GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
1563 {
1564     return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
1565 }
1566 
1567 GDBRemoteCommunication::PacketResult
1568 GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
1569 {
1570     packet.SetFilePos(::strlen("vFile:MD5:"));
1571     std::string path;
1572     packet.GetHexByteString(path);
1573     if (!path.empty())
1574     {
1575         uint64_t a,b;
1576         StreamGDBRemote response;
1577         if (Host::CalculateMD5(FileSpec(path.c_str(),false),a,b) == false)
1578         {
1579             response.PutCString("F,");
1580             response.PutCString("x");
1581         }
1582         else
1583         {
1584             response.PutCString("F,");
1585             response.PutHex64(a);
1586             response.PutHex64(b);
1587         }
1588         return SendPacketNoLock(response.GetData(), response.GetSize());
1589     }
1590     return SendErrorResponse(25);
1591 }
1592 
1593