1 //===-- GDBRemoteCommunicationServerCommon.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 "GDBRemoteCommunicationServerCommon.h"
11 
12 #include <errno.h>
13 
14 // C Includes
15 
16 #ifdef __APPLE__
17 #include <TargetConditionals.h>
18 #endif
19 
20 // C++ Includes
21 #include <chrono>
22 #include <cstring>
23 
24 // Other libraries and framework includes
25 #include "lldb/Core/Log.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/StreamGDBRemote.h"
28 #include "lldb/Core/StreamString.h"
29 #include "lldb/Host/Config.h"
30 #include "lldb/Host/Endian.h"
31 #include "lldb/Host/File.h"
32 #include "lldb/Host/FileSystem.h"
33 #include "lldb/Host/Host.h"
34 #include "lldb/Host/HostInfo.h"
35 #include "lldb/Host/StringConvert.h"
36 #include "lldb/Interpreter/Args.h"
37 #include "lldb/Symbol/ObjectFile.h"
38 #include "lldb/Target/FileAction.h"
39 #include "lldb/Target/Platform.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Utility/JSON.h"
42 #include "llvm/ADT/Triple.h"
43 
44 // Project includes
45 #include "ProcessGDBRemoteLog.h"
46 #include "Utility/StringExtractorGDBRemote.h"
47 
48 #ifdef __ANDROID__
49 #include "lldb/Host/android/HostInfoAndroid.h"
50 #endif
51 
52 #include "llvm/ADT/StringSwitch.h"
53 
54 using namespace lldb;
55 using namespace lldb_private;
56 using namespace lldb_private::process_gdb_remote;
57 
58 #ifdef __ANDROID__
59 const static uint32_t g_default_packet_timeout_sec = 20; // seconds
60 #else
61 const static uint32_t g_default_packet_timeout_sec = 0; // not specified
62 #endif
63 
64 //----------------------------------------------------------------------
65 // GDBRemoteCommunicationServerCommon constructor
66 //----------------------------------------------------------------------
67 GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon(
68     const char *comm_name, const char *listener_name)
69     : GDBRemoteCommunicationServer(comm_name, listener_name),
70       m_process_launch_info(), m_process_launch_error(), m_proc_infos(),
71       m_proc_infos_index(0), m_thread_suffix_supported(false),
72       m_list_threads_in_stop_reply(false) {
73   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A,
74                                 &GDBRemoteCommunicationServerCommon::Handle_A);
75   RegisterMemberFunctionHandler(
76       StringExtractorGDBRemote::eServerPacketType_QEnvironment,
77       &GDBRemoteCommunicationServerCommon::Handle_QEnvironment);
78   RegisterMemberFunctionHandler(
79       StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded,
80       &GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded);
81   RegisterMemberFunctionHandler(
82       StringExtractorGDBRemote::eServerPacketType_qfProcessInfo,
83       &GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo);
84   RegisterMemberFunctionHandler(
85       StringExtractorGDBRemote::eServerPacketType_qGroupName,
86       &GDBRemoteCommunicationServerCommon::Handle_qGroupName);
87   RegisterMemberFunctionHandler(
88       StringExtractorGDBRemote::eServerPacketType_qHostInfo,
89       &GDBRemoteCommunicationServerCommon::Handle_qHostInfo);
90   RegisterMemberFunctionHandler(
91       StringExtractorGDBRemote::eServerPacketType_QLaunchArch,
92       &GDBRemoteCommunicationServerCommon::Handle_QLaunchArch);
93   RegisterMemberFunctionHandler(
94       StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess,
95       &GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess);
96   RegisterMemberFunctionHandler(
97       StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
98       &GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply);
99   RegisterMemberFunctionHandler(
100       StringExtractorGDBRemote::eServerPacketType_qEcho,
101       &GDBRemoteCommunicationServerCommon::Handle_qEcho);
102   RegisterMemberFunctionHandler(
103       StringExtractorGDBRemote::eServerPacketType_qModuleInfo,
104       &GDBRemoteCommunicationServerCommon::Handle_qModuleInfo);
105   RegisterMemberFunctionHandler(
106       StringExtractorGDBRemote::eServerPacketType_jModulesInfo,
107       &GDBRemoteCommunicationServerCommon::Handle_jModulesInfo);
108   RegisterMemberFunctionHandler(
109       StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod,
110       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod);
111   RegisterMemberFunctionHandler(
112       StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir,
113       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir);
114   RegisterMemberFunctionHandler(
115       StringExtractorGDBRemote::eServerPacketType_qPlatform_shell,
116       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell);
117   RegisterMemberFunctionHandler(
118       StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID,
119       &GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID);
120   RegisterMemberFunctionHandler(
121       StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError,
122       &GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError);
123   RegisterMemberFunctionHandler(
124       StringExtractorGDBRemote::eServerPacketType_QSetSTDERR,
125       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR);
126   RegisterMemberFunctionHandler(
127       StringExtractorGDBRemote::eServerPacketType_QSetSTDIN,
128       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN);
129   RegisterMemberFunctionHandler(
130       StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT,
131       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT);
132   RegisterMemberFunctionHandler(
133       StringExtractorGDBRemote::eServerPacketType_qSpeedTest,
134       &GDBRemoteCommunicationServerCommon::Handle_qSpeedTest);
135   RegisterMemberFunctionHandler(
136       StringExtractorGDBRemote::eServerPacketType_qsProcessInfo,
137       &GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo);
138   RegisterMemberFunctionHandler(
139       StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode,
140       &GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode);
141   RegisterMemberFunctionHandler(
142       StringExtractorGDBRemote::eServerPacketType_qSupported,
143       &GDBRemoteCommunicationServerCommon::Handle_qSupported);
144   RegisterMemberFunctionHandler(
145       StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
146       &GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported);
147   RegisterMemberFunctionHandler(
148       StringExtractorGDBRemote::eServerPacketType_qUserName,
149       &GDBRemoteCommunicationServerCommon::Handle_qUserName);
150   RegisterMemberFunctionHandler(
151       StringExtractorGDBRemote::eServerPacketType_vFile_close,
152       &GDBRemoteCommunicationServerCommon::Handle_vFile_Close);
153   RegisterMemberFunctionHandler(
154       StringExtractorGDBRemote::eServerPacketType_vFile_exists,
155       &GDBRemoteCommunicationServerCommon::Handle_vFile_Exists);
156   RegisterMemberFunctionHandler(
157       StringExtractorGDBRemote::eServerPacketType_vFile_md5,
158       &GDBRemoteCommunicationServerCommon::Handle_vFile_MD5);
159   RegisterMemberFunctionHandler(
160       StringExtractorGDBRemote::eServerPacketType_vFile_mode,
161       &GDBRemoteCommunicationServerCommon::Handle_vFile_Mode);
162   RegisterMemberFunctionHandler(
163       StringExtractorGDBRemote::eServerPacketType_vFile_open,
164       &GDBRemoteCommunicationServerCommon::Handle_vFile_Open);
165   RegisterMemberFunctionHandler(
166       StringExtractorGDBRemote::eServerPacketType_vFile_pread,
167       &GDBRemoteCommunicationServerCommon::Handle_vFile_pRead);
168   RegisterMemberFunctionHandler(
169       StringExtractorGDBRemote::eServerPacketType_vFile_pwrite,
170       &GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite);
171   RegisterMemberFunctionHandler(
172       StringExtractorGDBRemote::eServerPacketType_vFile_size,
173       &GDBRemoteCommunicationServerCommon::Handle_vFile_Size);
174   RegisterMemberFunctionHandler(
175       StringExtractorGDBRemote::eServerPacketType_vFile_stat,
176       &GDBRemoteCommunicationServerCommon::Handle_vFile_Stat);
177   RegisterMemberFunctionHandler(
178       StringExtractorGDBRemote::eServerPacketType_vFile_symlink,
179       &GDBRemoteCommunicationServerCommon::Handle_vFile_symlink);
180   RegisterMemberFunctionHandler(
181       StringExtractorGDBRemote::eServerPacketType_vFile_unlink,
182       &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink);
183 }
184 
185 //----------------------------------------------------------------------
186 // Destructor
187 //----------------------------------------------------------------------
188 GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() {}
189 
190 GDBRemoteCommunication::PacketResult
191 GDBRemoteCommunicationServerCommon::Handle_qHostInfo(
192     StringExtractorGDBRemote &packet) {
193   StreamString response;
194 
195   // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
196 
197   ArchSpec host_arch(HostInfo::GetArchitecture());
198   const llvm::Triple &host_triple = host_arch.GetTriple();
199   response.PutCString("triple:");
200   response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
201   response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize());
202 
203   const char *distribution_id = host_arch.GetDistributionId().AsCString();
204   if (distribution_id) {
205     response.PutCString("distribution_id:");
206     response.PutCStringAsRawHex8(distribution_id);
207     response.PutCString(";");
208   }
209 
210 #if defined(__APPLE__)
211   // For parity with debugserver, we'll include the vendor key.
212   response.PutCString("vendor:apple;");
213 
214   // Send out MachO info.
215   uint32_t cpu = host_arch.GetMachOCPUType();
216   uint32_t sub = host_arch.GetMachOCPUSubType();
217   if (cpu != LLDB_INVALID_CPUTYPE)
218     response.Printf("cputype:%u;", cpu);
219   if (sub != LLDB_INVALID_CPUTYPE)
220     response.Printf("cpusubtype:%u;", sub);
221 
222   if (cpu == ArchSpec::kCore_arm_any) {
223 // Indicate the OS type.
224 #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
225     response.PutCString("ostype:tvos;");
226 #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
227     response.PutCString("ostype:watchos;");
228 #else
229     response.PutCString("ostype:ios;");
230 #endif
231 
232     // On arm, we use "synchronous" watchpoints which means the exception is
233     // delivered before the instruction executes.
234     response.PutCString("watchpoint_exceptions_received:before;");
235   } else {
236     response.PutCString("ostype:macosx;");
237     response.Printf("watchpoint_exceptions_received:after;");
238   }
239 
240 #else
241   if (host_arch.GetMachine() == llvm::Triple::aarch64 ||
242       host_arch.GetMachine() == llvm::Triple::aarch64_be ||
243       host_arch.GetMachine() == llvm::Triple::arm ||
244       host_arch.GetMachine() == llvm::Triple::armeb ||
245       host_arch.GetMachine() == llvm::Triple::mips64 ||
246       host_arch.GetMachine() == llvm::Triple::mips64el ||
247       host_arch.GetMachine() == llvm::Triple::mips ||
248       host_arch.GetMachine() == llvm::Triple::mipsel)
249     response.Printf("watchpoint_exceptions_received:before;");
250   else
251     response.Printf("watchpoint_exceptions_received:after;");
252 #endif
253 
254   switch (endian::InlHostByteOrder()) {
255   case eByteOrderBig:
256     response.PutCString("endian:big;");
257     break;
258   case eByteOrderLittle:
259     response.PutCString("endian:little;");
260     break;
261   case eByteOrderPDP:
262     response.PutCString("endian:pdp;");
263     break;
264   default:
265     response.PutCString("endian:unknown;");
266     break;
267   }
268 
269   uint32_t major = UINT32_MAX;
270   uint32_t minor = UINT32_MAX;
271   uint32_t update = UINT32_MAX;
272   if (HostInfo::GetOSVersion(major, minor, update)) {
273     if (major != UINT32_MAX) {
274       response.Printf("os_version:%u", major);
275       if (minor != UINT32_MAX) {
276         response.Printf(".%u", minor);
277         if (update != UINT32_MAX)
278           response.Printf(".%u", update);
279       }
280       response.PutChar(';');
281     }
282   }
283 
284   std::string s;
285   if (HostInfo::GetOSBuildString(s)) {
286     response.PutCString("os_build:");
287     response.PutCStringAsRawHex8(s.c_str());
288     response.PutChar(';');
289   }
290   if (HostInfo::GetOSKernelDescription(s)) {
291     response.PutCString("os_kernel:");
292     response.PutCStringAsRawHex8(s.c_str());
293     response.PutChar(';');
294   }
295 
296 #if defined(__APPLE__)
297 
298 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
299   // For iOS devices, we are connected through a USB Mux so we never pretend
300   // to actually have a hostname as far as the remote lldb that is connecting
301   // to this lldb-platform is concerned
302   response.PutCString("hostname:");
303   response.PutCStringAsRawHex8("127.0.0.1");
304   response.PutChar(';');
305 #else  // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
306   if (HostInfo::GetHostname(s)) {
307     response.PutCString("hostname:");
308     response.PutCStringAsRawHex8(s.c_str());
309     response.PutChar(';');
310   }
311 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
312 
313 #else  // #if defined(__APPLE__)
314   if (HostInfo::GetHostname(s)) {
315     response.PutCString("hostname:");
316     response.PutCStringAsRawHex8(s.c_str());
317     response.PutChar(';');
318   }
319 #endif // #if defined(__APPLE__)
320 
321   if (g_default_packet_timeout_sec > 0)
322     response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec);
323 
324   return SendPacketNoLock(response.GetString());
325 }
326 
327 GDBRemoteCommunication::PacketResult
328 GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID(
329     StringExtractorGDBRemote &packet) {
330   // Packet format: "qProcessInfoPID:%i" where %i is the pid
331   packet.SetFilePos(::strlen("qProcessInfoPID:"));
332   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID);
333   if (pid != LLDB_INVALID_PROCESS_ID) {
334     ProcessInstanceInfo proc_info;
335     if (Host::GetProcessInfo(pid, proc_info)) {
336       StreamString response;
337       CreateProcessInfoResponse(proc_info, response);
338       return SendPacketNoLock(response.GetString());
339     }
340   }
341   return SendErrorResponse(1);
342 }
343 
344 GDBRemoteCommunication::PacketResult
345 GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo(
346     StringExtractorGDBRemote &packet) {
347   m_proc_infos_index = 0;
348   m_proc_infos.Clear();
349 
350   ProcessInstanceInfoMatch match_info;
351   packet.SetFilePos(::strlen("qfProcessInfo"));
352   if (packet.GetChar() == ':') {
353     llvm::StringRef key;
354     llvm::StringRef value;
355     while (packet.GetNameColonValue(key, value)) {
356       bool success = true;
357       if (key.equals("name")) {
358         StringExtractor extractor(value);
359         std::string file;
360         extractor.GetHexByteString(file);
361         match_info.GetProcessInfo().GetExecutableFile().SetFile(file.c_str(),
362                                                                 false);
363       } else if (key.equals("name_match")) {
364         NameMatchType name_match =
365             llvm::StringSwitch<NameMatchType>(value)
366                 .Case("equals", eNameMatchEquals)
367                 .Case("starts_with", eNameMatchStartsWith)
368                 .Case("ends_with", eNameMatchEndsWith)
369                 .Case("contains", eNameMatchContains)
370                 .Case("regex", eNameMatchRegularExpression)
371                 .Default(eNameMatchIgnore);
372         match_info.SetNameMatchType(name_match);
373         if (name_match == eNameMatchIgnore)
374           return SendErrorResponse(2);
375       } else if (key.equals("pid")) {
376         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
377         if (value.getAsInteger(0, pid))
378           return SendErrorResponse(2);
379         match_info.GetProcessInfo().SetProcessID(pid);
380       } else if (key.equals("parent_pid")) {
381         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
382         if (value.getAsInteger(0, pid))
383           return SendErrorResponse(2);
384         match_info.GetProcessInfo().SetParentProcessID(pid);
385       } else if (key.equals("uid")) {
386         uint32_t uid = UINT32_MAX;
387         if (value.getAsInteger(0, uid))
388           return SendErrorResponse(2);
389         match_info.GetProcessInfo().SetUserID(uid);
390       } else if (key.equals("gid")) {
391         uint32_t gid = UINT32_MAX;
392         if (value.getAsInteger(0, gid))
393           return SendErrorResponse(2);
394         match_info.GetProcessInfo().SetGroupID(gid);
395       } else if (key.equals("euid")) {
396         uint32_t uid = UINT32_MAX;
397         if (value.getAsInteger(0, uid))
398           return SendErrorResponse(2);
399         match_info.GetProcessInfo().SetEffectiveUserID(uid);
400       } else if (key.equals("egid")) {
401         uint32_t gid = UINT32_MAX;
402         if (value.getAsInteger(0, gid))
403           return SendErrorResponse(2);
404         match_info.GetProcessInfo().SetEffectiveGroupID(gid);
405       } else if (key.equals("all_users")) {
406         match_info.SetMatchAllUsers(
407             Args::StringToBoolean(value, false, &success));
408       } else if (key.equals("triple")) {
409         match_info.GetProcessInfo().GetArchitecture().SetTriple(
410             value.str().c_str(), NULL);
411       } else {
412         success = false;
413       }
414 
415       if (!success)
416         return SendErrorResponse(2);
417     }
418   }
419 
420   if (Host::FindProcesses(match_info, m_proc_infos)) {
421     // We found something, return the first item by calling the get
422     // subsequent process info packet handler...
423     return Handle_qsProcessInfo(packet);
424   }
425   return SendErrorResponse(3);
426 }
427 
428 GDBRemoteCommunication::PacketResult
429 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(
430     StringExtractorGDBRemote &packet) {
431   if (m_proc_infos_index < m_proc_infos.GetSize()) {
432     StreamString response;
433     CreateProcessInfoResponse(
434         m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
435     ++m_proc_infos_index;
436     return SendPacketNoLock(response.GetString());
437   }
438   return SendErrorResponse(4);
439 }
440 
441 GDBRemoteCommunication::PacketResult
442 GDBRemoteCommunicationServerCommon::Handle_qUserName(
443     StringExtractorGDBRemote &packet) {
444 #if !defined(LLDB_DISABLE_POSIX)
445   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
446   if (log)
447     log->Printf("GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);
448 
449   // Packet format: "qUserName:%i" where %i is the uid
450   packet.SetFilePos(::strlen("qUserName:"));
451   uint32_t uid = packet.GetU32(UINT32_MAX);
452   if (uid != UINT32_MAX) {
453     std::string name;
454     if (HostInfo::LookupUserName(uid, name)) {
455       StreamString response;
456       response.PutCStringAsRawHex8(name.c_str());
457       return SendPacketNoLock(response.GetString());
458     }
459   }
460   if (log)
461     log->Printf("GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);
462 #endif
463   return SendErrorResponse(5);
464 }
465 
466 GDBRemoteCommunication::PacketResult
467 GDBRemoteCommunicationServerCommon::Handle_qGroupName(
468     StringExtractorGDBRemote &packet) {
469 #if !defined(LLDB_DISABLE_POSIX)
470   // Packet format: "qGroupName:%i" where %i is the gid
471   packet.SetFilePos(::strlen("qGroupName:"));
472   uint32_t gid = packet.GetU32(UINT32_MAX);
473   if (gid != UINT32_MAX) {
474     std::string name;
475     if (HostInfo::LookupGroupName(gid, name)) {
476       StreamString response;
477       response.PutCStringAsRawHex8(name.c_str());
478       return SendPacketNoLock(response.GetString());
479     }
480   }
481 #endif
482   return SendErrorResponse(6);
483 }
484 
485 GDBRemoteCommunication::PacketResult
486 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(
487     StringExtractorGDBRemote &packet) {
488   packet.SetFilePos(::strlen("qSpeedTest:"));
489 
490   llvm::StringRef key;
491   llvm::StringRef value;
492   bool success = packet.GetNameColonValue(key, value);
493   if (success && key.equals("response_size")) {
494     uint32_t response_size = 0;
495     if (!value.getAsInteger(0, response_size)) {
496       if (response_size == 0)
497         return SendOKResponse();
498       StreamString response;
499       uint32_t bytes_left = response_size;
500       response.PutCString("data:");
501       while (bytes_left > 0) {
502         if (bytes_left >= 26) {
503           response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
504           bytes_left -= 26;
505         } else {
506           response.Printf("%*.*s;", bytes_left, bytes_left,
507                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
508           bytes_left = 0;
509         }
510       }
511       return SendPacketNoLock(response.GetString());
512     }
513   }
514   return SendErrorResponse(7);
515 }
516 
517 GDBRemoteCommunication::PacketResult
518 GDBRemoteCommunicationServerCommon::Handle_vFile_Open(
519     StringExtractorGDBRemote &packet) {
520   packet.SetFilePos(::strlen("vFile:open:"));
521   std::string path;
522   packet.GetHexByteStringTerminatedBy(path, ',');
523   if (!path.empty()) {
524     if (packet.GetChar() == ',') {
525       uint32_t flags =
526           File::ConvertOpenOptionsForPOSIXOpen(packet.GetHexMaxU32(false, 0));
527       if (packet.GetChar() == ',') {
528         mode_t mode = packet.GetHexMaxU32(false, 0600);
529         Error error;
530         const FileSpec path_spec{path, true};
531         int fd = ::open(path_spec.GetCString(), flags, mode);
532         const int save_errno = fd == -1 ? errno : 0;
533         StreamString response;
534         response.PutChar('F');
535         response.Printf("%i", fd);
536         if (save_errno)
537           response.Printf(",%i", save_errno);
538         return SendPacketNoLock(response.GetString());
539       }
540     }
541   }
542   return SendErrorResponse(18);
543 }
544 
545 GDBRemoteCommunication::PacketResult
546 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
547     StringExtractorGDBRemote &packet) {
548   packet.SetFilePos(::strlen("vFile:close:"));
549   int fd = packet.GetS32(-1);
550   Error error;
551   int err = -1;
552   int save_errno = 0;
553   if (fd >= 0) {
554     err = close(fd);
555     save_errno = err == -1 ? errno : 0;
556   } else {
557     save_errno = EINVAL;
558   }
559   StreamString response;
560   response.PutChar('F');
561   response.Printf("%i", err);
562   if (save_errno)
563     response.Printf(",%i", save_errno);
564   return SendPacketNoLock(response.GetString());
565 }
566 
567 GDBRemoteCommunication::PacketResult
568 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
569     StringExtractorGDBRemote &packet) {
570 #ifdef _WIN32
571   // Not implemented on Windows
572   return SendUnimplementedResponse(
573       "GDBRemoteCommunicationServerCommon::Handle_vFile_pRead() unimplemented");
574 #else
575   StreamGDBRemote response;
576   packet.SetFilePos(::strlen("vFile:pread:"));
577   int fd = packet.GetS32(-1);
578   if (packet.GetChar() == ',') {
579     uint64_t count = packet.GetU64(UINT64_MAX);
580     if (packet.GetChar() == ',') {
581       uint64_t offset = packet.GetU64(UINT32_MAX);
582       if (count == UINT64_MAX) {
583         response.Printf("F-1:%i", EINVAL);
584         return SendPacketNoLock(response.GetString());
585       }
586 
587       std::string buffer(count, 0);
588       const ssize_t bytes_read = ::pread(fd, &buffer[0], buffer.size(), offset);
589       const int save_errno = bytes_read == -1 ? errno : 0;
590       response.PutChar('F');
591       response.Printf("%zi", bytes_read);
592       if (save_errno)
593         response.Printf(",%i", save_errno);
594       else {
595         response.PutChar(';');
596         response.PutEscapedBytes(&buffer[0], bytes_read);
597       }
598       return SendPacketNoLock(response.GetString());
599     }
600   }
601   return SendErrorResponse(21);
602 
603 #endif
604 }
605 
606 GDBRemoteCommunication::PacketResult
607 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
608     StringExtractorGDBRemote &packet) {
609 #ifdef _WIN32
610   return SendUnimplementedResponse("GDBRemoteCommunicationServerCommon::Handle_"
611                                    "vFile_pWrite() unimplemented");
612 #else
613   packet.SetFilePos(::strlen("vFile:pwrite:"));
614 
615   StreamGDBRemote response;
616   response.PutChar('F');
617 
618   int fd = packet.GetU32(UINT32_MAX);
619   if (packet.GetChar() == ',') {
620     off_t offset = packet.GetU64(UINT32_MAX);
621     if (packet.GetChar() == ',') {
622       std::string buffer;
623       if (packet.GetEscapedBinaryData(buffer)) {
624         const ssize_t bytes_written =
625             ::pwrite(fd, buffer.data(), buffer.size(), offset);
626         const int save_errno = bytes_written == -1 ? errno : 0;
627         response.Printf("%zi", bytes_written);
628         if (save_errno)
629           response.Printf(",%i", save_errno);
630       } else {
631         response.Printf("-1,%i", EINVAL);
632       }
633       return SendPacketNoLock(response.GetString());
634     }
635   }
636   return SendErrorResponse(27);
637 #endif
638 }
639 
640 GDBRemoteCommunication::PacketResult
641 GDBRemoteCommunicationServerCommon::Handle_vFile_Size(
642     StringExtractorGDBRemote &packet) {
643   packet.SetFilePos(::strlen("vFile:size:"));
644   std::string path;
645   packet.GetHexByteString(path);
646   if (!path.empty()) {
647     lldb::user_id_t retcode =
648         FileSystem::GetFileSize(FileSpec(path.c_str(), false));
649     StreamString response;
650     response.PutChar('F');
651     response.PutHex64(retcode);
652     if (retcode == UINT64_MAX) {
653       response.PutChar(',');
654       response.PutHex64(
655           retcode); // TODO: replace with Host::GetSyswideErrorCode()
656     }
657     return SendPacketNoLock(response.GetString());
658   }
659   return SendErrorResponse(22);
660 }
661 
662 GDBRemoteCommunication::PacketResult
663 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(
664     StringExtractorGDBRemote &packet) {
665   packet.SetFilePos(::strlen("vFile:mode:"));
666   std::string path;
667   packet.GetHexByteString(path);
668   if (!path.empty()) {
669     Error error;
670     const uint32_t mode = File::GetPermissions(FileSpec{path, true}, error);
671     StreamString response;
672     response.Printf("F%u", mode);
673     if (mode == 0 || error.Fail())
674       response.Printf(",%i", (int)error.GetError());
675     return SendPacketNoLock(response.GetString());
676   }
677   return SendErrorResponse(23);
678 }
679 
680 GDBRemoteCommunication::PacketResult
681 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(
682     StringExtractorGDBRemote &packet) {
683   packet.SetFilePos(::strlen("vFile:exists:"));
684   std::string path;
685   packet.GetHexByteString(path);
686   if (!path.empty()) {
687     bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
688     StreamString response;
689     response.PutChar('F');
690     response.PutChar(',');
691     if (retcode)
692       response.PutChar('1');
693     else
694       response.PutChar('0');
695     return SendPacketNoLock(response.GetString());
696   }
697   return SendErrorResponse(24);
698 }
699 
700 GDBRemoteCommunication::PacketResult
701 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(
702     StringExtractorGDBRemote &packet) {
703   packet.SetFilePos(::strlen("vFile:symlink:"));
704   std::string dst, src;
705   packet.GetHexByteStringTerminatedBy(dst, ',');
706   packet.GetChar(); // Skip ',' char
707   packet.GetHexByteString(src);
708   Error error = FileSystem::Symlink(FileSpec{src, true}, FileSpec{dst, false});
709   StreamString response;
710   response.Printf("F%u,%u", error.GetError(), error.GetError());
711   return SendPacketNoLock(response.GetString());
712 }
713 
714 GDBRemoteCommunication::PacketResult
715 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(
716     StringExtractorGDBRemote &packet) {
717   packet.SetFilePos(::strlen("vFile:unlink:"));
718   std::string path;
719   packet.GetHexByteString(path);
720   Error error = FileSystem::Unlink(FileSpec{path, true});
721   StreamString response;
722   response.Printf("F%u,%u", error.GetError(), error.GetError());
723   return SendPacketNoLock(response.GetString());
724 }
725 
726 GDBRemoteCommunication::PacketResult
727 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(
728     StringExtractorGDBRemote &packet) {
729   packet.SetFilePos(::strlen("qPlatform_shell:"));
730   std::string path;
731   std::string working_dir;
732   packet.GetHexByteStringTerminatedBy(path, ',');
733   if (!path.empty()) {
734     if (packet.GetChar() == ',') {
735       // FIXME: add timeout to qPlatform_shell packet
736       // uint32_t timeout = packet.GetHexMaxU32(false, 32);
737       uint32_t timeout = 10;
738       if (packet.GetChar() == ',')
739         packet.GetHexByteString(working_dir);
740       int status, signo;
741       std::string output;
742       Error err =
743           Host::RunShellCommand(path.c_str(), FileSpec{working_dir, true},
744                                 &status, &signo, &output, timeout);
745       StreamGDBRemote response;
746       if (err.Fail()) {
747         response.PutCString("F,");
748         response.PutHex32(UINT32_MAX);
749       } else {
750         response.PutCString("F,");
751         response.PutHex32(status);
752         response.PutChar(',');
753         response.PutHex32(signo);
754         response.PutChar(',');
755         response.PutEscapedBytes(output.c_str(), output.size());
756       }
757       return SendPacketNoLock(response.GetString());
758     }
759   }
760   return SendErrorResponse(24);
761 }
762 
763 GDBRemoteCommunication::PacketResult
764 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(
765     StringExtractorGDBRemote &packet) {
766   return SendUnimplementedResponse(
767       "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");
768 }
769 
770 GDBRemoteCommunication::PacketResult
771 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(
772     StringExtractorGDBRemote &packet) {
773   packet.SetFilePos(::strlen("vFile:MD5:"));
774   std::string path;
775   packet.GetHexByteString(path);
776   if (!path.empty()) {
777     uint64_t a, b;
778     StreamGDBRemote response;
779     if (!FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b)) {
780       response.PutCString("F,");
781       response.PutCString("x");
782     } else {
783       response.PutCString("F,");
784       response.PutHex64(a);
785       response.PutHex64(b);
786     }
787     return SendPacketNoLock(response.GetString());
788   }
789   return SendErrorResponse(25);
790 }
791 
792 GDBRemoteCommunication::PacketResult
793 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(
794     StringExtractorGDBRemote &packet) {
795   packet.SetFilePos(::strlen("qPlatform_mkdir:"));
796   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
797   if (packet.GetChar() == ',') {
798     std::string path;
799     packet.GetHexByteString(path);
800     Error error = FileSystem::MakeDirectory(FileSpec{path, false}, mode);
801 
802     StreamGDBRemote response;
803     response.Printf("F%u", error.GetError());
804 
805     return SendPacketNoLock(response.GetString());
806   }
807   return SendErrorResponse(20);
808 }
809 
810 GDBRemoteCommunication::PacketResult
811 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(
812     StringExtractorGDBRemote &packet) {
813   packet.SetFilePos(::strlen("qPlatform_chmod:"));
814 
815   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
816   if (packet.GetChar() == ',') {
817     std::string path;
818     packet.GetHexByteString(path);
819     Error error = FileSystem::SetFilePermissions(FileSpec{path, true}, mode);
820 
821     StreamGDBRemote response;
822     response.Printf("F%u", error.GetError());
823 
824     return SendPacketNoLock(response.GetString());
825   }
826   return SendErrorResponse(19);
827 }
828 
829 GDBRemoteCommunication::PacketResult
830 GDBRemoteCommunicationServerCommon::Handle_qSupported(
831     StringExtractorGDBRemote &packet) {
832   StreamGDBRemote response;
833 
834   // Features common to lldb-platform and llgs.
835   uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet
836                                          // size--debugger can always use less
837   response.Printf("PacketSize=%x", max_packet_size);
838 
839   response.PutCString(";QStartNoAckMode+");
840   response.PutCString(";QThreadSuffixSupported+");
841   response.PutCString(";QListThreadsInStopReply+");
842   response.PutCString(";qEcho+");
843 #if defined(__linux__)
844   response.PutCString(";qXfer:auxv:read+");
845 #endif
846 
847   return SendPacketNoLock(response.GetString());
848 }
849 
850 GDBRemoteCommunication::PacketResult
851 GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported(
852     StringExtractorGDBRemote &packet) {
853   m_thread_suffix_supported = true;
854   return SendOKResponse();
855 }
856 
857 GDBRemoteCommunication::PacketResult
858 GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply(
859     StringExtractorGDBRemote &packet) {
860   m_list_threads_in_stop_reply = true;
861   return SendOKResponse();
862 }
863 
864 GDBRemoteCommunication::PacketResult
865 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
866     StringExtractorGDBRemote &packet) {
867   packet.SetFilePos(::strlen("QSetDetachOnError:"));
868   if (packet.GetU32(0))
869     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
870   else
871     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
872   return SendOKResponse();
873 }
874 
875 GDBRemoteCommunication::PacketResult
876 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
877     StringExtractorGDBRemote &packet) {
878   // Send response first before changing m_send_acks to we ack this packet
879   PacketResult packet_result = SendOKResponse();
880   m_send_acks = false;
881   return packet_result;
882 }
883 
884 GDBRemoteCommunication::PacketResult
885 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
886     StringExtractorGDBRemote &packet) {
887   packet.SetFilePos(::strlen("QSetSTDIN:"));
888   FileAction file_action;
889   std::string path;
890   packet.GetHexByteString(path);
891   const bool read = true;
892   const bool write = false;
893   if (file_action.Open(STDIN_FILENO, FileSpec{path, false}, read, write)) {
894     m_process_launch_info.AppendFileAction(file_action);
895     return SendOKResponse();
896   }
897   return SendErrorResponse(15);
898 }
899 
900 GDBRemoteCommunication::PacketResult
901 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
902     StringExtractorGDBRemote &packet) {
903   packet.SetFilePos(::strlen("QSetSTDOUT:"));
904   FileAction file_action;
905   std::string path;
906   packet.GetHexByteString(path);
907   const bool read = false;
908   const bool write = true;
909   if (file_action.Open(STDOUT_FILENO, FileSpec{path, false}, read, write)) {
910     m_process_launch_info.AppendFileAction(file_action);
911     return SendOKResponse();
912   }
913   return SendErrorResponse(16);
914 }
915 
916 GDBRemoteCommunication::PacketResult
917 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
918     StringExtractorGDBRemote &packet) {
919   packet.SetFilePos(::strlen("QSetSTDERR:"));
920   FileAction file_action;
921   std::string path;
922   packet.GetHexByteString(path);
923   const bool read = false;
924   const bool write = true;
925   if (file_action.Open(STDERR_FILENO, FileSpec{path, false}, read, write)) {
926     m_process_launch_info.AppendFileAction(file_action);
927     return SendOKResponse();
928   }
929   return SendErrorResponse(17);
930 }
931 
932 GDBRemoteCommunication::PacketResult
933 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
934     StringExtractorGDBRemote &packet) {
935   if (m_process_launch_error.Success())
936     return SendOKResponse();
937   StreamString response;
938   response.PutChar('E');
939   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
940   return SendPacketNoLock(response.GetString());
941 }
942 
943 GDBRemoteCommunication::PacketResult
944 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
945     StringExtractorGDBRemote &packet) {
946   packet.SetFilePos(::strlen("QEnvironment:"));
947   const uint32_t bytes_left = packet.GetBytesLeft();
948   if (bytes_left > 0) {
949     m_process_launch_info.GetEnvironmentEntries().AppendArgument(
950         llvm::StringRef::withNullAsEmpty(packet.Peek()));
951     return SendOKResponse();
952   }
953   return SendErrorResponse(12);
954 }
955 
956 GDBRemoteCommunication::PacketResult
957 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
958     StringExtractorGDBRemote &packet) {
959   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
960   const uint32_t bytes_left = packet.GetBytesLeft();
961   if (bytes_left > 0) {
962     std::string str;
963     packet.GetHexByteString(str);
964     m_process_launch_info.GetEnvironmentEntries().AppendArgument(str);
965     return SendOKResponse();
966   }
967   return SendErrorResponse(12);
968 }
969 
970 GDBRemoteCommunication::PacketResult
971 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
972     StringExtractorGDBRemote &packet) {
973   packet.SetFilePos(::strlen("QLaunchArch:"));
974   const uint32_t bytes_left = packet.GetBytesLeft();
975   if (bytes_left > 0) {
976     const char *arch_triple = packet.Peek();
977     ArchSpec arch_spec(arch_triple, NULL);
978     m_process_launch_info.SetArchitecture(arch_spec);
979     return SendOKResponse();
980   }
981   return SendErrorResponse(13);
982 }
983 
984 GDBRemoteCommunication::PacketResult
985 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {
986   // The 'A' packet is the most over designed packet ever here with
987   // redundant argument indexes, redundant argument lengths and needed hex
988   // encoded argument string values. Really all that is needed is a comma
989   // separated hex encoded argument value list, but we will stay true to the
990   // documented version of the 'A' packet here...
991 
992   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
993   int actual_arg_index = 0;
994 
995   packet.SetFilePos(1); // Skip the 'A'
996   bool success = true;
997   while (success && packet.GetBytesLeft() > 0) {
998     // Decode the decimal argument string length. This length is the
999     // number of hex nibbles in the argument string value.
1000     const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1001     if (arg_len == UINT32_MAX)
1002       success = false;
1003     else {
1004       // Make sure the argument hex string length is followed by a comma
1005       if (packet.GetChar() != ',')
1006         success = false;
1007       else {
1008         // Decode the argument index. We ignore this really because
1009         // who would really send down the arguments in a random order???
1010         const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1011         if (arg_idx == UINT32_MAX)
1012           success = false;
1013         else {
1014           // Make sure the argument index is followed by a comma
1015           if (packet.GetChar() != ',')
1016             success = false;
1017           else {
1018             // Decode the argument string value from hex bytes
1019             // back into a UTF8 string and make sure the length
1020             // matches the one supplied in the packet
1021             std::string arg;
1022             if (packet.GetHexByteStringFixedLength(arg, arg_len) !=
1023                 (arg_len / 2))
1024               success = false;
1025             else {
1026               // If there are any bytes left
1027               if (packet.GetBytesLeft()) {
1028                 if (packet.GetChar() != ',')
1029                   success = false;
1030               }
1031 
1032               if (success) {
1033                 if (arg_idx == 0)
1034                   m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(),
1035                                                                     false);
1036                 m_process_launch_info.GetArguments().AppendArgument(arg);
1037                 if (log)
1038                   log->Printf("LLGSPacketHandler::%s added arg %d: \"%s\"",
1039                               __FUNCTION__, actual_arg_index, arg.c_str());
1040                 ++actual_arg_index;
1041               }
1042             }
1043           }
1044         }
1045       }
1046     }
1047   }
1048 
1049   if (success) {
1050     m_process_launch_error = LaunchProcess();
1051     if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1052       return SendOKResponse();
1053     } else {
1054       Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1055       if (log)
1056         log->Printf("LLGSPacketHandler::%s failed to launch exe: %s",
1057                     __FUNCTION__, m_process_launch_error.AsCString());
1058     }
1059   }
1060   return SendErrorResponse(8);
1061 }
1062 
1063 GDBRemoteCommunication::PacketResult
1064 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1065     StringExtractorGDBRemote &packet) {
1066   // Just echo back the exact same packet for qEcho...
1067   return SendPacketNoLock(packet.GetStringRef());
1068 }
1069 
1070 GDBRemoteCommunication::PacketResult
1071 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1072     StringExtractorGDBRemote &packet) {
1073   packet.SetFilePos(::strlen("qModuleInfo:"));
1074 
1075   std::string module_path;
1076   packet.GetHexByteStringTerminatedBy(module_path, ';');
1077   if (module_path.empty())
1078     return SendErrorResponse(1);
1079 
1080   if (packet.GetChar() != ';')
1081     return SendErrorResponse(2);
1082 
1083   std::string triple;
1084   packet.GetHexByteString(triple);
1085 
1086   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1087   if (!matched_module_spec.GetFileSpec())
1088     return SendErrorResponse(3);
1089 
1090   const auto file_offset = matched_module_spec.GetObjectOffset();
1091   const auto file_size = matched_module_spec.GetObjectSize();
1092   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1093 
1094   StreamGDBRemote response;
1095 
1096   if (uuid_str.empty()) {
1097     std::string md5_hash;
1098     if (!FileSystem::CalculateMD5AsString(matched_module_spec.GetFileSpec(),
1099                                           file_offset, file_size, md5_hash))
1100       return SendErrorResponse(5);
1101     response.PutCString("md5:");
1102     response.PutCStringAsRawHex8(md5_hash.c_str());
1103   } else {
1104     response.PutCString("uuid:");
1105     response.PutCStringAsRawHex8(uuid_str.c_str());
1106   }
1107   response.PutChar(';');
1108 
1109   const auto &module_arch = matched_module_spec.GetArchitecture();
1110   response.PutCString("triple:");
1111   response.PutCStringAsRawHex8(module_arch.GetTriple().getTriple().c_str());
1112   response.PutChar(';');
1113 
1114   response.PutCString("file_path:");
1115   response.PutCStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1116   response.PutChar(';');
1117   response.PutCString("file_offset:");
1118   response.PutHex64(file_offset);
1119   response.PutChar(';');
1120   response.PutCString("file_size:");
1121   response.PutHex64(file_size);
1122   response.PutChar(';');
1123 
1124   return SendPacketNoLock(response.GetString());
1125 }
1126 
1127 GDBRemoteCommunication::PacketResult
1128 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1129     StringExtractorGDBRemote &packet) {
1130   packet.SetFilePos(::strlen("jModulesInfo:"));
1131 
1132   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1133   if (!object_sp)
1134     return SendErrorResponse(1);
1135 
1136   StructuredData::Array *packet_array = object_sp->GetAsArray();
1137   if (!packet_array)
1138     return SendErrorResponse(2);
1139 
1140   JSONArray::SP response_array_sp = std::make_shared<JSONArray>();
1141   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1142     StructuredData::Dictionary *query =
1143         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1144     if (!query)
1145       continue;
1146     std::string file, triple;
1147     if (!query->GetValueForKeyAsString("file", file) ||
1148         !query->GetValueForKeyAsString("triple", triple))
1149       continue;
1150 
1151     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1152     if (!matched_module_spec.GetFileSpec())
1153       continue;
1154 
1155     const auto file_offset = matched_module_spec.GetObjectOffset();
1156     const auto file_size = matched_module_spec.GetObjectSize();
1157     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1158 
1159     if (uuid_str.empty())
1160       continue;
1161 
1162     JSONObject::SP response = std::make_shared<JSONObject>();
1163     response_array_sp->AppendObject(response);
1164     response->SetObject("uuid", std::make_shared<JSONString>(uuid_str));
1165     response->SetObject(
1166         "triple",
1167         std::make_shared<JSONString>(
1168             matched_module_spec.GetArchitecture().GetTriple().getTriple()));
1169     response->SetObject("file_path",
1170                         std::make_shared<JSONString>(
1171                             matched_module_spec.GetFileSpec().GetPath()));
1172     response->SetObject("file_offset",
1173                         std::make_shared<JSONNumber>(file_offset));
1174     response->SetObject("file_size", std::make_shared<JSONNumber>(file_size));
1175   }
1176 
1177   StreamString response;
1178   response_array_sp->Write(response);
1179   StreamGDBRemote escaped_response;
1180   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1181   return SendPacketNoLock(escaped_response.GetString());
1182 }
1183 
1184 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1185     const ProcessInstanceInfo &proc_info, StreamString &response) {
1186   response.Printf(
1187       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1188       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1189       proc_info.GetUserID(), proc_info.GetGroupID(),
1190       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1191   response.PutCString("name:");
1192   response.PutCStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1193   response.PutChar(';');
1194   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1195   if (proc_arch.IsValid()) {
1196     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1197     response.PutCString("triple:");
1198     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1199     response.PutChar(';');
1200   }
1201 }
1202 
1203 void GDBRemoteCommunicationServerCommon::
1204     CreateProcessInfoResponse_DebugServerStyle(
1205         const ProcessInstanceInfo &proc_info, StreamString &response) {
1206   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1207                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1208                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1209                   proc_info.GetUserID(), proc_info.GetGroupID(),
1210                   proc_info.GetEffectiveUserID(),
1211                   proc_info.GetEffectiveGroupID());
1212 
1213   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1214   if (proc_arch.IsValid()) {
1215     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1216 #if defined(__APPLE__)
1217     // We'll send cputype/cpusubtype.
1218     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1219     if (cpu_type != 0)
1220       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1221 
1222     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1223     if (cpu_subtype != 0)
1224       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1225 
1226     const std::string vendor = proc_triple.getVendorName();
1227     if (!vendor.empty())
1228       response.Printf("vendor:%s;", vendor.c_str());
1229 #else
1230     // We'll send the triple.
1231     response.PutCString("triple:");
1232     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1233     response.PutChar(';');
1234 #endif
1235     std::string ostype = proc_triple.getOSName();
1236     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1237     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1238       switch (proc_triple.getArch()) {
1239       case llvm::Triple::arm:
1240       case llvm::Triple::thumb:
1241       case llvm::Triple::aarch64:
1242         ostype = "ios";
1243         break;
1244       default:
1245         // No change.
1246         break;
1247       }
1248     }
1249     response.Printf("ostype:%s;", ostype.c_str());
1250 
1251     switch (proc_arch.GetByteOrder()) {
1252     case lldb::eByteOrderLittle:
1253       response.PutCString("endian:little;");
1254       break;
1255     case lldb::eByteOrderBig:
1256       response.PutCString("endian:big;");
1257       break;
1258     case lldb::eByteOrderPDP:
1259       response.PutCString("endian:pdp;");
1260       break;
1261     default:
1262       // Nothing.
1263       break;
1264     }
1265     // In case of MIPS64, pointer size is depend on ELF ABI
1266     // For N32 the pointer size is 4 and for N64 it is 8
1267     std::string abi = proc_arch.GetTargetABI();
1268     if (!abi.empty())
1269       response.Printf("elf_abi:%s;", abi.c_str());
1270     response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());
1271   }
1272 }
1273 
1274 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(
1275     const std::string &module_path, const ArchSpec &arch) {
1276 #ifdef __ANDROID__
1277   return HostInfoAndroid::ResolveLibraryPath(module_path, arch);
1278 #else
1279   return FileSpec(module_path.c_str(), true);
1280 #endif
1281 }
1282 
1283 ModuleSpec GDBRemoteCommunicationServerCommon::GetModuleInfo(
1284     const std::string &module_path, const std::string &triple) {
1285   ArchSpec arch(triple.c_str());
1286 
1287   const FileSpec req_module_path_spec(module_path.c_str(), true);
1288   const FileSpec module_path_spec =
1289       FindModuleFile(req_module_path_spec.GetPath(), arch);
1290   const ModuleSpec module_spec(module_path_spec, arch);
1291 
1292   ModuleSpecList module_specs;
1293   if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0,
1294                                            module_specs))
1295     return ModuleSpec();
1296 
1297   ModuleSpec matched_module_spec;
1298   if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))
1299     return ModuleSpec();
1300 
1301   return matched_module_spec;
1302 }
1303