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