1 //===-- GDBRemoteCommunicationServerCommon.cpp ----------------------------===//
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 <cerrno>
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) {
64   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A,
65                                 &GDBRemoteCommunicationServerCommon::Handle_A);
66   RegisterMemberFunctionHandler(
67       StringExtractorGDBRemote::eServerPacketType_QEnvironment,
68       &GDBRemoteCommunicationServerCommon::Handle_QEnvironment);
69   RegisterMemberFunctionHandler(
70       StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded,
71       &GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded);
72   RegisterMemberFunctionHandler(
73       StringExtractorGDBRemote::eServerPacketType_qfProcessInfo,
74       &GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo);
75   RegisterMemberFunctionHandler(
76       StringExtractorGDBRemote::eServerPacketType_qGroupName,
77       &GDBRemoteCommunicationServerCommon::Handle_qGroupName);
78   RegisterMemberFunctionHandler(
79       StringExtractorGDBRemote::eServerPacketType_qHostInfo,
80       &GDBRemoteCommunicationServerCommon::Handle_qHostInfo);
81   RegisterMemberFunctionHandler(
82       StringExtractorGDBRemote::eServerPacketType_QLaunchArch,
83       &GDBRemoteCommunicationServerCommon::Handle_QLaunchArch);
84   RegisterMemberFunctionHandler(
85       StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess,
86       &GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess);
87   RegisterMemberFunctionHandler(
88       StringExtractorGDBRemote::eServerPacketType_qEcho,
89       &GDBRemoteCommunicationServerCommon::Handle_qEcho);
90   RegisterMemberFunctionHandler(
91       StringExtractorGDBRemote::eServerPacketType_qModuleInfo,
92       &GDBRemoteCommunicationServerCommon::Handle_qModuleInfo);
93   RegisterMemberFunctionHandler(
94       StringExtractorGDBRemote::eServerPacketType_jModulesInfo,
95       &GDBRemoteCommunicationServerCommon::Handle_jModulesInfo);
96   RegisterMemberFunctionHandler(
97       StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod,
98       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod);
99   RegisterMemberFunctionHandler(
100       StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir,
101       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir);
102   RegisterMemberFunctionHandler(
103       StringExtractorGDBRemote::eServerPacketType_qPlatform_shell,
104       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell);
105   RegisterMemberFunctionHandler(
106       StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID,
107       &GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID);
108   RegisterMemberFunctionHandler(
109       StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError,
110       &GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError);
111   RegisterMemberFunctionHandler(
112       StringExtractorGDBRemote::eServerPacketType_QSetSTDERR,
113       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR);
114   RegisterMemberFunctionHandler(
115       StringExtractorGDBRemote::eServerPacketType_QSetSTDIN,
116       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN);
117   RegisterMemberFunctionHandler(
118       StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT,
119       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT);
120   RegisterMemberFunctionHandler(
121       StringExtractorGDBRemote::eServerPacketType_qSpeedTest,
122       &GDBRemoteCommunicationServerCommon::Handle_qSpeedTest);
123   RegisterMemberFunctionHandler(
124       StringExtractorGDBRemote::eServerPacketType_qsProcessInfo,
125       &GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo);
126   RegisterMemberFunctionHandler(
127       StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode,
128       &GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode);
129   RegisterMemberFunctionHandler(
130       StringExtractorGDBRemote::eServerPacketType_qSupported,
131       &GDBRemoteCommunicationServerCommon::Handle_qSupported);
132   RegisterMemberFunctionHandler(
133       StringExtractorGDBRemote::eServerPacketType_qUserName,
134       &GDBRemoteCommunicationServerCommon::Handle_qUserName);
135   RegisterMemberFunctionHandler(
136       StringExtractorGDBRemote::eServerPacketType_vFile_close,
137       &GDBRemoteCommunicationServerCommon::Handle_vFile_Close);
138   RegisterMemberFunctionHandler(
139       StringExtractorGDBRemote::eServerPacketType_vFile_exists,
140       &GDBRemoteCommunicationServerCommon::Handle_vFile_Exists);
141   RegisterMemberFunctionHandler(
142       StringExtractorGDBRemote::eServerPacketType_vFile_md5,
143       &GDBRemoteCommunicationServerCommon::Handle_vFile_MD5);
144   RegisterMemberFunctionHandler(
145       StringExtractorGDBRemote::eServerPacketType_vFile_mode,
146       &GDBRemoteCommunicationServerCommon::Handle_vFile_Mode);
147   RegisterMemberFunctionHandler(
148       StringExtractorGDBRemote::eServerPacketType_vFile_open,
149       &GDBRemoteCommunicationServerCommon::Handle_vFile_Open);
150   RegisterMemberFunctionHandler(
151       StringExtractorGDBRemote::eServerPacketType_vFile_pread,
152       &GDBRemoteCommunicationServerCommon::Handle_vFile_pRead);
153   RegisterMemberFunctionHandler(
154       StringExtractorGDBRemote::eServerPacketType_vFile_pwrite,
155       &GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite);
156   RegisterMemberFunctionHandler(
157       StringExtractorGDBRemote::eServerPacketType_vFile_size,
158       &GDBRemoteCommunicationServerCommon::Handle_vFile_Size);
159   RegisterMemberFunctionHandler(
160       StringExtractorGDBRemote::eServerPacketType_vFile_fstat,
161       &GDBRemoteCommunicationServerCommon::Handle_vFile_FStat);
162   RegisterMemberFunctionHandler(
163       StringExtractorGDBRemote::eServerPacketType_vFile_stat,
164       &GDBRemoteCommunicationServerCommon::Handle_vFile_Stat);
165   RegisterMemberFunctionHandler(
166       StringExtractorGDBRemote::eServerPacketType_vFile_symlink,
167       &GDBRemoteCommunicationServerCommon::Handle_vFile_symlink);
168   RegisterMemberFunctionHandler(
169       StringExtractorGDBRemote::eServerPacketType_vFile_unlink,
170       &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink);
171 }
172 
173 // Destructor
174 GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() =
175     default;
176 
177 GDBRemoteCommunication::PacketResult
178 GDBRemoteCommunicationServerCommon::Handle_qHostInfo(
179     StringExtractorGDBRemote &packet) {
180   StreamString response;
181 
182   // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
183 
184   ArchSpec host_arch(HostInfo::GetArchitecture());
185   const llvm::Triple &host_triple = host_arch.GetTriple();
186   response.PutCString("triple:");
187   response.PutStringAsRawHex8(host_triple.getTriple());
188   response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize());
189 
190   const char *distribution_id = host_arch.GetDistributionId().AsCString();
191   if (distribution_id) {
192     response.PutCString("distribution_id:");
193     response.PutStringAsRawHex8(distribution_id);
194     response.PutCString(";");
195   }
196 
197 #if defined(__APPLE__)
198   // For parity with debugserver, we'll include the vendor key.
199   response.PutCString("vendor:apple;");
200 
201   // Send out MachO info.
202   uint32_t cpu = host_arch.GetMachOCPUType();
203   uint32_t sub = host_arch.GetMachOCPUSubType();
204   if (cpu != LLDB_INVALID_CPUTYPE)
205     response.Printf("cputype:%u;", cpu);
206   if (sub != LLDB_INVALID_CPUTYPE)
207     response.Printf("cpusubtype:%u;", sub);
208 
209   if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) {
210 // Indicate the OS type.
211 #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
212     response.PutCString("ostype:tvos;");
213 #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
214     response.PutCString("ostype:watchos;");
215 #elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
216     response.PutCString("ostype:bridgeos;");
217 #else
218     response.PutCString("ostype:ios;");
219 #endif
220 
221     // On arm, we use "synchronous" watchpoints which means the exception is
222     // delivered before the instruction executes.
223     response.PutCString("watchpoint_exceptions_received:before;");
224   } else {
225     response.PutCString("ostype:macosx;");
226     response.Printf("watchpoint_exceptions_received:after;");
227   }
228 
229 #else
230   if (host_arch.GetMachine() == llvm::Triple::aarch64 ||
231       host_arch.GetMachine() == llvm::Triple::aarch64_32 ||
232       host_arch.GetMachine() == llvm::Triple::aarch64_be ||
233       host_arch.GetMachine() == llvm::Triple::arm ||
234       host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS())
235     response.Printf("watchpoint_exceptions_received:before;");
236   else
237     response.Printf("watchpoint_exceptions_received:after;");
238 #endif
239 
240   switch (endian::InlHostByteOrder()) {
241   case eByteOrderBig:
242     response.PutCString("endian:big;");
243     break;
244   case eByteOrderLittle:
245     response.PutCString("endian:little;");
246     break;
247   case eByteOrderPDP:
248     response.PutCString("endian:pdp;");
249     break;
250   default:
251     response.PutCString("endian:unknown;");
252     break;
253   }
254 
255   llvm::VersionTuple version = HostInfo::GetOSVersion();
256   if (!version.empty()) {
257     response.Format("os_version:{0}", version.getAsString());
258     response.PutChar(';');
259   }
260 
261 #if defined(__APPLE__)
262   llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion();
263   if (!maccatalyst_version.empty()) {
264     response.Format("maccatalyst_version:{0}",
265                     maccatalyst_version.getAsString());
266     response.PutChar(';');
267   }
268 #endif
269 
270   std::string s;
271   if (HostInfo::GetOSBuildString(s)) {
272     response.PutCString("os_build:");
273     response.PutStringAsRawHex8(s);
274     response.PutChar(';');
275   }
276   if (HostInfo::GetOSKernelDescription(s)) {
277     response.PutCString("os_kernel:");
278     response.PutStringAsRawHex8(s);
279     response.PutChar(';');
280   }
281 
282 #if defined(__APPLE__)
283 
284 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
285   // For iOS devices, we are connected through a USB Mux so we never pretend to
286   // actually have a hostname as far as the remote lldb that is connecting to
287   // this lldb-platform is concerned
288   response.PutCString("hostname:");
289   response.PutStringAsRawHex8("127.0.0.1");
290   response.PutChar(';');
291 #else  // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
292   if (HostInfo::GetHostname(s)) {
293     response.PutCString("hostname:");
294     response.PutStringAsRawHex8(s);
295     response.PutChar(';');
296   }
297 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
298 
299 #else  // #if defined(__APPLE__)
300   if (HostInfo::GetHostname(s)) {
301     response.PutCString("hostname:");
302     response.PutStringAsRawHex8(s);
303     response.PutChar(';');
304   }
305 #endif // #if defined(__APPLE__)
306 
307   if (g_default_packet_timeout_sec > 0)
308     response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec);
309 
310   return SendPacketNoLock(response.GetString());
311 }
312 
313 GDBRemoteCommunication::PacketResult
314 GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID(
315     StringExtractorGDBRemote &packet) {
316   // Packet format: "qProcessInfoPID:%i" where %i is the pid
317   packet.SetFilePos(::strlen("qProcessInfoPID:"));
318   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID);
319   if (pid != LLDB_INVALID_PROCESS_ID) {
320     ProcessInstanceInfo proc_info;
321     if (Host::GetProcessInfo(pid, proc_info)) {
322       StreamString response;
323       CreateProcessInfoResponse(proc_info, response);
324       return SendPacketNoLock(response.GetString());
325     }
326   }
327   return SendErrorResponse(1);
328 }
329 
330 GDBRemoteCommunication::PacketResult
331 GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo(
332     StringExtractorGDBRemote &packet) {
333   m_proc_infos_index = 0;
334   m_proc_infos.clear();
335 
336   ProcessInstanceInfoMatch match_info;
337   packet.SetFilePos(::strlen("qfProcessInfo"));
338   if (packet.GetChar() == ':') {
339     llvm::StringRef key;
340     llvm::StringRef value;
341     while (packet.GetNameColonValue(key, value)) {
342       bool success = true;
343       if (key.equals("name")) {
344         StringExtractor extractor(value);
345         std::string file;
346         extractor.GetHexByteString(file);
347         match_info.GetProcessInfo().GetExecutableFile().SetFile(
348             file, FileSpec::Style::native);
349       } else if (key.equals("name_match")) {
350         NameMatch name_match = llvm::StringSwitch<NameMatch>(value)
351                                    .Case("equals", NameMatch::Equals)
352                                    .Case("starts_with", NameMatch::StartsWith)
353                                    .Case("ends_with", NameMatch::EndsWith)
354                                    .Case("contains", NameMatch::Contains)
355                                    .Case("regex", NameMatch::RegularExpression)
356                                    .Default(NameMatch::Ignore);
357         match_info.SetNameMatchType(name_match);
358         if (name_match == NameMatch::Ignore)
359           return SendErrorResponse(2);
360       } else if (key.equals("pid")) {
361         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
362         if (value.getAsInteger(0, pid))
363           return SendErrorResponse(2);
364         match_info.GetProcessInfo().SetProcessID(pid);
365       } else if (key.equals("parent_pid")) {
366         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
367         if (value.getAsInteger(0, pid))
368           return SendErrorResponse(2);
369         match_info.GetProcessInfo().SetParentProcessID(pid);
370       } else if (key.equals("uid")) {
371         uint32_t uid = UINT32_MAX;
372         if (value.getAsInteger(0, uid))
373           return SendErrorResponse(2);
374         match_info.GetProcessInfo().SetUserID(uid);
375       } else if (key.equals("gid")) {
376         uint32_t gid = UINT32_MAX;
377         if (value.getAsInteger(0, gid))
378           return SendErrorResponse(2);
379         match_info.GetProcessInfo().SetGroupID(gid);
380       } else if (key.equals("euid")) {
381         uint32_t uid = UINT32_MAX;
382         if (value.getAsInteger(0, uid))
383           return SendErrorResponse(2);
384         match_info.GetProcessInfo().SetEffectiveUserID(uid);
385       } else if (key.equals("egid")) {
386         uint32_t gid = UINT32_MAX;
387         if (value.getAsInteger(0, gid))
388           return SendErrorResponse(2);
389         match_info.GetProcessInfo().SetEffectiveGroupID(gid);
390       } else if (key.equals("all_users")) {
391         match_info.SetMatchAllUsers(
392             OptionArgParser::ToBoolean(value, false, &success));
393       } else if (key.equals("triple")) {
394         match_info.GetProcessInfo().GetArchitecture() =
395             HostInfo::GetAugmentedArchSpec(value);
396       } else {
397         success = false;
398       }
399 
400       if (!success)
401         return SendErrorResponse(2);
402     }
403   }
404 
405   if (Host::FindProcesses(match_info, m_proc_infos)) {
406     // We found something, return the first item by calling the get subsequent
407     // process info packet handler...
408     return Handle_qsProcessInfo(packet);
409   }
410   return SendErrorResponse(3);
411 }
412 
413 GDBRemoteCommunication::PacketResult
414 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(
415     StringExtractorGDBRemote &packet) {
416   if (m_proc_infos_index < m_proc_infos.size()) {
417     StreamString response;
418     CreateProcessInfoResponse(m_proc_infos[m_proc_infos_index], response);
419     ++m_proc_infos_index;
420     return SendPacketNoLock(response.GetString());
421   }
422   return SendErrorResponse(4);
423 }
424 
425 GDBRemoteCommunication::PacketResult
426 GDBRemoteCommunicationServerCommon::Handle_qUserName(
427     StringExtractorGDBRemote &packet) {
428 #if LLDB_ENABLE_POSIX
429   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
430   LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);
431 
432   // Packet format: "qUserName:%i" where %i is the uid
433   packet.SetFilePos(::strlen("qUserName:"));
434   uint32_t uid = packet.GetU32(UINT32_MAX);
435   if (uid != UINT32_MAX) {
436     if (llvm::Optional<llvm::StringRef> name =
437             HostInfo::GetUserIDResolver().GetUserName(uid)) {
438       StreamString response;
439       response.PutStringAsRawHex8(*name);
440       return SendPacketNoLock(response.GetString());
441     }
442   }
443   LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);
444 #endif
445   return SendErrorResponse(5);
446 }
447 
448 GDBRemoteCommunication::PacketResult
449 GDBRemoteCommunicationServerCommon::Handle_qGroupName(
450     StringExtractorGDBRemote &packet) {
451 #if LLDB_ENABLE_POSIX
452   // Packet format: "qGroupName:%i" where %i is the gid
453   packet.SetFilePos(::strlen("qGroupName:"));
454   uint32_t gid = packet.GetU32(UINT32_MAX);
455   if (gid != UINT32_MAX) {
456     if (llvm::Optional<llvm::StringRef> name =
457             HostInfo::GetUserIDResolver().GetGroupName(gid)) {
458       StreamString response;
459       response.PutStringAsRawHex8(*name);
460       return SendPacketNoLock(response.GetString());
461     }
462   }
463 #endif
464   return SendErrorResponse(6);
465 }
466 
467 GDBRemoteCommunication::PacketResult
468 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(
469     StringExtractorGDBRemote &packet) {
470   packet.SetFilePos(::strlen("qSpeedTest:"));
471 
472   llvm::StringRef key;
473   llvm::StringRef value;
474   bool success = packet.GetNameColonValue(key, value);
475   if (success && key.equals("response_size")) {
476     uint32_t response_size = 0;
477     if (!value.getAsInteger(0, response_size)) {
478       if (response_size == 0)
479         return SendOKResponse();
480       StreamString response;
481       uint32_t bytes_left = response_size;
482       response.PutCString("data:");
483       while (bytes_left > 0) {
484         if (bytes_left >= 26) {
485           response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
486           bytes_left -= 26;
487         } else {
488           response.Printf("%*.*s;", bytes_left, bytes_left,
489                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
490           bytes_left = 0;
491         }
492       }
493       return SendPacketNoLock(response.GetString());
494     }
495   }
496   return SendErrorResponse(7);
497 }
498 
499 GDBRemoteCommunication::PacketResult
500 GDBRemoteCommunicationServerCommon::Handle_vFile_Open(
501     StringExtractorGDBRemote &packet) {
502   packet.SetFilePos(::strlen("vFile:open:"));
503   std::string path;
504   packet.GetHexByteStringTerminatedBy(path, ',');
505   if (!path.empty()) {
506     if (packet.GetChar() == ',') {
507       auto flags = File::OpenOptions(packet.GetHexMaxU32(false, 0));
508       if (packet.GetChar() == ',') {
509         mode_t mode = packet.GetHexMaxU32(false, 0600);
510         FileSpec path_spec(path);
511         FileSystem::Instance().Resolve(path_spec);
512         // Do not close fd.
513         auto file = FileSystem::Instance().Open(path_spec, flags, mode, false);
514 
515         StreamString response;
516         response.PutChar('F');
517 
518         int descriptor = File::kInvalidDescriptor;
519         if (file) {
520           descriptor = file.get()->GetDescriptor();
521           response.Printf("%x", descriptor);
522         } else {
523           response.PutCString("-1");
524           std::error_code code = errorToErrorCode(file.takeError());
525           if (code.category() == std::system_category()) {
526             response.Printf(",%x", code.value());
527           }
528         }
529 
530         return SendPacketNoLock(response.GetString());
531       }
532     }
533   }
534   return SendErrorResponse(18);
535 }
536 
537 GDBRemoteCommunication::PacketResult
538 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
539     StringExtractorGDBRemote &packet) {
540   packet.SetFilePos(::strlen("vFile:close:"));
541   int fd = packet.GetS32(-1, 16);
542   int err = -1;
543   int save_errno = 0;
544   if (fd >= 0) {
545     NativeFile file(fd, File::OpenOptions(0), true);
546     Status error = file.Close();
547     err = 0;
548     save_errno = error.GetError();
549   } else {
550     save_errno = EINVAL;
551   }
552   StreamString response;
553   response.PutChar('F');
554   response.Printf("%x", err);
555   if (save_errno)
556     response.Printf(",%x", save_errno);
557   return SendPacketNoLock(response.GetString());
558 }
559 
560 GDBRemoteCommunication::PacketResult
561 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
562     StringExtractorGDBRemote &packet) {
563   StreamGDBRemote response;
564   packet.SetFilePos(::strlen("vFile:pread:"));
565   int fd = packet.GetS32(-1, 16);
566   if (packet.GetChar() == ',') {
567     size_t count = packet.GetHexMaxU64(false, SIZE_MAX);
568     if (packet.GetChar() == ',') {
569       off_t offset = packet.GetHexMaxU32(false, UINT32_MAX);
570       if (count == SIZE_MAX) {
571         response.Printf("F-1:%x", EINVAL);
572         return SendPacketNoLock(response.GetString());
573       }
574 
575       std::string buffer(count, 0);
576       NativeFile file(fd, File::eOpenOptionReadOnly, false);
577       Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset);
578       const int save_errno = error.GetError();
579       response.PutChar('F');
580       if (error.Success()) {
581         response.Printf("%zx", count);
582         response.PutChar(';');
583         response.PutEscapedBytes(&buffer[0], count);
584       } else {
585         response.PutCString("-1");
586         if (save_errno)
587           response.Printf(",%x", save_errno);
588       }
589       return SendPacketNoLock(response.GetString());
590     }
591   }
592   return SendErrorResponse(21);
593 }
594 
595 GDBRemoteCommunication::PacketResult
596 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
597     StringExtractorGDBRemote &packet) {
598   packet.SetFilePos(::strlen("vFile:pwrite:"));
599 
600   StreamGDBRemote response;
601   response.PutChar('F');
602 
603   int fd = packet.GetS32(-1, 16);
604   if (packet.GetChar() == ',') {
605     off_t offset = packet.GetHexMaxU32(false, UINT32_MAX);
606     if (packet.GetChar() == ',') {
607       std::string buffer;
608       if (packet.GetEscapedBinaryData(buffer)) {
609         NativeFile file(fd, File::eOpenOptionWriteOnly, false);
610         size_t count = buffer.size();
611         Status error =
612             file.Write(static_cast<const void *>(&buffer[0]), count, offset);
613         const int save_errno = error.GetError();
614         if (error.Success())
615           response.Printf("%zx", count);
616         else {
617           response.PutCString("-1");
618           if (save_errno)
619             response.Printf(",%x", save_errno);
620         }
621       } else {
622         response.Printf("-1,%x", 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%x", mode);
665     if (mode == 0 || ec)
666       response.Printf(",%x", (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%x,%x", 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%x,%x", 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 template <typename T, typename U>
761 static void fill_clamp(T &dest, U src, typename T::value_type fallback) {
762   dest = src <= std::numeric_limits<typename T::value_type>::max() ? src
763                                                                    : fallback;
764 }
765 
766 GDBRemoteCommunication::PacketResult
767 GDBRemoteCommunicationServerCommon::Handle_vFile_FStat(
768     StringExtractorGDBRemote &packet) {
769   StreamGDBRemote response;
770   packet.SetFilePos(::strlen("vFile:fstat:"));
771   int fd = packet.GetS32(-1, 16);
772 
773   struct stat file_stats;
774   if (::fstat(fd, &file_stats) == -1) {
775     const int save_errno = errno;
776     response.Printf("F-1,%x", save_errno);
777     return SendPacketNoLock(response.GetString());
778   }
779 
780   GDBRemoteFStatData data;
781   fill_clamp(data.gdb_st_dev, file_stats.st_dev, 0);
782   fill_clamp(data.gdb_st_ino, file_stats.st_ino, 0);
783   data.gdb_st_mode = file_stats.st_mode;
784   fill_clamp(data.gdb_st_nlink, file_stats.st_nlink, UINT32_MAX);
785   fill_clamp(data.gdb_st_uid, file_stats.st_uid, 0);
786   fill_clamp(data.gdb_st_gid, file_stats.st_gid, 0);
787   fill_clamp(data.gdb_st_rdev, file_stats.st_rdev, 0);
788   data.gdb_st_size = file_stats.st_size;
789   data.gdb_st_blksize = file_stats.st_blksize;
790   data.gdb_st_blocks = file_stats.st_blocks;
791   fill_clamp(data.gdb_st_atime, file_stats.st_atime, 0);
792   fill_clamp(data.gdb_st_mtime, file_stats.st_mtime, 0);
793   fill_clamp(data.gdb_st_ctime, file_stats.st_ctime, 0);
794 
795   response.Printf("F%zx;", sizeof(data));
796   response.PutEscapedBytes(&data, sizeof(data));
797   return SendPacketNoLock(response.GetString());
798 }
799 
800 GDBRemoteCommunication::PacketResult
801 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(
802     StringExtractorGDBRemote &packet) {
803   return SendUnimplementedResponse(
804       "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");
805 }
806 
807 GDBRemoteCommunication::PacketResult
808 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(
809     StringExtractorGDBRemote &packet) {
810   packet.SetFilePos(::strlen("vFile:MD5:"));
811   std::string path;
812   packet.GetHexByteString(path);
813   if (!path.empty()) {
814     StreamGDBRemote response;
815     auto Result = llvm::sys::fs::md5_contents(path);
816     if (!Result) {
817       response.PutCString("F,");
818       response.PutCString("x");
819     } else {
820       response.PutCString("F,");
821       response.PutHex64(Result->low());
822       response.PutHex64(Result->high());
823     }
824     return SendPacketNoLock(response.GetString());
825   }
826   return SendErrorResponse(25);
827 }
828 
829 GDBRemoteCommunication::PacketResult
830 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(
831     StringExtractorGDBRemote &packet) {
832   packet.SetFilePos(::strlen("qPlatform_mkdir:"));
833   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
834   if (packet.GetChar() == ',') {
835     std::string path;
836     packet.GetHexByteString(path);
837     Status error(llvm::sys::fs::create_directory(path, mode));
838 
839     StreamGDBRemote response;
840     response.Printf("F%x", error.GetError());
841 
842     return SendPacketNoLock(response.GetString());
843   }
844   return SendErrorResponse(20);
845 }
846 
847 GDBRemoteCommunication::PacketResult
848 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(
849     StringExtractorGDBRemote &packet) {
850   packet.SetFilePos(::strlen("qPlatform_chmod:"));
851 
852   auto perms =
853       static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX));
854   if (packet.GetChar() == ',') {
855     std::string path;
856     packet.GetHexByteString(path);
857     Status error(llvm::sys::fs::setPermissions(path, perms));
858 
859     StreamGDBRemote response;
860     response.Printf("F%x", error.GetError());
861 
862     return SendPacketNoLock(response.GetString());
863   }
864   return SendErrorResponse(19);
865 }
866 
867 GDBRemoteCommunication::PacketResult
868 GDBRemoteCommunicationServerCommon::Handle_qSupported(
869     StringExtractorGDBRemote &packet) {
870   // Parse client-indicated features.
871   llvm::SmallVector<llvm::StringRef, 4> client_features;
872   packet.GetStringRef().split(client_features, ';');
873   return SendPacketNoLock(llvm::join(HandleFeatures(client_features), ";"));
874 }
875 
876 GDBRemoteCommunication::PacketResult
877 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
878     StringExtractorGDBRemote &packet) {
879   packet.SetFilePos(::strlen("QSetDetachOnError:"));
880   if (packet.GetU32(0))
881     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
882   else
883     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
884   return SendOKResponse();
885 }
886 
887 GDBRemoteCommunication::PacketResult
888 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
889     StringExtractorGDBRemote &packet) {
890   // Send response first before changing m_send_acks to we ack this packet
891   PacketResult packet_result = SendOKResponse();
892   m_send_acks = false;
893   return packet_result;
894 }
895 
896 GDBRemoteCommunication::PacketResult
897 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
898     StringExtractorGDBRemote &packet) {
899   packet.SetFilePos(::strlen("QSetSTDIN:"));
900   FileAction file_action;
901   std::string path;
902   packet.GetHexByteString(path);
903   const bool read = true;
904   const bool write = false;
905   if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) {
906     m_process_launch_info.AppendFileAction(file_action);
907     return SendOKResponse();
908   }
909   return SendErrorResponse(15);
910 }
911 
912 GDBRemoteCommunication::PacketResult
913 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
914     StringExtractorGDBRemote &packet) {
915   packet.SetFilePos(::strlen("QSetSTDOUT:"));
916   FileAction file_action;
917   std::string path;
918   packet.GetHexByteString(path);
919   const bool read = false;
920   const bool write = true;
921   if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) {
922     m_process_launch_info.AppendFileAction(file_action);
923     return SendOKResponse();
924   }
925   return SendErrorResponse(16);
926 }
927 
928 GDBRemoteCommunication::PacketResult
929 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
930     StringExtractorGDBRemote &packet) {
931   packet.SetFilePos(::strlen("QSetSTDERR:"));
932   FileAction file_action;
933   std::string path;
934   packet.GetHexByteString(path);
935   const bool read = false;
936   const bool write = true;
937   if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) {
938     m_process_launch_info.AppendFileAction(file_action);
939     return SendOKResponse();
940   }
941   return SendErrorResponse(17);
942 }
943 
944 GDBRemoteCommunication::PacketResult
945 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
946     StringExtractorGDBRemote &packet) {
947   if (m_process_launch_error.Success())
948     return SendOKResponse();
949   StreamString response;
950   response.PutChar('E');
951   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
952   return SendPacketNoLock(response.GetString());
953 }
954 
955 GDBRemoteCommunication::PacketResult
956 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
957     StringExtractorGDBRemote &packet) {
958   packet.SetFilePos(::strlen("QEnvironment:"));
959   const uint32_t bytes_left = packet.GetBytesLeft();
960   if (bytes_left > 0) {
961     m_process_launch_info.GetEnvironment().insert(packet.Peek());
962     return SendOKResponse();
963   }
964   return SendErrorResponse(12);
965 }
966 
967 GDBRemoteCommunication::PacketResult
968 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
969     StringExtractorGDBRemote &packet) {
970   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
971   const uint32_t bytes_left = packet.GetBytesLeft();
972   if (bytes_left > 0) {
973     std::string str;
974     packet.GetHexByteString(str);
975     m_process_launch_info.GetEnvironment().insert(str);
976     return SendOKResponse();
977   }
978   return SendErrorResponse(12);
979 }
980 
981 GDBRemoteCommunication::PacketResult
982 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
983     StringExtractorGDBRemote &packet) {
984   packet.SetFilePos(::strlen("QLaunchArch:"));
985   const uint32_t bytes_left = packet.GetBytesLeft();
986   if (bytes_left > 0) {
987     const char *arch_triple = packet.Peek();
988     m_process_launch_info.SetArchitecture(
989         HostInfo::GetAugmentedArchSpec(arch_triple));
990     return SendOKResponse();
991   }
992   return SendErrorResponse(13);
993 }
994 
995 GDBRemoteCommunication::PacketResult
996 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {
997   // The 'A' packet is the most over designed packet ever here with redundant
998   // argument indexes, redundant argument lengths and needed hex encoded
999   // argument string values. Really all that is needed is a comma separated hex
1000   // encoded argument value list, but we will stay true to the documented
1001   // version of the 'A' packet here...
1002 
1003   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1004   int actual_arg_index = 0;
1005 
1006   packet.SetFilePos(1); // Skip the 'A'
1007   bool success = true;
1008   while (success && packet.GetBytesLeft() > 0) {
1009     // Decode the decimal argument string length. This length is the number of
1010     // hex nibbles in the argument string value.
1011     const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1012     if (arg_len == UINT32_MAX)
1013       success = false;
1014     else {
1015       // Make sure the argument hex string length is followed by a comma
1016       if (packet.GetChar() != ',')
1017         success = false;
1018       else {
1019         // Decode the argument index. We ignore this really because who would
1020         // really send down the arguments in a random order???
1021         const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1022         if (arg_idx == UINT32_MAX)
1023           success = false;
1024         else {
1025           // Make sure the argument index is followed by a comma
1026           if (packet.GetChar() != ',')
1027             success = false;
1028           else {
1029             // Decode the argument string value from hex bytes back into a UTF8
1030             // string and make sure the length matches the one supplied in the
1031             // packet
1032             std::string arg;
1033             if (packet.GetHexByteStringFixedLength(arg, arg_len) !=
1034                 (arg_len / 2))
1035               success = false;
1036             else {
1037               // If there are any bytes left
1038               if (packet.GetBytesLeft()) {
1039                 if (packet.GetChar() != ',')
1040                   success = false;
1041               }
1042 
1043               if (success) {
1044                 if (arg_idx == 0)
1045                   m_process_launch_info.GetExecutableFile().SetFile(
1046                       arg, FileSpec::Style::native);
1047                 m_process_launch_info.GetArguments().AppendArgument(arg);
1048                 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg %d: \"%s\"",
1049                           __FUNCTION__, actual_arg_index, arg.c_str());
1050                 ++actual_arg_index;
1051               }
1052             }
1053           }
1054         }
1055       }
1056     }
1057   }
1058 
1059   if (success) {
1060     m_process_launch_error = LaunchProcess();
1061     if (m_process_launch_error.Success())
1062       return SendOKResponse();
1063     LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
1064   }
1065   return SendErrorResponse(8);
1066 }
1067 
1068 GDBRemoteCommunication::PacketResult
1069 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1070     StringExtractorGDBRemote &packet) {
1071   // Just echo back the exact same packet for qEcho...
1072   return SendPacketNoLock(packet.GetStringRef());
1073 }
1074 
1075 GDBRemoteCommunication::PacketResult
1076 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1077     StringExtractorGDBRemote &packet) {
1078   packet.SetFilePos(::strlen("qModuleInfo:"));
1079 
1080   std::string module_path;
1081   packet.GetHexByteStringTerminatedBy(module_path, ';');
1082   if (module_path.empty())
1083     return SendErrorResponse(1);
1084 
1085   if (packet.GetChar() != ';')
1086     return SendErrorResponse(2);
1087 
1088   std::string triple;
1089   packet.GetHexByteString(triple);
1090 
1091   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1092   if (!matched_module_spec.GetFileSpec())
1093     return SendErrorResponse(3);
1094 
1095   const auto file_offset = matched_module_spec.GetObjectOffset();
1096   const auto file_size = matched_module_spec.GetObjectSize();
1097   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1098 
1099   StreamGDBRemote response;
1100 
1101   if (uuid_str.empty()) {
1102     auto Result = llvm::sys::fs::md5_contents(
1103         matched_module_spec.GetFileSpec().GetPath());
1104     if (!Result)
1105       return SendErrorResponse(5);
1106     response.PutCString("md5:");
1107     response.PutStringAsRawHex8(Result->digest());
1108   } else {
1109     response.PutCString("uuid:");
1110     response.PutStringAsRawHex8(uuid_str);
1111   }
1112   response.PutChar(';');
1113 
1114   const auto &module_arch = matched_module_spec.GetArchitecture();
1115   response.PutCString("triple:");
1116   response.PutStringAsRawHex8(module_arch.GetTriple().getTriple());
1117   response.PutChar(';');
1118 
1119   response.PutCString("file_path:");
1120   response.PutStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1121   response.PutChar(';');
1122   response.PutCString("file_offset:");
1123   response.PutHex64(file_offset);
1124   response.PutChar(';');
1125   response.PutCString("file_size:");
1126   response.PutHex64(file_size);
1127   response.PutChar(';');
1128 
1129   return SendPacketNoLock(response.GetString());
1130 }
1131 
1132 GDBRemoteCommunication::PacketResult
1133 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1134     StringExtractorGDBRemote &packet) {
1135   namespace json = llvm::json;
1136 
1137   packet.SetFilePos(::strlen("jModulesInfo:"));
1138 
1139   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1140   if (!object_sp)
1141     return SendErrorResponse(1);
1142 
1143   StructuredData::Array *packet_array = object_sp->GetAsArray();
1144   if (!packet_array)
1145     return SendErrorResponse(2);
1146 
1147   json::Array response_array;
1148   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1149     StructuredData::Dictionary *query =
1150         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1151     if (!query)
1152       continue;
1153     llvm::StringRef file, triple;
1154     if (!query->GetValueForKeyAsString("file", file) ||
1155         !query->GetValueForKeyAsString("triple", triple))
1156       continue;
1157 
1158     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1159     if (!matched_module_spec.GetFileSpec())
1160       continue;
1161 
1162     const auto file_offset = matched_module_spec.GetObjectOffset();
1163     const auto file_size = matched_module_spec.GetObjectSize();
1164     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1165     if (uuid_str.empty())
1166       continue;
1167     const auto triple_str =
1168         matched_module_spec.GetArchitecture().GetTriple().getTriple();
1169     const auto file_path = matched_module_spec.GetFileSpec().GetPath();
1170 
1171     json::Object response{{"uuid", uuid_str},
1172                           {"triple", triple_str},
1173                           {"file_path", file_path},
1174                           {"file_offset", static_cast<int64_t>(file_offset)},
1175                           {"file_size", static_cast<int64_t>(file_size)}};
1176     response_array.push_back(std::move(response));
1177   }
1178 
1179   StreamString response;
1180   response.AsRawOstream() << std::move(response_array);
1181   StreamGDBRemote escaped_response;
1182   escaped_response.PutEscapedBytes(response.GetString().data(),
1183                                    response.GetSize());
1184   return SendPacketNoLock(escaped_response.GetString());
1185 }
1186 
1187 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1188     const ProcessInstanceInfo &proc_info, StreamString &response) {
1189   response.Printf(
1190       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1191       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1192       proc_info.GetUserID(), proc_info.GetGroupID(),
1193       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1194   response.PutCString("name:");
1195   response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1196 
1197   response.PutChar(';');
1198   response.PutCString("args:");
1199   response.PutStringAsRawHex8(proc_info.GetArg0());
1200   for (auto &arg : proc_info.GetArguments()) {
1201     response.PutChar('-');
1202     response.PutStringAsRawHex8(arg.ref());
1203   }
1204 
1205   response.PutChar(';');
1206   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1207   if (proc_arch.IsValid()) {
1208     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1209     response.PutCString("triple:");
1210     response.PutStringAsRawHex8(proc_triple.getTriple());
1211     response.PutChar(';');
1212   }
1213 }
1214 
1215 void GDBRemoteCommunicationServerCommon::
1216     CreateProcessInfoResponse_DebugServerStyle(
1217         const ProcessInstanceInfo &proc_info, StreamString &response) {
1218   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1219                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1220                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1221                   proc_info.GetUserID(), proc_info.GetGroupID(),
1222                   proc_info.GetEffectiveUserID(),
1223                   proc_info.GetEffectiveGroupID());
1224 
1225   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1226   if (proc_arch.IsValid()) {
1227     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1228 #if defined(__APPLE__)
1229     // We'll send cputype/cpusubtype.
1230     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1231     if (cpu_type != 0)
1232       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1233 
1234     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1235     if (cpu_subtype != 0)
1236       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1237 
1238     const std::string vendor = proc_triple.getVendorName().str();
1239     if (!vendor.empty())
1240       response.Printf("vendor:%s;", vendor.c_str());
1241 #else
1242     // We'll send the triple.
1243     response.PutCString("triple:");
1244     response.PutStringAsRawHex8(proc_triple.getTriple());
1245     response.PutChar(';');
1246 #endif
1247     std::string ostype = std::string(proc_triple.getOSName());
1248     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1249     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1250       switch (proc_triple.getArch()) {
1251       case llvm::Triple::arm:
1252       case llvm::Triple::thumb:
1253       case llvm::Triple::aarch64:
1254       case llvm::Triple::aarch64_32:
1255         ostype = "ios";
1256         break;
1257       default:
1258         // No change.
1259         break;
1260       }
1261     }
1262     response.Printf("ostype:%s;", ostype.c_str());
1263 
1264     switch (proc_arch.GetByteOrder()) {
1265     case lldb::eByteOrderLittle:
1266       response.PutCString("endian:little;");
1267       break;
1268     case lldb::eByteOrderBig:
1269       response.PutCString("endian:big;");
1270       break;
1271     case lldb::eByteOrderPDP:
1272       response.PutCString("endian:pdp;");
1273       break;
1274     default:
1275       // Nothing.
1276       break;
1277     }
1278     // In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer
1279     // size is 4 and for N64 it is 8
1280     std::string abi = proc_arch.GetTargetABI();
1281     if (!abi.empty())
1282       response.Printf("elf_abi:%s;", abi.c_str());
1283     response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());
1284   }
1285 }
1286 
1287 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(
1288     const std::string &module_path, const ArchSpec &arch) {
1289 #ifdef __ANDROID__
1290   return HostInfoAndroid::ResolveLibraryPath(module_path, arch);
1291 #else
1292   FileSpec file_spec(module_path);
1293   FileSystem::Instance().Resolve(file_spec);
1294   return file_spec;
1295 #endif
1296 }
1297 
1298 ModuleSpec
1299 GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path,
1300                                                   llvm::StringRef triple) {
1301   ArchSpec arch(triple);
1302 
1303   FileSpec req_module_path_spec(module_path);
1304   FileSystem::Instance().Resolve(req_module_path_spec);
1305 
1306   const FileSpec module_path_spec =
1307       FindModuleFile(req_module_path_spec.GetPath(), arch);
1308   const ModuleSpec module_spec(module_path_spec, arch);
1309 
1310   ModuleSpecList module_specs;
1311   if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0,
1312                                            module_specs))
1313     return ModuleSpec();
1314 
1315   ModuleSpec matched_module_spec;
1316   if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))
1317     return ModuleSpec();
1318 
1319   return matched_module_spec;
1320 }
1321 
1322 std::vector<std::string> GDBRemoteCommunicationServerCommon::HandleFeatures(
1323     const llvm::ArrayRef<llvm::StringRef> client_features) {
1324   // 128KBytes is a reasonable max packet size--debugger can always use less.
1325   constexpr uint32_t max_packet_size = 128 * 1024;
1326 
1327   // Features common to platform server and llgs.
1328   return {
1329       llvm::formatv("PacketSize={0}", max_packet_size),
1330       "QStartNoAckMode+",
1331       "qEcho+",
1332   };
1333 }
1334