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/ModuleSpec.h"
26 #include "lldb/Host/Config.h"
27 #include "lldb/Host/File.h"
28 #include "lldb/Host/FileSystem.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Host/HostInfo.h"
31 #include "lldb/Interpreter/OptionArgParser.h"
32 #include "lldb/Symbol/ObjectFile.h"
33 #include "lldb/Target/FileAction.h"
34 #include "lldb/Target/Platform.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Utility/Endian.h"
37 #include "lldb/Utility/JSON.h"
38 #include "lldb/Utility/Log.h"
39 #include "lldb/Utility/SafeMachO.h"
40 #include "lldb/Utility/StreamGDBRemote.h"
41 #include "lldb/Utility/StreamString.h"
42 #include "llvm/ADT/Triple.h"
43 
44 // Project includes
45 #include "ProcessGDBRemoteLog.h"
46 #include "lldb/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 == llvm::MachO::CPU_TYPE_ARM
223       || cpu == llvm::MachO::CPU_TYPE_ARM64) {
224 // Indicate the OS type.
225 #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
226     response.PutCString("ostype:tvos;");
227 #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
228     response.PutCString("ostype:watchos;");
229 #elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
230     response.PutCString("ostype:bridgeos;");
231 #else
232     response.PutCString("ostype:ios;");
233 #endif
234 
235     // On arm, we use "synchronous" watchpoints which means the exception is
236     // delivered before the instruction executes.
237     response.PutCString("watchpoint_exceptions_received:before;");
238   } else {
239     response.PutCString("ostype:macosx;");
240     response.Printf("watchpoint_exceptions_received:after;");
241   }
242 
243 #else
244   if (host_arch.GetMachine() == llvm::Triple::aarch64 ||
245       host_arch.GetMachine() == llvm::Triple::aarch64_be ||
246       host_arch.GetMachine() == llvm::Triple::arm ||
247       host_arch.GetMachine() == llvm::Triple::armeb ||
248       host_arch.GetMachine() == llvm::Triple::mips64 ||
249       host_arch.GetMachine() == llvm::Triple::mips64el ||
250       host_arch.GetMachine() == llvm::Triple::mips ||
251       host_arch.GetMachine() == llvm::Triple::mipsel)
252     response.Printf("watchpoint_exceptions_received:before;");
253   else
254     response.Printf("watchpoint_exceptions_received:after;");
255 #endif
256 
257   switch (endian::InlHostByteOrder()) {
258   case eByteOrderBig:
259     response.PutCString("endian:big;");
260     break;
261   case eByteOrderLittle:
262     response.PutCString("endian:little;");
263     break;
264   case eByteOrderPDP:
265     response.PutCString("endian:pdp;");
266     break;
267   default:
268     response.PutCString("endian:unknown;");
269     break;
270   }
271 
272   uint32_t major = UINT32_MAX;
273   uint32_t minor = UINT32_MAX;
274   uint32_t update = UINT32_MAX;
275   if (HostInfo::GetOSVersion(major, minor, update)) {
276     if (major != UINT32_MAX) {
277       response.Printf("os_version:%u", major);
278       if (minor != UINT32_MAX) {
279         response.Printf(".%u", minor);
280         if (update != UINT32_MAX)
281           response.Printf(".%u", update);
282       }
283       response.PutChar(';');
284     }
285   }
286 
287   std::string s;
288   if (HostInfo::GetOSBuildString(s)) {
289     response.PutCString("os_build:");
290     response.PutCStringAsRawHex8(s.c_str());
291     response.PutChar(';');
292   }
293   if (HostInfo::GetOSKernelDescription(s)) {
294     response.PutCString("os_kernel:");
295     response.PutCStringAsRawHex8(s.c_str());
296     response.PutChar(';');
297   }
298 
299 #if defined(__APPLE__)
300 
301 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
302   // For iOS devices, we are connected through a USB Mux so we never pretend to
303   // actually have a hostname as far as the remote lldb that is connecting to
304   // this lldb-platform is concerned
305   response.PutCString("hostname:");
306   response.PutCStringAsRawHex8("127.0.0.1");
307   response.PutChar(';');
308 #else  // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
309   if (HostInfo::GetHostname(s)) {
310     response.PutCString("hostname:");
311     response.PutCStringAsRawHex8(s.c_str());
312     response.PutChar(';');
313   }
314 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
315 
316 #else  // #if defined(__APPLE__)
317   if (HostInfo::GetHostname(s)) {
318     response.PutCString("hostname:");
319     response.PutCStringAsRawHex8(s.c_str());
320     response.PutChar(';');
321   }
322 #endif // #if defined(__APPLE__)
323 
324   if (g_default_packet_timeout_sec > 0)
325     response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec);
326 
327   return SendPacketNoLock(response.GetString());
328 }
329 
330 GDBRemoteCommunication::PacketResult
331 GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID(
332     StringExtractorGDBRemote &packet) {
333   // Packet format: "qProcessInfoPID:%i" where %i is the pid
334   packet.SetFilePos(::strlen("qProcessInfoPID:"));
335   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID);
336   if (pid != LLDB_INVALID_PROCESS_ID) {
337     ProcessInstanceInfo proc_info;
338     if (Host::GetProcessInfo(pid, proc_info)) {
339       StreamString response;
340       CreateProcessInfoResponse(proc_info, response);
341       return SendPacketNoLock(response.GetString());
342     }
343   }
344   return SendErrorResponse(1);
345 }
346 
347 GDBRemoteCommunication::PacketResult
348 GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo(
349     StringExtractorGDBRemote &packet) {
350   m_proc_infos_index = 0;
351   m_proc_infos.Clear();
352 
353   ProcessInstanceInfoMatch match_info;
354   packet.SetFilePos(::strlen("qfProcessInfo"));
355   if (packet.GetChar() == ':') {
356     llvm::StringRef key;
357     llvm::StringRef value;
358     while (packet.GetNameColonValue(key, value)) {
359       bool success = true;
360       if (key.equals("name")) {
361         StringExtractor extractor(value);
362         std::string file;
363         extractor.GetHexByteString(file);
364         match_info.GetProcessInfo().GetExecutableFile().SetFile(file, false);
365       } else if (key.equals("name_match")) {
366         NameMatch name_match = llvm::StringSwitch<NameMatch>(value)
367                                    .Case("equals", NameMatch::Equals)
368                                    .Case("starts_with", NameMatch::StartsWith)
369                                    .Case("ends_with", NameMatch::EndsWith)
370                                    .Case("contains", NameMatch::Contains)
371                                    .Case("regex", NameMatch::RegularExpression)
372                                    .Default(NameMatch::Ignore);
373         match_info.SetNameMatchType(name_match);
374         if (name_match == NameMatch::Ignore)
375           return SendErrorResponse(2);
376       } else if (key.equals("pid")) {
377         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
378         if (value.getAsInteger(0, pid))
379           return SendErrorResponse(2);
380         match_info.GetProcessInfo().SetProcessID(pid);
381       } else if (key.equals("parent_pid")) {
382         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
383         if (value.getAsInteger(0, pid))
384           return SendErrorResponse(2);
385         match_info.GetProcessInfo().SetParentProcessID(pid);
386       } else if (key.equals("uid")) {
387         uint32_t uid = UINT32_MAX;
388         if (value.getAsInteger(0, uid))
389           return SendErrorResponse(2);
390         match_info.GetProcessInfo().SetUserID(uid);
391       } else if (key.equals("gid")) {
392         uint32_t gid = UINT32_MAX;
393         if (value.getAsInteger(0, gid))
394           return SendErrorResponse(2);
395         match_info.GetProcessInfo().SetGroupID(gid);
396       } else if (key.equals("euid")) {
397         uint32_t uid = UINT32_MAX;
398         if (value.getAsInteger(0, uid))
399           return SendErrorResponse(2);
400         match_info.GetProcessInfo().SetEffectiveUserID(uid);
401       } else if (key.equals("egid")) {
402         uint32_t gid = UINT32_MAX;
403         if (value.getAsInteger(0, gid))
404           return SendErrorResponse(2);
405         match_info.GetProcessInfo().SetEffectiveGroupID(gid);
406       } else if (key.equals("all_users")) {
407         match_info.SetMatchAllUsers(
408             OptionArgParser::ToBoolean(value, false, &success));
409       } else if (key.equals("triple")) {
410         match_info.GetProcessInfo().GetArchitecture() =
411             HostInfo::GetAugmentedArchSpec(value);
412       } else {
413         success = false;
414       }
415 
416       if (!success)
417         return SendErrorResponse(2);
418     }
419   }
420 
421   if (Host::FindProcesses(match_info, m_proc_infos)) {
422     // We found something, return the first item by calling the get subsequent
423     // process info packet handler...
424     return Handle_qsProcessInfo(packet);
425   }
426   return SendErrorResponse(3);
427 }
428 
429 GDBRemoteCommunication::PacketResult
430 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(
431     StringExtractorGDBRemote &packet) {
432   if (m_proc_infos_index < m_proc_infos.GetSize()) {
433     StreamString response;
434     CreateProcessInfoResponse(
435         m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
436     ++m_proc_infos_index;
437     return SendPacketNoLock(response.GetString());
438   }
439   return SendErrorResponse(4);
440 }
441 
442 GDBRemoteCommunication::PacketResult
443 GDBRemoteCommunicationServerCommon::Handle_qUserName(
444     StringExtractorGDBRemote &packet) {
445 #if !defined(LLDB_DISABLE_POSIX)
446   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
447   if (log)
448     log->Printf("GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);
449 
450   // Packet format: "qUserName:%i" where %i is the uid
451   packet.SetFilePos(::strlen("qUserName:"));
452   uint32_t uid = packet.GetU32(UINT32_MAX);
453   if (uid != UINT32_MAX) {
454     std::string name;
455     if (HostInfo::LookupUserName(uid, name)) {
456       StreamString response;
457       response.PutCStringAsRawHex8(name.c_str());
458       return SendPacketNoLock(response.GetString());
459     }
460   }
461   if (log)
462     log->Printf("GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);
463 #endif
464   return SendErrorResponse(5);
465 }
466 
467 GDBRemoteCommunication::PacketResult
468 GDBRemoteCommunicationServerCommon::Handle_qGroupName(
469     StringExtractorGDBRemote &packet) {
470 #if !defined(LLDB_DISABLE_POSIX)
471   // Packet format: "qGroupName:%i" where %i is the gid
472   packet.SetFilePos(::strlen("qGroupName:"));
473   uint32_t gid = packet.GetU32(UINT32_MAX);
474   if (gid != UINT32_MAX) {
475     std::string name;
476     if (HostInfo::LookupGroupName(gid, name)) {
477       StreamString response;
478       response.PutCStringAsRawHex8(name.c_str());
479       return SendPacketNoLock(response.GetString());
480     }
481   }
482 #endif
483   return SendErrorResponse(6);
484 }
485 
486 GDBRemoteCommunication::PacketResult
487 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(
488     StringExtractorGDBRemote &packet) {
489   packet.SetFilePos(::strlen("qSpeedTest:"));
490 
491   llvm::StringRef key;
492   llvm::StringRef value;
493   bool success = packet.GetNameColonValue(key, value);
494   if (success && key.equals("response_size")) {
495     uint32_t response_size = 0;
496     if (!value.getAsInteger(0, response_size)) {
497       if (response_size == 0)
498         return SendOKResponse();
499       StreamString response;
500       uint32_t bytes_left = response_size;
501       response.PutCString("data:");
502       while (bytes_left > 0) {
503         if (bytes_left >= 26) {
504           response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
505           bytes_left -= 26;
506         } else {
507           response.Printf("%*.*s;", bytes_left, bytes_left,
508                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
509           bytes_left = 0;
510         }
511       }
512       return SendPacketNoLock(response.GetString());
513     }
514   }
515   return SendErrorResponse(7);
516 }
517 
518 GDBRemoteCommunication::PacketResult
519 GDBRemoteCommunicationServerCommon::Handle_vFile_Open(
520     StringExtractorGDBRemote &packet) {
521   packet.SetFilePos(::strlen("vFile:open:"));
522   std::string path;
523   packet.GetHexByteStringTerminatedBy(path, ',');
524   if (!path.empty()) {
525     if (packet.GetChar() == ',') {
526       uint32_t flags =
527           File::ConvertOpenOptionsForPOSIXOpen(packet.GetHexMaxU32(false, 0));
528       if (packet.GetChar() == ',') {
529         mode_t mode = packet.GetHexMaxU32(false, 0600);
530         Status error;
531         const FileSpec path_spec{path, true};
532         int fd = ::open(path_spec.GetCString(), flags, mode);
533         const int save_errno = fd == -1 ? errno : 0;
534         StreamString response;
535         response.PutChar('F');
536         response.Printf("%i", fd);
537         if (save_errno)
538           response.Printf(",%i", save_errno);
539         return SendPacketNoLock(response.GetString());
540       }
541     }
542   }
543   return SendErrorResponse(18);
544 }
545 
546 GDBRemoteCommunication::PacketResult
547 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
548     StringExtractorGDBRemote &packet) {
549   packet.SetFilePos(::strlen("vFile:close:"));
550   int fd = packet.GetS32(-1);
551   Status error;
552   int err = -1;
553   int save_errno = 0;
554   if (fd >= 0) {
555     err = close(fd);
556     save_errno = err == -1 ? errno : 0;
557   } else {
558     save_errno = EINVAL;
559   }
560   StreamString response;
561   response.PutChar('F');
562   response.Printf("%i", err);
563   if (save_errno)
564     response.Printf(",%i", save_errno);
565   return SendPacketNoLock(response.GetString());
566 }
567 
568 GDBRemoteCommunication::PacketResult
569 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
570     StringExtractorGDBRemote &packet) {
571 #ifdef _WIN32
572   // Not implemented on Windows
573   return SendUnimplementedResponse(
574       "GDBRemoteCommunicationServerCommon::Handle_vFile_pRead() unimplemented");
575 #else
576   StreamGDBRemote response;
577   packet.SetFilePos(::strlen("vFile:pread:"));
578   int fd = packet.GetS32(-1);
579   if (packet.GetChar() == ',') {
580     uint64_t count = packet.GetU64(UINT64_MAX);
581     if (packet.GetChar() == ',') {
582       uint64_t offset = packet.GetU64(UINT32_MAX);
583       if (count == UINT64_MAX) {
584         response.Printf("F-1:%i", EINVAL);
585         return SendPacketNoLock(response.GetString());
586       }
587 
588       std::string buffer(count, 0);
589       const ssize_t bytes_read = ::pread(fd, &buffer[0], buffer.size(), offset);
590       const int save_errno = bytes_read == -1 ? errno : 0;
591       response.PutChar('F');
592       response.Printf("%zi", bytes_read);
593       if (save_errno)
594         response.Printf(",%i", save_errno);
595       else {
596         response.PutChar(';');
597         response.PutEscapedBytes(&buffer[0], bytes_read);
598       }
599       return SendPacketNoLock(response.GetString());
600     }
601   }
602   return SendErrorResponse(21);
603 
604 #endif
605 }
606 
607 GDBRemoteCommunication::PacketResult
608 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
609     StringExtractorGDBRemote &packet) {
610 #ifdef _WIN32
611   return SendUnimplementedResponse("GDBRemoteCommunicationServerCommon::Handle_"
612                                    "vFile_pWrite() unimplemented");
613 #else
614   packet.SetFilePos(::strlen("vFile:pwrite:"));
615 
616   StreamGDBRemote response;
617   response.PutChar('F');
618 
619   int fd = packet.GetU32(UINT32_MAX);
620   if (packet.GetChar() == ',') {
621     off_t offset = packet.GetU64(UINT32_MAX);
622     if (packet.GetChar() == ',') {
623       std::string buffer;
624       if (packet.GetEscapedBinaryData(buffer)) {
625         const ssize_t bytes_written =
626             ::pwrite(fd, buffer.data(), buffer.size(), offset);
627         const int save_errno = bytes_written == -1 ? errno : 0;
628         response.Printf("%zi", bytes_written);
629         if (save_errno)
630           response.Printf(",%i", save_errno);
631       } else {
632         response.Printf("-1,%i", EINVAL);
633       }
634       return SendPacketNoLock(response.GetString());
635     }
636   }
637   return SendErrorResponse(27);
638 #endif
639 }
640 
641 GDBRemoteCommunication::PacketResult
642 GDBRemoteCommunicationServerCommon::Handle_vFile_Size(
643     StringExtractorGDBRemote &packet) {
644   packet.SetFilePos(::strlen("vFile:size:"));
645   std::string path;
646   packet.GetHexByteString(path);
647   if (!path.empty()) {
648     uint64_t Size;
649     if (llvm::sys::fs::file_size(path, Size))
650       return SendErrorResponse(5);
651     StreamString response;
652     response.PutChar('F');
653     response.PutHex64(Size);
654     if (Size == UINT64_MAX) {
655       response.PutChar(',');
656       response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode()
657     }
658     return SendPacketNoLock(response.GetString());
659   }
660   return SendErrorResponse(22);
661 }
662 
663 GDBRemoteCommunication::PacketResult
664 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(
665     StringExtractorGDBRemote &packet) {
666   packet.SetFilePos(::strlen("vFile:mode:"));
667   std::string path;
668   packet.GetHexByteString(path);
669   if (!path.empty()) {
670     Status error;
671     const uint32_t mode = File::GetPermissions(FileSpec{path, true}, error);
672     StreamString response;
673     response.Printf("F%u", mode);
674     if (mode == 0 || error.Fail())
675       response.Printf(",%i", (int)error.GetError());
676     return SendPacketNoLock(response.GetString());
677   }
678   return SendErrorResponse(23);
679 }
680 
681 GDBRemoteCommunication::PacketResult
682 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(
683     StringExtractorGDBRemote &packet) {
684   packet.SetFilePos(::strlen("vFile:exists:"));
685   std::string path;
686   packet.GetHexByteString(path);
687   if (!path.empty()) {
688     bool retcode = llvm::sys::fs::exists(path);
689     StreamString response;
690     response.PutChar('F');
691     response.PutChar(',');
692     if (retcode)
693       response.PutChar('1');
694     else
695       response.PutChar('0');
696     return SendPacketNoLock(response.GetString());
697   }
698   return SendErrorResponse(24);
699 }
700 
701 GDBRemoteCommunication::PacketResult
702 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(
703     StringExtractorGDBRemote &packet) {
704   packet.SetFilePos(::strlen("vFile:symlink:"));
705   std::string dst, src;
706   packet.GetHexByteStringTerminatedBy(dst, ',');
707   packet.GetChar(); // Skip ',' char
708   packet.GetHexByteString(src);
709   Status error = FileSystem::Symlink(FileSpec{src, true}, FileSpec{dst, false});
710   StreamString response;
711   response.Printf("F%u,%u", error.GetError(), error.GetError());
712   return SendPacketNoLock(response.GetString());
713 }
714 
715 GDBRemoteCommunication::PacketResult
716 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(
717     StringExtractorGDBRemote &packet) {
718   packet.SetFilePos(::strlen("vFile:unlink:"));
719   std::string path;
720   packet.GetHexByteString(path);
721   Status error(llvm::sys::fs::remove(path));
722   StreamString response;
723   response.Printf("F%u,%u", error.GetError(), error.GetError());
724   return SendPacketNoLock(response.GetString());
725 }
726 
727 GDBRemoteCommunication::PacketResult
728 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(
729     StringExtractorGDBRemote &packet) {
730   packet.SetFilePos(::strlen("qPlatform_shell:"));
731   std::string path;
732   std::string working_dir;
733   packet.GetHexByteStringTerminatedBy(path, ',');
734   if (!path.empty()) {
735     if (packet.GetChar() == ',') {
736       // FIXME: add timeout to qPlatform_shell packet
737       // uint32_t timeout = packet.GetHexMaxU32(false, 32);
738       if (packet.GetChar() == ',')
739         packet.GetHexByteString(working_dir);
740       int status, signo;
741       std::string output;
742       Status err = Host::RunShellCommand(
743           path.c_str(), FileSpec{working_dir, true}, &status, &signo, &output,
744           std::chrono::seconds(10));
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     StreamGDBRemote response;
778     auto Result = llvm::sys::fs::md5_contents(path);
779     if (!Result) {
780       response.PutCString("F,");
781       response.PutCString("x");
782     } else {
783       response.PutCString("F,");
784       response.PutHex64(Result->low());
785       response.PutHex64(Result->high());
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     Status error(llvm::sys::fs::create_directory(path, 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   auto perms =
816       static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX));
817   if (packet.GetChar() == ',') {
818     std::string path;
819     packet.GetHexByteString(path);
820     Status error(llvm::sys::fs::setPermissions(path, perms));
821 
822     StreamGDBRemote response;
823     response.Printf("F%u", error.GetError());
824 
825     return SendPacketNoLock(response.GetString());
826   }
827   return SendErrorResponse(19);
828 }
829 
830 GDBRemoteCommunication::PacketResult
831 GDBRemoteCommunicationServerCommon::Handle_qSupported(
832     StringExtractorGDBRemote &packet) {
833   StreamGDBRemote response;
834 
835   // Features common to lldb-platform and llgs.
836   uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet
837                                          // size--debugger can always use less
838   response.Printf("PacketSize=%x", max_packet_size);
839 
840   response.PutCString(";QStartNoAckMode+");
841   response.PutCString(";QThreadSuffixSupported+");
842   response.PutCString(";QListThreadsInStopReply+");
843   response.PutCString(";qEcho+");
844 #if defined(__linux__) || defined(__NetBSD__)
845   response.PutCString(";QPassSignals+");
846   response.PutCString(";qXfer:auxv:read+");
847 #endif
848 
849   return SendPacketNoLock(response.GetString());
850 }
851 
852 GDBRemoteCommunication::PacketResult
853 GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported(
854     StringExtractorGDBRemote &packet) {
855   m_thread_suffix_supported = true;
856   return SendOKResponse();
857 }
858 
859 GDBRemoteCommunication::PacketResult
860 GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply(
861     StringExtractorGDBRemote &packet) {
862   m_list_threads_in_stop_reply = true;
863   return SendOKResponse();
864 }
865 
866 GDBRemoteCommunication::PacketResult
867 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
868     StringExtractorGDBRemote &packet) {
869   packet.SetFilePos(::strlen("QSetDetachOnError:"));
870   if (packet.GetU32(0))
871     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
872   else
873     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
874   return SendOKResponse();
875 }
876 
877 GDBRemoteCommunication::PacketResult
878 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
879     StringExtractorGDBRemote &packet) {
880   // Send response first before changing m_send_acks to we ack this packet
881   PacketResult packet_result = SendOKResponse();
882   m_send_acks = false;
883   return packet_result;
884 }
885 
886 GDBRemoteCommunication::PacketResult
887 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
888     StringExtractorGDBRemote &packet) {
889   packet.SetFilePos(::strlen("QSetSTDIN:"));
890   FileAction file_action;
891   std::string path;
892   packet.GetHexByteString(path);
893   const bool read = true;
894   const bool write = false;
895   if (file_action.Open(STDIN_FILENO, FileSpec{path, false}, read, write)) {
896     m_process_launch_info.AppendFileAction(file_action);
897     return SendOKResponse();
898   }
899   return SendErrorResponse(15);
900 }
901 
902 GDBRemoteCommunication::PacketResult
903 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
904     StringExtractorGDBRemote &packet) {
905   packet.SetFilePos(::strlen("QSetSTDOUT:"));
906   FileAction file_action;
907   std::string path;
908   packet.GetHexByteString(path);
909   const bool read = false;
910   const bool write = true;
911   if (file_action.Open(STDOUT_FILENO, FileSpec{path, false}, read, write)) {
912     m_process_launch_info.AppendFileAction(file_action);
913     return SendOKResponse();
914   }
915   return SendErrorResponse(16);
916 }
917 
918 GDBRemoteCommunication::PacketResult
919 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
920     StringExtractorGDBRemote &packet) {
921   packet.SetFilePos(::strlen("QSetSTDERR:"));
922   FileAction file_action;
923   std::string path;
924   packet.GetHexByteString(path);
925   const bool read = false;
926   const bool write = true;
927   if (file_action.Open(STDERR_FILENO, FileSpec{path, false}, read, write)) {
928     m_process_launch_info.AppendFileAction(file_action);
929     return SendOKResponse();
930   }
931   return SendErrorResponse(17);
932 }
933 
934 GDBRemoteCommunication::PacketResult
935 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
936     StringExtractorGDBRemote &packet) {
937   if (m_process_launch_error.Success())
938     return SendOKResponse();
939   StreamString response;
940   response.PutChar('E');
941   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
942   return SendPacketNoLock(response.GetString());
943 }
944 
945 GDBRemoteCommunication::PacketResult
946 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
947     StringExtractorGDBRemote &packet) {
948   packet.SetFilePos(::strlen("QEnvironment:"));
949   const uint32_t bytes_left = packet.GetBytesLeft();
950   if (bytes_left > 0) {
951     m_process_launch_info.GetEnvironment().insert(packet.Peek());
952     return SendOKResponse();
953   }
954   return SendErrorResponse(12);
955 }
956 
957 GDBRemoteCommunication::PacketResult
958 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
959     StringExtractorGDBRemote &packet) {
960   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
961   const uint32_t bytes_left = packet.GetBytesLeft();
962   if (bytes_left > 0) {
963     std::string str;
964     packet.GetHexByteString(str);
965     m_process_launch_info.GetEnvironment().insert(str);
966     return SendOKResponse();
967   }
968   return SendErrorResponse(12);
969 }
970 
971 GDBRemoteCommunication::PacketResult
972 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
973     StringExtractorGDBRemote &packet) {
974   packet.SetFilePos(::strlen("QLaunchArch:"));
975   const uint32_t bytes_left = packet.GetBytesLeft();
976   if (bytes_left > 0) {
977     const char *arch_triple = packet.Peek();
978     m_process_launch_info.SetArchitecture(HostInfo::GetAugmentedArchSpec(arch_triple));
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 redundant
987   // argument indexes, redundant argument lengths and needed hex encoded
988   // argument string values. Really all that is needed is a comma separated hex
989   // encoded argument value list, but we will stay true to the documented
990   // 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 number of
999     // 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 who would
1009         // 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 back into a UTF8
1019             // string and make sure the length matches the one supplied in the
1020             // 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, false);
1035                 m_process_launch_info.GetArguments().AppendArgument(arg);
1036                 if (log)
1037                   log->Printf("LLGSPacketHandler::%s added arg %d: \"%s\"",
1038                               __FUNCTION__, actual_arg_index, arg.c_str());
1039                 ++actual_arg_index;
1040               }
1041             }
1042           }
1043         }
1044       }
1045     }
1046   }
1047 
1048   if (success) {
1049     m_process_launch_error = LaunchProcess();
1050     if (m_process_launch_error.Success())
1051       return SendOKResponse();
1052     LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
1053   }
1054   return SendErrorResponse(8);
1055 }
1056 
1057 GDBRemoteCommunication::PacketResult
1058 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1059     StringExtractorGDBRemote &packet) {
1060   // Just echo back the exact same packet for qEcho...
1061   return SendPacketNoLock(packet.GetStringRef());
1062 }
1063 
1064 GDBRemoteCommunication::PacketResult
1065 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1066     StringExtractorGDBRemote &packet) {
1067   packet.SetFilePos(::strlen("qModuleInfo:"));
1068 
1069   std::string module_path;
1070   packet.GetHexByteStringTerminatedBy(module_path, ';');
1071   if (module_path.empty())
1072     return SendErrorResponse(1);
1073 
1074   if (packet.GetChar() != ';')
1075     return SendErrorResponse(2);
1076 
1077   std::string triple;
1078   packet.GetHexByteString(triple);
1079 
1080   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1081   if (!matched_module_spec.GetFileSpec())
1082     return SendErrorResponse(3);
1083 
1084   const auto file_offset = matched_module_spec.GetObjectOffset();
1085   const auto file_size = matched_module_spec.GetObjectSize();
1086   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1087 
1088   StreamGDBRemote response;
1089 
1090   if (uuid_str.empty()) {
1091     auto Result = llvm::sys::fs::md5_contents(matched_module_spec.GetFileSpec().GetPath());
1092     if (!Result)
1093       return SendErrorResponse(5);
1094     response.PutCString("md5:");
1095     response.PutCStringAsRawHex8(Result->digest().c_str());
1096   } else {
1097     response.PutCString("uuid:");
1098     response.PutCStringAsRawHex8(uuid_str.c_str());
1099   }
1100   response.PutChar(';');
1101 
1102   const auto &module_arch = matched_module_spec.GetArchitecture();
1103   response.PutCString("triple:");
1104   response.PutCStringAsRawHex8(module_arch.GetTriple().getTriple().c_str());
1105   response.PutChar(';');
1106 
1107   response.PutCString("file_path:");
1108   response.PutCStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1109   response.PutChar(';');
1110   response.PutCString("file_offset:");
1111   response.PutHex64(file_offset);
1112   response.PutChar(';');
1113   response.PutCString("file_size:");
1114   response.PutHex64(file_size);
1115   response.PutChar(';');
1116 
1117   return SendPacketNoLock(response.GetString());
1118 }
1119 
1120 GDBRemoteCommunication::PacketResult
1121 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1122     StringExtractorGDBRemote &packet) {
1123   packet.SetFilePos(::strlen("jModulesInfo:"));
1124 
1125   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1126   if (!object_sp)
1127     return SendErrorResponse(1);
1128 
1129   StructuredData::Array *packet_array = object_sp->GetAsArray();
1130   if (!packet_array)
1131     return SendErrorResponse(2);
1132 
1133   JSONArray::SP response_array_sp = std::make_shared<JSONArray>();
1134   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1135     StructuredData::Dictionary *query =
1136         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1137     if (!query)
1138       continue;
1139     llvm::StringRef file, triple;
1140     if (!query->GetValueForKeyAsString("file", file) ||
1141         !query->GetValueForKeyAsString("triple", triple))
1142       continue;
1143 
1144     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1145     if (!matched_module_spec.GetFileSpec())
1146       continue;
1147 
1148     const auto file_offset = matched_module_spec.GetObjectOffset();
1149     const auto file_size = matched_module_spec.GetObjectSize();
1150     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1151 
1152     if (uuid_str.empty())
1153       continue;
1154 
1155     JSONObject::SP response = std::make_shared<JSONObject>();
1156     response_array_sp->AppendObject(response);
1157     response->SetObject("uuid", std::make_shared<JSONString>(uuid_str));
1158     response->SetObject(
1159         "triple",
1160         std::make_shared<JSONString>(
1161             matched_module_spec.GetArchitecture().GetTriple().getTriple()));
1162     response->SetObject("file_path",
1163                         std::make_shared<JSONString>(
1164                             matched_module_spec.GetFileSpec().GetPath()));
1165     response->SetObject("file_offset",
1166                         std::make_shared<JSONNumber>(file_offset));
1167     response->SetObject("file_size", std::make_shared<JSONNumber>(file_size));
1168   }
1169 
1170   StreamString response;
1171   response_array_sp->Write(response);
1172   StreamGDBRemote escaped_response;
1173   escaped_response.PutEscapedBytes(response.GetString().data(),
1174                                    response.GetSize());
1175   return SendPacketNoLock(escaped_response.GetString());
1176 }
1177 
1178 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1179     const ProcessInstanceInfo &proc_info, StreamString &response) {
1180   response.Printf(
1181       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1182       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1183       proc_info.GetUserID(), proc_info.GetGroupID(),
1184       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1185   response.PutCString("name:");
1186   response.PutCStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1187   response.PutChar(';');
1188   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1189   if (proc_arch.IsValid()) {
1190     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1191     response.PutCString("triple:");
1192     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1193     response.PutChar(';');
1194   }
1195 }
1196 
1197 void GDBRemoteCommunicationServerCommon::
1198     CreateProcessInfoResponse_DebugServerStyle(
1199         const ProcessInstanceInfo &proc_info, StreamString &response) {
1200   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1201                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1202                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1203                   proc_info.GetUserID(), proc_info.GetGroupID(),
1204                   proc_info.GetEffectiveUserID(),
1205                   proc_info.GetEffectiveGroupID());
1206 
1207   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1208   if (proc_arch.IsValid()) {
1209     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1210 #if defined(__APPLE__)
1211     // We'll send cputype/cpusubtype.
1212     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1213     if (cpu_type != 0)
1214       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1215 
1216     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1217     if (cpu_subtype != 0)
1218       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1219 
1220     const std::string vendor = proc_triple.getVendorName();
1221     if (!vendor.empty())
1222       response.Printf("vendor:%s;", vendor.c_str());
1223 #else
1224     // We'll send the triple.
1225     response.PutCString("triple:");
1226     response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1227     response.PutChar(';');
1228 #endif
1229     std::string ostype = proc_triple.getOSName();
1230     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1231     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1232       switch (proc_triple.getArch()) {
1233       case llvm::Triple::arm:
1234       case llvm::Triple::thumb:
1235       case llvm::Triple::aarch64:
1236         ostype = "ios";
1237         break;
1238       default:
1239         // No change.
1240         break;
1241       }
1242     }
1243     response.Printf("ostype:%s;", ostype.c_str());
1244 
1245     switch (proc_arch.GetByteOrder()) {
1246     case lldb::eByteOrderLittle:
1247       response.PutCString("endian:little;");
1248       break;
1249     case lldb::eByteOrderBig:
1250       response.PutCString("endian:big;");
1251       break;
1252     case lldb::eByteOrderPDP:
1253       response.PutCString("endian:pdp;");
1254       break;
1255     default:
1256       // Nothing.
1257       break;
1258     }
1259     // In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer
1260     // size is 4 and for N64 it is 8
1261     std::string abi = proc_arch.GetTargetABI();
1262     if (!abi.empty())
1263       response.Printf("elf_abi:%s;", abi.c_str());
1264     response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());
1265   }
1266 }
1267 
1268 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(
1269     const std::string &module_path, const ArchSpec &arch) {
1270 #ifdef __ANDROID__
1271   return HostInfoAndroid::ResolveLibraryPath(module_path, arch);
1272 #else
1273   return FileSpec(module_path, true);
1274 #endif
1275 }
1276 
1277 ModuleSpec
1278 GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path,
1279                                                   llvm::StringRef triple) {
1280   ArchSpec arch(triple);
1281 
1282   const FileSpec req_module_path_spec(module_path, true);
1283   const FileSpec module_path_spec =
1284       FindModuleFile(req_module_path_spec.GetPath(), arch);
1285   const ModuleSpec module_spec(module_path_spec, arch);
1286 
1287   ModuleSpecList module_specs;
1288   if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0,
1289                                            module_specs))
1290     return ModuleSpec();
1291 
1292   ModuleSpec matched_module_spec;
1293   if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))
1294     return ModuleSpec();
1295 
1296   return matched_module_spec;
1297 }
1298