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, false);
362       } else if (key.equals("name_match")) {
363         NameMatchType name_match =
364             llvm::StringSwitch<NameMatchType>(value)
365                 .Case("equals", eNameMatchEquals)
366                 .Case("starts_with", eNameMatchStartsWith)
367                 .Case("ends_with", eNameMatchEndsWith)
368                 .Case("contains", eNameMatchContains)
369                 .Case("regex", eNameMatchRegularExpression)
370                 .Default(eNameMatchIgnore);
371         match_info.SetNameMatchType(name_match);
372         if (name_match == eNameMatchIgnore)
373           return SendErrorResponse(2);
374       } else if (key.equals("pid")) {
375         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
376         if (value.getAsInteger(0, pid))
377           return SendErrorResponse(2);
378         match_info.GetProcessInfo().SetProcessID(pid);
379       } else if (key.equals("parent_pid")) {
380         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
381         if (value.getAsInteger(0, pid))
382           return SendErrorResponse(2);
383         match_info.GetProcessInfo().SetParentProcessID(pid);
384       } else if (key.equals("uid")) {
385         uint32_t uid = UINT32_MAX;
386         if (value.getAsInteger(0, uid))
387           return SendErrorResponse(2);
388         match_info.GetProcessInfo().SetUserID(uid);
389       } else if (key.equals("gid")) {
390         uint32_t gid = UINT32_MAX;
391         if (value.getAsInteger(0, gid))
392           return SendErrorResponse(2);
393         match_info.GetProcessInfo().SetGroupID(gid);
394       } else if (key.equals("euid")) {
395         uint32_t uid = UINT32_MAX;
396         if (value.getAsInteger(0, uid))
397           return SendErrorResponse(2);
398         match_info.GetProcessInfo().SetEffectiveUserID(uid);
399       } else if (key.equals("egid")) {
400         uint32_t gid = UINT32_MAX;
401         if (value.getAsInteger(0, gid))
402           return SendErrorResponse(2);
403         match_info.GetProcessInfo().SetEffectiveGroupID(gid);
404       } else if (key.equals("all_users")) {
405         match_info.SetMatchAllUsers(
406             Args::StringToBoolean(value, false, &success));
407       } else if (key.equals("triple")) {
408         match_info.GetProcessInfo().GetArchitecture().SetTriple(
409             value.str().c_str(), NULL);
410       } else {
411         success = false;
412       }
413 
414       if (!success)
415         return SendErrorResponse(2);
416     }
417   }
418 
419   if (Host::FindProcesses(match_info, m_proc_infos)) {
420     // We found something, return the first item by calling the get
421     // subsequent process info packet handler...
422     return Handle_qsProcessInfo(packet);
423   }
424   return SendErrorResponse(3);
425 }
426 
427 GDBRemoteCommunication::PacketResult
428 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(
429     StringExtractorGDBRemote &packet) {
430   if (m_proc_infos_index < m_proc_infos.GetSize()) {
431     StreamString response;
432     CreateProcessInfoResponse(
433         m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
434     ++m_proc_infos_index;
435     return SendPacketNoLock(response.GetString());
436   }
437   return SendErrorResponse(4);
438 }
439 
440 GDBRemoteCommunication::PacketResult
441 GDBRemoteCommunicationServerCommon::Handle_qUserName(
442     StringExtractorGDBRemote &packet) {
443 #if !defined(LLDB_DISABLE_POSIX)
444   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
445   if (log)
446     log->Printf("GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);
447 
448   // Packet format: "qUserName:%i" where %i is the uid
449   packet.SetFilePos(::strlen("qUserName:"));
450   uint32_t uid = packet.GetU32(UINT32_MAX);
451   if (uid != UINT32_MAX) {
452     std::string name;
453     if (HostInfo::LookupUserName(uid, name)) {
454       StreamString response;
455       response.PutCStringAsRawHex8(name.c_str());
456       return SendPacketNoLock(response.GetString());
457     }
458   }
459   if (log)
460     log->Printf("GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);
461 #endif
462   return SendErrorResponse(5);
463 }
464 
465 GDBRemoteCommunication::PacketResult
466 GDBRemoteCommunicationServerCommon::Handle_qGroupName(
467     StringExtractorGDBRemote &packet) {
468 #if !defined(LLDB_DISABLE_POSIX)
469   // Packet format: "qGroupName:%i" where %i is the gid
470   packet.SetFilePos(::strlen("qGroupName:"));
471   uint32_t gid = packet.GetU32(UINT32_MAX);
472   if (gid != UINT32_MAX) {
473     std::string name;
474     if (HostInfo::LookupGroupName(gid, name)) {
475       StreamString response;
476       response.PutCStringAsRawHex8(name.c_str());
477       return SendPacketNoLock(response.GetString());
478     }
479   }
480 #endif
481   return SendErrorResponse(6);
482 }
483 
484 GDBRemoteCommunication::PacketResult
485 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(
486     StringExtractorGDBRemote &packet) {
487   packet.SetFilePos(::strlen("qSpeedTest:"));
488 
489   llvm::StringRef key;
490   llvm::StringRef value;
491   bool success = packet.GetNameColonValue(key, value);
492   if (success && key.equals("response_size")) {
493     uint32_t response_size = 0;
494     if (!value.getAsInteger(0, response_size)) {
495       if (response_size == 0)
496         return SendOKResponse();
497       StreamString response;
498       uint32_t bytes_left = response_size;
499       response.PutCString("data:");
500       while (bytes_left > 0) {
501         if (bytes_left >= 26) {
502           response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
503           bytes_left -= 26;
504         } else {
505           response.Printf("%*.*s;", bytes_left, bytes_left,
506                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
507           bytes_left = 0;
508         }
509       }
510       return SendPacketNoLock(response.GetString());
511     }
512   }
513   return SendErrorResponse(7);
514 }
515 
516 GDBRemoteCommunication::PacketResult
517 GDBRemoteCommunicationServerCommon::Handle_vFile_Open(
518     StringExtractorGDBRemote &packet) {
519   packet.SetFilePos(::strlen("vFile:open:"));
520   std::string path;
521   packet.GetHexByteStringTerminatedBy(path, ',');
522   if (!path.empty()) {
523     if (packet.GetChar() == ',') {
524       uint32_t flags =
525           File::ConvertOpenOptionsForPOSIXOpen(packet.GetHexMaxU32(false, 0));
526       if (packet.GetChar() == ',') {
527         mode_t mode = packet.GetHexMaxU32(false, 0600);
528         Error error;
529         const FileSpec path_spec{path, true};
530         int fd = ::open(path_spec.GetCString(), flags, mode);
531         const int save_errno = fd == -1 ? errno : 0;
532         StreamString response;
533         response.PutChar('F');
534         response.Printf("%i", fd);
535         if (save_errno)
536           response.Printf(",%i", save_errno);
537         return SendPacketNoLock(response.GetString());
538       }
539     }
540   }
541   return SendErrorResponse(18);
542 }
543 
544 GDBRemoteCommunication::PacketResult
545 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
546     StringExtractorGDBRemote &packet) {
547   packet.SetFilePos(::strlen("vFile:close:"));
548   int fd = packet.GetS32(-1);
549   Error error;
550   int err = -1;
551   int save_errno = 0;
552   if (fd >= 0) {
553     err = close(fd);
554     save_errno = err == -1 ? errno : 0;
555   } else {
556     save_errno = EINVAL;
557   }
558   StreamString response;
559   response.PutChar('F');
560   response.Printf("%i", err);
561   if (save_errno)
562     response.Printf(",%i", save_errno);
563   return SendPacketNoLock(response.GetString());
564 }
565 
566 GDBRemoteCommunication::PacketResult
567 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
568     StringExtractorGDBRemote &packet) {
569 #ifdef _WIN32
570   // Not implemented on Windows
571   return SendUnimplementedResponse(
572       "GDBRemoteCommunicationServerCommon::Handle_vFile_pRead() unimplemented");
573 #else
574   StreamGDBRemote response;
575   packet.SetFilePos(::strlen("vFile:pread:"));
576   int fd = packet.GetS32(-1);
577   if (packet.GetChar() == ',') {
578     uint64_t count = packet.GetU64(UINT64_MAX);
579     if (packet.GetChar() == ',') {
580       uint64_t offset = packet.GetU64(UINT32_MAX);
581       if (count == UINT64_MAX) {
582         response.Printf("F-1:%i", EINVAL);
583         return SendPacketNoLock(response.GetString());
584       }
585 
586       std::string buffer(count, 0);
587       const ssize_t bytes_read = ::pread(fd, &buffer[0], buffer.size(), offset);
588       const int save_errno = bytes_read == -1 ? errno : 0;
589       response.PutChar('F');
590       response.Printf("%zi", bytes_read);
591       if (save_errno)
592         response.Printf(",%i", save_errno);
593       else {
594         response.PutChar(';');
595         response.PutEscapedBytes(&buffer[0], bytes_read);
596       }
597       return SendPacketNoLock(response.GetString());
598     }
599   }
600   return SendErrorResponse(21);
601 
602 #endif
603 }
604 
605 GDBRemoteCommunication::PacketResult
606 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
607     StringExtractorGDBRemote &packet) {
608 #ifdef _WIN32
609   return SendUnimplementedResponse("GDBRemoteCommunicationServerCommon::Handle_"
610                                    "vFile_pWrite() unimplemented");
611 #else
612   packet.SetFilePos(::strlen("vFile:pwrite:"));
613 
614   StreamGDBRemote response;
615   response.PutChar('F');
616 
617   int fd = packet.GetU32(UINT32_MAX);
618   if (packet.GetChar() == ',') {
619     off_t offset = packet.GetU64(UINT32_MAX);
620     if (packet.GetChar() == ',') {
621       std::string buffer;
622       if (packet.GetEscapedBinaryData(buffer)) {
623         const ssize_t bytes_written =
624             ::pwrite(fd, buffer.data(), buffer.size(), offset);
625         const int save_errno = bytes_written == -1 ? errno : 0;
626         response.Printf("%zi", bytes_written);
627         if (save_errno)
628           response.Printf(",%i", save_errno);
629       } else {
630         response.Printf("-1,%i", EINVAL);
631       }
632       return SendPacketNoLock(response.GetString());
633     }
634   }
635   return SendErrorResponse(27);
636 #endif
637 }
638 
639 GDBRemoteCommunication::PacketResult
640 GDBRemoteCommunicationServerCommon::Handle_vFile_Size(
641     StringExtractorGDBRemote &packet) {
642   packet.SetFilePos(::strlen("vFile:size:"));
643   std::string path;
644   packet.GetHexByteString(path);
645   if (!path.empty()) {
646     lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path, false));
647     StreamString response;
648     response.PutChar('F');
649     response.PutHex64(retcode);
650     if (retcode == UINT64_MAX) {
651       response.PutChar(',');
652       response.PutHex64(
653           retcode); // TODO: replace with Host::GetSyswideErrorCode()
654     }
655     return SendPacketNoLock(response.GetString());
656   }
657   return SendErrorResponse(22);
658 }
659 
660 GDBRemoteCommunication::PacketResult
661 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(
662     StringExtractorGDBRemote &packet) {
663   packet.SetFilePos(::strlen("vFile:mode:"));
664   std::string path;
665   packet.GetHexByteString(path);
666   if (!path.empty()) {
667     Error error;
668     const uint32_t mode = File::GetPermissions(FileSpec{path, true}, error);
669     StreamString response;
670     response.Printf("F%u", mode);
671     if (mode == 0 || error.Fail())
672       response.Printf(",%i", (int)error.GetError());
673     return SendPacketNoLock(response.GetString());
674   }
675   return SendErrorResponse(23);
676 }
677 
678 GDBRemoteCommunication::PacketResult
679 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(
680     StringExtractorGDBRemote &packet) {
681   packet.SetFilePos(::strlen("vFile:exists:"));
682   std::string path;
683   packet.GetHexByteString(path);
684   if (!path.empty()) {
685     bool retcode = FileSystem::GetFileExists(FileSpec(path, false));
686     StreamString response;
687     response.PutChar('F');
688     response.PutChar(',');
689     if (retcode)
690       response.PutChar('1');
691     else
692       response.PutChar('0');
693     return SendPacketNoLock(response.GetString());
694   }
695   return SendErrorResponse(24);
696 }
697 
698 GDBRemoteCommunication::PacketResult
699 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(
700     StringExtractorGDBRemote &packet) {
701   packet.SetFilePos(::strlen("vFile:symlink:"));
702   std::string dst, src;
703   packet.GetHexByteStringTerminatedBy(dst, ',');
704   packet.GetChar(); // Skip ',' char
705   packet.GetHexByteString(src);
706   Error error = FileSystem::Symlink(FileSpec{src, true}, FileSpec{dst, false});
707   StreamString response;
708   response.Printf("F%u,%u", error.GetError(), error.GetError());
709   return SendPacketNoLock(response.GetString());
710 }
711 
712 GDBRemoteCommunication::PacketResult
713 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(
714     StringExtractorGDBRemote &packet) {
715   packet.SetFilePos(::strlen("vFile:unlink:"));
716   std::string path;
717   packet.GetHexByteString(path);
718   Error error = FileSystem::Unlink(FileSpec{path, true});
719   StreamString response;
720   response.Printf("F%u,%u", error.GetError(), error.GetError());
721   return SendPacketNoLock(response.GetString());
722 }
723 
724 GDBRemoteCommunication::PacketResult
725 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(
726     StringExtractorGDBRemote &packet) {
727   packet.SetFilePos(::strlen("qPlatform_shell:"));
728   std::string path;
729   std::string working_dir;
730   packet.GetHexByteStringTerminatedBy(path, ',');
731   if (!path.empty()) {
732     if (packet.GetChar() == ',') {
733       // FIXME: add timeout to qPlatform_shell packet
734       // uint32_t timeout = packet.GetHexMaxU32(false, 32);
735       uint32_t timeout = 10;
736       if (packet.GetChar() == ',')
737         packet.GetHexByteString(working_dir);
738       int status, signo;
739       std::string output;
740       Error err =
741           Host::RunShellCommand(path.c_str(), FileSpec{working_dir, true},
742                                 &status, &signo, &output, timeout);
743       StreamGDBRemote response;
744       if (err.Fail()) {
745         response.PutCString("F,");
746         response.PutHex32(UINT32_MAX);
747       } else {
748         response.PutCString("F,");
749         response.PutHex32(status);
750         response.PutChar(',');
751         response.PutHex32(signo);
752         response.PutChar(',');
753         response.PutEscapedBytes(output.c_str(), output.size());
754       }
755       return SendPacketNoLock(response.GetString());
756     }
757   }
758   return SendErrorResponse(24);
759 }
760 
761 GDBRemoteCommunication::PacketResult
762 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(
763     StringExtractorGDBRemote &packet) {
764   return SendUnimplementedResponse(
765       "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");
766 }
767 
768 GDBRemoteCommunication::PacketResult
769 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(
770     StringExtractorGDBRemote &packet) {
771   packet.SetFilePos(::strlen("vFile:MD5:"));
772   std::string path;
773   packet.GetHexByteString(path);
774   if (!path.empty()) {
775     uint64_t a, b;
776     StreamGDBRemote response;
777     if (!FileSystem::CalculateMD5(FileSpec(path, false), a, b)) {
778       response.PutCString("F,");
779       response.PutCString("x");
780     } else {
781       response.PutCString("F,");
782       response.PutHex64(a);
783       response.PutHex64(b);
784     }
785     return SendPacketNoLock(response.GetString());
786   }
787   return SendErrorResponse(25);
788 }
789 
790 GDBRemoteCommunication::PacketResult
791 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(
792     StringExtractorGDBRemote &packet) {
793   packet.SetFilePos(::strlen("qPlatform_mkdir:"));
794   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
795   if (packet.GetChar() == ',') {
796     std::string path;
797     packet.GetHexByteString(path);
798     Error error = FileSystem::MakeDirectory(FileSpec{path, false}, mode);
799 
800     StreamGDBRemote response;
801     response.Printf("F%u", error.GetError());
802 
803     return SendPacketNoLock(response.GetString());
804   }
805   return SendErrorResponse(20);
806 }
807 
808 GDBRemoteCommunication::PacketResult
809 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(
810     StringExtractorGDBRemote &packet) {
811   packet.SetFilePos(::strlen("qPlatform_chmod:"));
812 
813   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
814   if (packet.GetChar() == ',') {
815     std::string path;
816     packet.GetHexByteString(path);
817     Error error = FileSystem::SetFilePermissions(FileSpec{path, true}, mode);
818 
819     StreamGDBRemote response;
820     response.Printf("F%u", error.GetError());
821 
822     return SendPacketNoLock(response.GetString());
823   }
824   return SendErrorResponse(19);
825 }
826 
827 GDBRemoteCommunication::PacketResult
828 GDBRemoteCommunicationServerCommon::Handle_qSupported(
829     StringExtractorGDBRemote &packet) {
830   StreamGDBRemote response;
831 
832   // Features common to lldb-platform and llgs.
833   uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet
834                                          // size--debugger can always use less
835   response.Printf("PacketSize=%x", max_packet_size);
836 
837   response.PutCString(";QStartNoAckMode+");
838   response.PutCString(";QThreadSuffixSupported+");
839   response.PutCString(";QListThreadsInStopReply+");
840   response.PutCString(";qEcho+");
841 #if defined(__linux__)
842   response.PutCString(";qXfer:auxv:read+");
843 #endif
844 
845   return SendPacketNoLock(response.GetString());
846 }
847 
848 GDBRemoteCommunication::PacketResult
849 GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported(
850     StringExtractorGDBRemote &packet) {
851   m_thread_suffix_supported = true;
852   return SendOKResponse();
853 }
854 
855 GDBRemoteCommunication::PacketResult
856 GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply(
857     StringExtractorGDBRemote &packet) {
858   m_list_threads_in_stop_reply = true;
859   return SendOKResponse();
860 }
861 
862 GDBRemoteCommunication::PacketResult
863 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
864     StringExtractorGDBRemote &packet) {
865   packet.SetFilePos(::strlen("QSetDetachOnError:"));
866   if (packet.GetU32(0))
867     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
868   else
869     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
870   return SendOKResponse();
871 }
872 
873 GDBRemoteCommunication::PacketResult
874 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
875     StringExtractorGDBRemote &packet) {
876   // Send response first before changing m_send_acks to we ack this packet
877   PacketResult packet_result = SendOKResponse();
878   m_send_acks = false;
879   return packet_result;
880 }
881 
882 GDBRemoteCommunication::PacketResult
883 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
884     StringExtractorGDBRemote &packet) {
885   packet.SetFilePos(::strlen("QSetSTDIN:"));
886   FileAction file_action;
887   std::string path;
888   packet.GetHexByteString(path);
889   const bool read = true;
890   const bool write = false;
891   if (file_action.Open(STDIN_FILENO, FileSpec{path, false}, read, write)) {
892     m_process_launch_info.AppendFileAction(file_action);
893     return SendOKResponse();
894   }
895   return SendErrorResponse(15);
896 }
897 
898 GDBRemoteCommunication::PacketResult
899 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
900     StringExtractorGDBRemote &packet) {
901   packet.SetFilePos(::strlen("QSetSTDOUT:"));
902   FileAction file_action;
903   std::string path;
904   packet.GetHexByteString(path);
905   const bool read = false;
906   const bool write = true;
907   if (file_action.Open(STDOUT_FILENO, FileSpec{path, false}, read, write)) {
908     m_process_launch_info.AppendFileAction(file_action);
909     return SendOKResponse();
910   }
911   return SendErrorResponse(16);
912 }
913 
914 GDBRemoteCommunication::PacketResult
915 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
916     StringExtractorGDBRemote &packet) {
917   packet.SetFilePos(::strlen("QSetSTDERR:"));
918   FileAction file_action;
919   std::string path;
920   packet.GetHexByteString(path);
921   const bool read = false;
922   const bool write = true;
923   if (file_action.Open(STDERR_FILENO, FileSpec{path, false}, read, write)) {
924     m_process_launch_info.AppendFileAction(file_action);
925     return SendOKResponse();
926   }
927   return SendErrorResponse(17);
928 }
929 
930 GDBRemoteCommunication::PacketResult
931 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
932     StringExtractorGDBRemote &packet) {
933   if (m_process_launch_error.Success())
934     return SendOKResponse();
935   StreamString response;
936   response.PutChar('E');
937   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
938   return SendPacketNoLock(response.GetString());
939 }
940 
941 GDBRemoteCommunication::PacketResult
942 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
943     StringExtractorGDBRemote &packet) {
944   packet.SetFilePos(::strlen("QEnvironment:"));
945   const uint32_t bytes_left = packet.GetBytesLeft();
946   if (bytes_left > 0) {
947     m_process_launch_info.GetEnvironmentEntries().AppendArgument(
948         llvm::StringRef::withNullAsEmpty(packet.Peek()));
949     return SendOKResponse();
950   }
951   return SendErrorResponse(12);
952 }
953 
954 GDBRemoteCommunication::PacketResult
955 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
956     StringExtractorGDBRemote &packet) {
957   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
958   const uint32_t bytes_left = packet.GetBytesLeft();
959   if (bytes_left > 0) {
960     std::string str;
961     packet.GetHexByteString(str);
962     m_process_launch_info.GetEnvironmentEntries().AppendArgument(str);
963     return SendOKResponse();
964   }
965   return SendErrorResponse(12);
966 }
967 
968 GDBRemoteCommunication::PacketResult
969 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
970     StringExtractorGDBRemote &packet) {
971   packet.SetFilePos(::strlen("QLaunchArch:"));
972   const uint32_t bytes_left = packet.GetBytesLeft();
973   if (bytes_left > 0) {
974     const char *arch_triple = packet.Peek();
975     ArchSpec arch_spec(arch_triple, NULL);
976     m_process_launch_info.SetArchitecture(arch_spec);
977     return SendOKResponse();
978   }
979   return SendErrorResponse(13);
980 }
981 
982 GDBRemoteCommunication::PacketResult
983 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {
984   // The 'A' packet is the most over designed packet ever here with
985   // redundant argument indexes, redundant argument lengths and needed hex
986   // encoded argument string values. Really all that is needed is a comma
987   // separated hex encoded argument value list, but we will stay true to the
988   // documented version of the 'A' packet here...
989 
990   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
991   int actual_arg_index = 0;
992 
993   packet.SetFilePos(1); // Skip the 'A'
994   bool success = true;
995   while (success && packet.GetBytesLeft() > 0) {
996     // Decode the decimal argument string length. This length is the
997     // number of hex nibbles in the argument string value.
998     const uint32_t arg_len = packet.GetU32(UINT32_MAX);
999     if (arg_len == UINT32_MAX)
1000       success = false;
1001     else {
1002       // Make sure the argument hex string length is followed by a comma
1003       if (packet.GetChar() != ',')
1004         success = false;
1005       else {
1006         // Decode the argument index. We ignore this really because
1007         // who would really send down the arguments in a random order???
1008         const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1009         if (arg_idx == UINT32_MAX)
1010           success = false;
1011         else {
1012           // Make sure the argument index is followed by a comma
1013           if (packet.GetChar() != ',')
1014             success = false;
1015           else {
1016             // Decode the argument string value from hex bytes
1017             // back into a UTF8 string and make sure the length
1018             // matches the one supplied in the packet
1019             std::string arg;
1020             if (packet.GetHexByteStringFixedLength(arg, arg_len) !=
1021                 (arg_len / 2))
1022               success = false;
1023             else {
1024               // If there are any bytes left
1025               if (packet.GetBytesLeft()) {
1026                 if (packet.GetChar() != ',')
1027                   success = false;
1028               }
1029 
1030               if (success) {
1031                 if (arg_idx == 0)
1032                   m_process_launch_info.GetExecutableFile().SetFile(arg, false);
1033                 m_process_launch_info.GetArguments().AppendArgument(arg);
1034                 if (log)
1035                   log->Printf("LLGSPacketHandler::%s added arg %d: \"%s\"",
1036                               __FUNCTION__, actual_arg_index, arg.c_str());
1037                 ++actual_arg_index;
1038               }
1039             }
1040           }
1041         }
1042       }
1043     }
1044   }
1045 
1046   if (success) {
1047     m_process_launch_error = LaunchProcess();
1048     if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1049       return SendOKResponse();
1050     } else {
1051       Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1052       if (log)
1053         log->Printf("LLGSPacketHandler::%s failed to launch exe: %s",
1054                     __FUNCTION__, m_process_launch_error.AsCString());
1055     }
1056   }
1057   return SendErrorResponse(8);
1058 }
1059 
1060 GDBRemoteCommunication::PacketResult
1061 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1062     StringExtractorGDBRemote &packet) {
1063   // Just echo back the exact same packet for qEcho...
1064   return SendPacketNoLock(packet.GetStringRef());
1065 }
1066 
1067 GDBRemoteCommunication::PacketResult
1068 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1069     StringExtractorGDBRemote &packet) {
1070   packet.SetFilePos(::strlen("qModuleInfo:"));
1071 
1072   std::string module_path;
1073   packet.GetHexByteStringTerminatedBy(module_path, ';');
1074   if (module_path.empty())
1075     return SendErrorResponse(1);
1076 
1077   if (packet.GetChar() != ';')
1078     return SendErrorResponse(2);
1079 
1080   std::string triple;
1081   packet.GetHexByteString(triple);
1082 
1083   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1084   if (!matched_module_spec.GetFileSpec())
1085     return SendErrorResponse(3);
1086 
1087   const auto file_offset = matched_module_spec.GetObjectOffset();
1088   const auto file_size = matched_module_spec.GetObjectSize();
1089   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1090 
1091   StreamGDBRemote response;
1092 
1093   if (uuid_str.empty()) {
1094     std::string md5_hash;
1095     if (!FileSystem::CalculateMD5AsString(matched_module_spec.GetFileSpec(),
1096                                           file_offset, file_size, md5_hash))
1097       return SendErrorResponse(5);
1098     response.PutCString("md5:");
1099     response.PutCStringAsRawHex8(md5_hash.c_str());
1100   } else {
1101     response.PutCString("uuid:");
1102     response.PutCStringAsRawHex8(uuid_str.c_str());
1103   }
1104   response.PutChar(';');
1105 
1106   const auto &module_arch = matched_module_spec.GetArchitecture();
1107   response.PutCString("triple:");
1108   response.PutCStringAsRawHex8(module_arch.GetTriple().getTriple().c_str());
1109   response.PutChar(';');
1110 
1111   response.PutCString("file_path:");
1112   response.PutCStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1113   response.PutChar(';');
1114   response.PutCString("file_offset:");
1115   response.PutHex64(file_offset);
1116   response.PutChar(';');
1117   response.PutCString("file_size:");
1118   response.PutHex64(file_size);
1119   response.PutChar(';');
1120 
1121   return SendPacketNoLock(response.GetString());
1122 }
1123 
1124 GDBRemoteCommunication::PacketResult
1125 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1126     StringExtractorGDBRemote &packet) {
1127   packet.SetFilePos(::strlen("jModulesInfo:"));
1128 
1129   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1130   if (!object_sp)
1131     return SendErrorResponse(1);
1132 
1133   StructuredData::Array *packet_array = object_sp->GetAsArray();
1134   if (!packet_array)
1135     return SendErrorResponse(2);
1136 
1137   JSONArray::SP response_array_sp = std::make_shared<JSONArray>();
1138   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1139     StructuredData::Dictionary *query =
1140         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1141     if (!query)
1142       continue;
1143     std::string file, triple;
1144     if (!query->GetValueForKeyAsString("file", file) ||
1145         !query->GetValueForKeyAsString("triple", triple))
1146       continue;
1147 
1148     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1149     if (!matched_module_spec.GetFileSpec())
1150       continue;
1151 
1152     const auto file_offset = matched_module_spec.GetObjectOffset();
1153     const auto file_size = matched_module_spec.GetObjectSize();
1154     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1155 
1156     if (uuid_str.empty())
1157       continue;
1158 
1159     JSONObject::SP response = std::make_shared<JSONObject>();
1160     response_array_sp->AppendObject(response);
1161     response->SetObject("uuid", std::make_shared<JSONString>(uuid_str));
1162     response->SetObject(
1163         "triple",
1164         std::make_shared<JSONString>(
1165             matched_module_spec.GetArchitecture().GetTriple().getTriple()));
1166     response->SetObject("file_path",
1167                         std::make_shared<JSONString>(
1168                             matched_module_spec.GetFileSpec().GetPath()));
1169     response->SetObject("file_offset",
1170                         std::make_shared<JSONNumber>(file_offset));
1171     response->SetObject("file_size", std::make_shared<JSONNumber>(file_size));
1172   }
1173 
1174   StreamString response;
1175   response_array_sp->Write(response);
1176   StreamGDBRemote escaped_response;
1177   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1178   return SendPacketNoLock(escaped_response.GetString());
1179 }
1180 
1181 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1182     const ProcessInstanceInfo &proc_info, StreamString &response) {
1183   response.Printf(
1184       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1185       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1186       proc_info.GetUserID(), proc_info.GetGroupID(),
1187       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1188   response.PutCString("name:");
1189   response.PutCStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1190   response.PutChar(';');
1191   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1192   if (proc_arch.IsValid()) {
1193     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1194     response.PutCString("triple:");
1195     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1196     response.PutChar(';');
1197   }
1198 }
1199 
1200 void GDBRemoteCommunicationServerCommon::
1201     CreateProcessInfoResponse_DebugServerStyle(
1202         const ProcessInstanceInfo &proc_info, StreamString &response) {
1203   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1204                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1205                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1206                   proc_info.GetUserID(), proc_info.GetGroupID(),
1207                   proc_info.GetEffectiveUserID(),
1208                   proc_info.GetEffectiveGroupID());
1209 
1210   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1211   if (proc_arch.IsValid()) {
1212     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1213 #if defined(__APPLE__)
1214     // We'll send cputype/cpusubtype.
1215     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1216     if (cpu_type != 0)
1217       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1218 
1219     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1220     if (cpu_subtype != 0)
1221       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1222 
1223     const std::string vendor = proc_triple.getVendorName();
1224     if (!vendor.empty())
1225       response.Printf("vendor:%s;", vendor.c_str());
1226 #else
1227     // We'll send the triple.
1228     response.PutCString("triple:");
1229     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1230     response.PutChar(';');
1231 #endif
1232     std::string ostype = proc_triple.getOSName();
1233     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1234     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1235       switch (proc_triple.getArch()) {
1236       case llvm::Triple::arm:
1237       case llvm::Triple::thumb:
1238       case llvm::Triple::aarch64:
1239         ostype = "ios";
1240         break;
1241       default:
1242         // No change.
1243         break;
1244       }
1245     }
1246     response.Printf("ostype:%s;", ostype.c_str());
1247 
1248     switch (proc_arch.GetByteOrder()) {
1249     case lldb::eByteOrderLittle:
1250       response.PutCString("endian:little;");
1251       break;
1252     case lldb::eByteOrderBig:
1253       response.PutCString("endian:big;");
1254       break;
1255     case lldb::eByteOrderPDP:
1256       response.PutCString("endian:pdp;");
1257       break;
1258     default:
1259       // Nothing.
1260       break;
1261     }
1262     // In case of MIPS64, pointer size is depend on ELF ABI
1263     // For N32 the pointer size is 4 and for N64 it is 8
1264     std::string abi = proc_arch.GetTargetABI();
1265     if (!abi.empty())
1266       response.Printf("elf_abi:%s;", abi.c_str());
1267     response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());
1268   }
1269 }
1270 
1271 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(
1272     const std::string &module_path, const ArchSpec &arch) {
1273 #ifdef __ANDROID__
1274   return HostInfoAndroid::ResolveLibraryPath(module_path, arch);
1275 #else
1276   return FileSpec(module_path, true);
1277 #endif
1278 }
1279 
1280 ModuleSpec GDBRemoteCommunicationServerCommon::GetModuleInfo(
1281     const std::string &module_path, const std::string &triple) {
1282   ArchSpec arch(triple.c_str());
1283 
1284   const FileSpec req_module_path_spec(module_path, true);
1285   const FileSpec module_path_spec =
1286       FindModuleFile(req_module_path_spec.GetPath(), arch);
1287   const ModuleSpec module_spec(module_path_spec, arch);
1288 
1289   ModuleSpecList module_specs;
1290   if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0,
1291                                            module_specs))
1292     return ModuleSpec();
1293 
1294   ModuleSpec matched_module_spec;
1295   if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))
1296     return ModuleSpec();
1297 
1298   return matched_module_spec;
1299 }
1300