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