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 <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_32 ||
235       host_arch.GetMachine() == llvm::Triple::aarch64_be ||
236       host_arch.GetMachine() == llvm::Triple::arm ||
237       host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS())
238     response.Printf("watchpoint_exceptions_received:before;");
239   else
240     response.Printf("watchpoint_exceptions_received:after;");
241 #endif
242 
243   switch (endian::InlHostByteOrder()) {
244   case eByteOrderBig:
245     response.PutCString("endian:big;");
246     break;
247   case eByteOrderLittle:
248     response.PutCString("endian:little;");
249     break;
250   case eByteOrderPDP:
251     response.PutCString("endian:pdp;");
252     break;
253   default:
254     response.PutCString("endian:unknown;");
255     break;
256   }
257 
258   llvm::VersionTuple version = HostInfo::GetOSVersion();
259   if (!version.empty()) {
260     response.Format("os_version:{0}", version.getAsString());
261     response.PutChar(';');
262   }
263 
264 #if defined(__APPLE__)
265   llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion();
266   if (!maccatalyst_version.empty()) {
267     response.Format("maccatalyst_version:{0}",
268                     maccatalyst_version.getAsString());
269     response.PutChar(';');
270   }
271 #endif
272 
273   std::string s;
274   if (HostInfo::GetOSBuildString(s)) {
275     response.PutCString("os_build:");
276     response.PutStringAsRawHex8(s);
277     response.PutChar(';');
278   }
279   if (HostInfo::GetOSKernelDescription(s)) {
280     response.PutCString("os_kernel:");
281     response.PutStringAsRawHex8(s);
282     response.PutChar(';');
283   }
284 
285 #if defined(__APPLE__)
286 
287 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
288   // For iOS devices, we are connected through a USB Mux so we never pretend to
289   // actually have a hostname as far as the remote lldb that is connecting to
290   // this lldb-platform is concerned
291   response.PutCString("hostname:");
292   response.PutStringAsRawHex8("127.0.0.1");
293   response.PutChar(';');
294 #else  // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
295   if (HostInfo::GetHostname(s)) {
296     response.PutCString("hostname:");
297     response.PutStringAsRawHex8(s);
298     response.PutChar(';');
299   }
300 #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
301 
302 #else  // #if defined(__APPLE__)
303   if (HostInfo::GetHostname(s)) {
304     response.PutCString("hostname:");
305     response.PutStringAsRawHex8(s);
306     response.PutChar(';');
307   }
308 #endif // #if defined(__APPLE__)
309 
310   if (g_default_packet_timeout_sec > 0)
311     response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec);
312 
313   return SendPacketNoLock(response.GetString());
314 }
315 
316 GDBRemoteCommunication::PacketResult
317 GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID(
318     StringExtractorGDBRemote &packet) {
319   // Packet format: "qProcessInfoPID:%i" where %i is the pid
320   packet.SetFilePos(::strlen("qProcessInfoPID:"));
321   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID);
322   if (pid != LLDB_INVALID_PROCESS_ID) {
323     ProcessInstanceInfo proc_info;
324     if (Host::GetProcessInfo(pid, proc_info)) {
325       StreamString response;
326       CreateProcessInfoResponse(proc_info, response);
327       return SendPacketNoLock(response.GetString());
328     }
329   }
330   return SendErrorResponse(1);
331 }
332 
333 GDBRemoteCommunication::PacketResult
334 GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo(
335     StringExtractorGDBRemote &packet) {
336   m_proc_infos_index = 0;
337   m_proc_infos.clear();
338 
339   ProcessInstanceInfoMatch match_info;
340   packet.SetFilePos(::strlen("qfProcessInfo"));
341   if (packet.GetChar() == ':') {
342     llvm::StringRef key;
343     llvm::StringRef value;
344     while (packet.GetNameColonValue(key, value)) {
345       bool success = true;
346       if (key.equals("name")) {
347         StringExtractor extractor(value);
348         std::string file;
349         extractor.GetHexByteString(file);
350         match_info.GetProcessInfo().GetExecutableFile().SetFile(
351             file, FileSpec::Style::native);
352       } else if (key.equals("name_match")) {
353         NameMatch name_match = llvm::StringSwitch<NameMatch>(value)
354                                    .Case("equals", NameMatch::Equals)
355                                    .Case("starts_with", NameMatch::StartsWith)
356                                    .Case("ends_with", NameMatch::EndsWith)
357                                    .Case("contains", NameMatch::Contains)
358                                    .Case("regex", NameMatch::RegularExpression)
359                                    .Default(NameMatch::Ignore);
360         match_info.SetNameMatchType(name_match);
361         if (name_match == NameMatch::Ignore)
362           return SendErrorResponse(2);
363       } else if (key.equals("pid")) {
364         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
365         if (value.getAsInteger(0, pid))
366           return SendErrorResponse(2);
367         match_info.GetProcessInfo().SetProcessID(pid);
368       } else if (key.equals("parent_pid")) {
369         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
370         if (value.getAsInteger(0, pid))
371           return SendErrorResponse(2);
372         match_info.GetProcessInfo().SetParentProcessID(pid);
373       } else if (key.equals("uid")) {
374         uint32_t uid = UINT32_MAX;
375         if (value.getAsInteger(0, uid))
376           return SendErrorResponse(2);
377         match_info.GetProcessInfo().SetUserID(uid);
378       } else if (key.equals("gid")) {
379         uint32_t gid = UINT32_MAX;
380         if (value.getAsInteger(0, gid))
381           return SendErrorResponse(2);
382         match_info.GetProcessInfo().SetGroupID(gid);
383       } else if (key.equals("euid")) {
384         uint32_t uid = UINT32_MAX;
385         if (value.getAsInteger(0, uid))
386           return SendErrorResponse(2);
387         match_info.GetProcessInfo().SetEffectiveUserID(uid);
388       } else if (key.equals("egid")) {
389         uint32_t gid = UINT32_MAX;
390         if (value.getAsInteger(0, gid))
391           return SendErrorResponse(2);
392         match_info.GetProcessInfo().SetEffectiveGroupID(gid);
393       } else if (key.equals("all_users")) {
394         match_info.SetMatchAllUsers(
395             OptionArgParser::ToBoolean(value, false, &success));
396       } else if (key.equals("triple")) {
397         match_info.GetProcessInfo().GetArchitecture() =
398             HostInfo::GetAugmentedArchSpec(value);
399       } else {
400         success = false;
401       }
402 
403       if (!success)
404         return SendErrorResponse(2);
405     }
406   }
407 
408   if (Host::FindProcesses(match_info, m_proc_infos)) {
409     // We found something, return the first item by calling the get subsequent
410     // process info packet handler...
411     return Handle_qsProcessInfo(packet);
412   }
413   return SendErrorResponse(3);
414 }
415 
416 GDBRemoteCommunication::PacketResult
417 GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(
418     StringExtractorGDBRemote &packet) {
419   if (m_proc_infos_index < m_proc_infos.size()) {
420     StreamString response;
421     CreateProcessInfoResponse(m_proc_infos[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 LLDB_ENABLE_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 LLDB_ENABLE_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       // FIXME
511       // The flag values for OpenOptions do not match the values used by GDB
512       // * https://sourceware.org/gdb/onlinedocs/gdb/Open-Flags.html#Open-Flags
513       // * rdar://problem/46788934
514       auto flags = File::OpenOptions(packet.GetHexMaxU32(false, 0));
515       if (packet.GetChar() == ',') {
516         mode_t mode = packet.GetHexMaxU32(false, 0600);
517         FileSpec path_spec(path);
518         FileSystem::Instance().Resolve(path_spec);
519         // Do not close fd.
520         auto file = FileSystem::Instance().Open(path_spec, flags, mode, false);
521 
522         int save_errno = 0;
523         int descriptor = File::kInvalidDescriptor;
524         if (file) {
525           descriptor = file.get()->GetDescriptor();
526         } else {
527           std::error_code code = errorToErrorCode(file.takeError());
528           if (code.category() == std::system_category()) {
529             save_errno = code.value();
530           }
531         }
532 
533         StreamString response;
534         response.PutChar('F');
535         response.Printf("%i", descriptor);
536         if (save_errno)
537           response.Printf(",%i", save_errno);
538         return SendPacketNoLock(response.GetString());
539       }
540     }
541   }
542   return SendErrorResponse(18);
543 }
544 
545 GDBRemoteCommunication::PacketResult
546 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
547     StringExtractorGDBRemote &packet) {
548   packet.SetFilePos(::strlen("vFile:close:"));
549   int fd = packet.GetS32(-1);
550   int err = -1;
551   int save_errno = 0;
552   if (fd >= 0) {
553     NativeFile file(fd, File::OpenOptions(0), true);
554     Status error = file.Close();
555     err = 0;
556     save_errno = error.GetError();
557   } else {
558     save_errno = EINVAL;
559   }
560   StreamString response;
561   response.PutChar('F');
562   response.Printf("%i", err);
563   if (save_errno)
564     response.Printf(",%i", save_errno);
565   return SendPacketNoLock(response.GetString());
566 }
567 
568 GDBRemoteCommunication::PacketResult
569 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
570     StringExtractorGDBRemote &packet) {
571   StreamGDBRemote response;
572   packet.SetFilePos(::strlen("vFile:pread:"));
573   int fd = packet.GetS32(-1);
574   if (packet.GetChar() == ',') {
575     size_t count = packet.GetU64(SIZE_MAX);
576     if (packet.GetChar() == ',') {
577       off_t offset = packet.GetU64(UINT32_MAX);
578       if (count == SIZE_MAX) {
579         response.Printf("F-1:%i", EINVAL);
580         return SendPacketNoLock(response.GetString());
581       }
582 
583       std::string buffer(count, 0);
584       NativeFile file(fd, File::eOpenOptionRead, false);
585       Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset);
586       const ssize_t bytes_read = error.Success() ? count : -1;
587       const int save_errno = error.GetError();
588       response.PutChar('F');
589       response.Printf("%zi", bytes_read);
590       if (save_errno)
591         response.Printf(",%i", save_errno);
592       else {
593         response.PutChar(';');
594         response.PutEscapedBytes(&buffer[0], bytes_read);
595       }
596       return SendPacketNoLock(response.GetString());
597     }
598   }
599   return SendErrorResponse(21);
600 }
601 
602 GDBRemoteCommunication::PacketResult
603 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
604     StringExtractorGDBRemote &packet) {
605   packet.SetFilePos(::strlen("vFile:pwrite:"));
606 
607   StreamGDBRemote response;
608   response.PutChar('F');
609 
610   int fd = packet.GetU32(UINT32_MAX);
611   if (packet.GetChar() == ',') {
612     off_t offset = packet.GetU64(UINT32_MAX);
613     if (packet.GetChar() == ',') {
614       std::string buffer;
615       if (packet.GetEscapedBinaryData(buffer)) {
616         NativeFile file(fd, File::eOpenOptionWrite, false);
617         size_t count = buffer.size();
618         Status error =
619             file.Write(static_cast<const void *>(&buffer[0]), count, offset);
620         const ssize_t bytes_written = error.Success() ? count : -1;
621         const int save_errno = error.GetError();
622         response.Printf("%zi", bytes_written);
623         if (save_errno)
624           response.Printf(",%i", save_errno);
625       } else {
626         response.Printf("-1,%i", EINVAL);
627       }
628       return SendPacketNoLock(response.GetString());
629     }
630   }
631   return SendErrorResponse(27);
632 }
633 
634 GDBRemoteCommunication::PacketResult
635 GDBRemoteCommunicationServerCommon::Handle_vFile_Size(
636     StringExtractorGDBRemote &packet) {
637   packet.SetFilePos(::strlen("vFile:size:"));
638   std::string path;
639   packet.GetHexByteString(path);
640   if (!path.empty()) {
641     uint64_t Size;
642     if (llvm::sys::fs::file_size(path, Size))
643       return SendErrorResponse(5);
644     StreamString response;
645     response.PutChar('F');
646     response.PutHex64(Size);
647     if (Size == UINT64_MAX) {
648       response.PutChar(',');
649       response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode()
650     }
651     return SendPacketNoLock(response.GetString());
652   }
653   return SendErrorResponse(22);
654 }
655 
656 GDBRemoteCommunication::PacketResult
657 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(
658     StringExtractorGDBRemote &packet) {
659   packet.SetFilePos(::strlen("vFile:mode:"));
660   std::string path;
661   packet.GetHexByteString(path);
662   if (!path.empty()) {
663     FileSpec file_spec(path);
664     FileSystem::Instance().Resolve(file_spec);
665     std::error_code ec;
666     const uint32_t mode = FileSystem::Instance().GetPermissions(file_spec, ec);
667     StreamString response;
668     response.Printf("F%u", mode);
669     if (mode == 0 || ec)
670       response.Printf(",%i", (int)Status(ec).GetError());
671     return SendPacketNoLock(response.GetString());
672   }
673   return SendErrorResponse(23);
674 }
675 
676 GDBRemoteCommunication::PacketResult
677 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(
678     StringExtractorGDBRemote &packet) {
679   packet.SetFilePos(::strlen("vFile:exists:"));
680   std::string path;
681   packet.GetHexByteString(path);
682   if (!path.empty()) {
683     bool retcode = llvm::sys::fs::exists(path);
684     StreamString response;
685     response.PutChar('F');
686     response.PutChar(',');
687     if (retcode)
688       response.PutChar('1');
689     else
690       response.PutChar('0');
691     return SendPacketNoLock(response.GetString());
692   }
693   return SendErrorResponse(24);
694 }
695 
696 GDBRemoteCommunication::PacketResult
697 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(
698     StringExtractorGDBRemote &packet) {
699   packet.SetFilePos(::strlen("vFile:symlink:"));
700   std::string dst, src;
701   packet.GetHexByteStringTerminatedBy(dst, ',');
702   packet.GetChar(); // Skip ',' char
703   packet.GetHexByteString(src);
704 
705   FileSpec src_spec(src);
706   FileSystem::Instance().Resolve(src_spec);
707   Status error = FileSystem::Instance().Symlink(src_spec, FileSpec(dst));
708 
709   StreamString response;
710   response.Printf("F%u,%u", error.GetError(), error.GetError());
711   return SendPacketNoLock(response.GetString());
712 }
713 
714 GDBRemoteCommunication::PacketResult
715 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(
716     StringExtractorGDBRemote &packet) {
717   packet.SetFilePos(::strlen("vFile:unlink:"));
718   std::string path;
719   packet.GetHexByteString(path);
720   Status error(llvm::sys::fs::remove(path));
721   StreamString response;
722   response.Printf("F%u,%u", error.GetError(), error.GetError());
723   return SendPacketNoLock(response.GetString());
724 }
725 
726 GDBRemoteCommunication::PacketResult
727 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(
728     StringExtractorGDBRemote &packet) {
729   packet.SetFilePos(::strlen("qPlatform_shell:"));
730   std::string path;
731   std::string working_dir;
732   packet.GetHexByteStringTerminatedBy(path, ',');
733   if (!path.empty()) {
734     if (packet.GetChar() == ',') {
735       // FIXME: add timeout to qPlatform_shell packet
736       // uint32_t timeout = packet.GetHexMaxU32(false, 32);
737       if (packet.GetChar() == ',')
738         packet.GetHexByteString(working_dir);
739       int status, signo;
740       std::string output;
741       FileSpec working_spec(working_dir);
742       FileSystem::Instance().Resolve(working_spec);
743       Status err =
744           Host::RunShellCommand(path.c_str(), working_spec, &status, &signo,
745                                 &output, std::chrono::seconds(10));
746       StreamGDBRemote response;
747       if (err.Fail()) {
748         response.PutCString("F,");
749         response.PutHex32(UINT32_MAX);
750       } else {
751         response.PutCString("F,");
752         response.PutHex32(status);
753         response.PutChar(',');
754         response.PutHex32(signo);
755         response.PutChar(',');
756         response.PutEscapedBytes(output.c_str(), output.size());
757       }
758       return SendPacketNoLock(response.GetString());
759     }
760   }
761   return SendErrorResponse(24);
762 }
763 
764 GDBRemoteCommunication::PacketResult
765 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(
766     StringExtractorGDBRemote &packet) {
767   return SendUnimplementedResponse(
768       "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");
769 }
770 
771 GDBRemoteCommunication::PacketResult
772 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(
773     StringExtractorGDBRemote &packet) {
774   packet.SetFilePos(::strlen("vFile:MD5:"));
775   std::string path;
776   packet.GetHexByteString(path);
777   if (!path.empty()) {
778     StreamGDBRemote response;
779     auto Result = llvm::sys::fs::md5_contents(path);
780     if (!Result) {
781       response.PutCString("F,");
782       response.PutCString("x");
783     } else {
784       response.PutCString("F,");
785       response.PutHex64(Result->low());
786       response.PutHex64(Result->high());
787     }
788     return SendPacketNoLock(response.GetString());
789   }
790   return SendErrorResponse(25);
791 }
792 
793 GDBRemoteCommunication::PacketResult
794 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(
795     StringExtractorGDBRemote &packet) {
796   packet.SetFilePos(::strlen("qPlatform_mkdir:"));
797   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
798   if (packet.GetChar() == ',') {
799     std::string path;
800     packet.GetHexByteString(path);
801     Status error(llvm::sys::fs::create_directory(path, mode));
802 
803     StreamGDBRemote response;
804     response.Printf("F%u", error.GetError());
805 
806     return SendPacketNoLock(response.GetString());
807   }
808   return SendErrorResponse(20);
809 }
810 
811 GDBRemoteCommunication::PacketResult
812 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(
813     StringExtractorGDBRemote &packet) {
814   packet.SetFilePos(::strlen("qPlatform_chmod:"));
815 
816   auto perms =
817       static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX));
818   if (packet.GetChar() == ',') {
819     std::string path;
820     packet.GetHexByteString(path);
821     Status error(llvm::sys::fs::setPermissions(path, perms));
822 
823     StreamGDBRemote response;
824     response.Printf("F%u", error.GetError());
825 
826     return SendPacketNoLock(response.GetString());
827   }
828   return SendErrorResponse(19);
829 }
830 
831 GDBRemoteCommunication::PacketResult
832 GDBRemoteCommunicationServerCommon::Handle_qSupported(
833     StringExtractorGDBRemote &packet) {
834   // Parse client-indicated features.
835   llvm::SmallVector<llvm::StringRef, 4> client_features;
836   packet.GetStringRef().split(client_features, ';');
837   return SendPacketNoLock(llvm::join(HandleFeatures(client_features), ";"));
838 }
839 
840 GDBRemoteCommunication::PacketResult
841 GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported(
842     StringExtractorGDBRemote &packet) {
843   m_thread_suffix_supported = true;
844   return SendOKResponse();
845 }
846 
847 GDBRemoteCommunication::PacketResult
848 GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply(
849     StringExtractorGDBRemote &packet) {
850   m_list_threads_in_stop_reply = true;
851   return SendOKResponse();
852 }
853 
854 GDBRemoteCommunication::PacketResult
855 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
856     StringExtractorGDBRemote &packet) {
857   packet.SetFilePos(::strlen("QSetDetachOnError:"));
858   if (packet.GetU32(0))
859     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
860   else
861     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
862   return SendOKResponse();
863 }
864 
865 GDBRemoteCommunication::PacketResult
866 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
867     StringExtractorGDBRemote &packet) {
868   // Send response first before changing m_send_acks to we ack this packet
869   PacketResult packet_result = SendOKResponse();
870   m_send_acks = false;
871   return packet_result;
872 }
873 
874 GDBRemoteCommunication::PacketResult
875 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
876     StringExtractorGDBRemote &packet) {
877   packet.SetFilePos(::strlen("QSetSTDIN:"));
878   FileAction file_action;
879   std::string path;
880   packet.GetHexByteString(path);
881   const bool read = true;
882   const bool write = false;
883   if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) {
884     m_process_launch_info.AppendFileAction(file_action);
885     return SendOKResponse();
886   }
887   return SendErrorResponse(15);
888 }
889 
890 GDBRemoteCommunication::PacketResult
891 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
892     StringExtractorGDBRemote &packet) {
893   packet.SetFilePos(::strlen("QSetSTDOUT:"));
894   FileAction file_action;
895   std::string path;
896   packet.GetHexByteString(path);
897   const bool read = false;
898   const bool write = true;
899   if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) {
900     m_process_launch_info.AppendFileAction(file_action);
901     return SendOKResponse();
902   }
903   return SendErrorResponse(16);
904 }
905 
906 GDBRemoteCommunication::PacketResult
907 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
908     StringExtractorGDBRemote &packet) {
909   packet.SetFilePos(::strlen("QSetSTDERR:"));
910   FileAction file_action;
911   std::string path;
912   packet.GetHexByteString(path);
913   const bool read = false;
914   const bool write = true;
915   if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) {
916     m_process_launch_info.AppendFileAction(file_action);
917     return SendOKResponse();
918   }
919   return SendErrorResponse(17);
920 }
921 
922 GDBRemoteCommunication::PacketResult
923 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
924     StringExtractorGDBRemote &packet) {
925   if (m_process_launch_error.Success())
926     return SendOKResponse();
927   StreamString response;
928   response.PutChar('E');
929   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
930   return SendPacketNoLock(response.GetString());
931 }
932 
933 GDBRemoteCommunication::PacketResult
934 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
935     StringExtractorGDBRemote &packet) {
936   packet.SetFilePos(::strlen("QEnvironment:"));
937   const uint32_t bytes_left = packet.GetBytesLeft();
938   if (bytes_left > 0) {
939     m_process_launch_info.GetEnvironment().insert(packet.Peek());
940     return SendOKResponse();
941   }
942   return SendErrorResponse(12);
943 }
944 
945 GDBRemoteCommunication::PacketResult
946 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
947     StringExtractorGDBRemote &packet) {
948   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
949   const uint32_t bytes_left = packet.GetBytesLeft();
950   if (bytes_left > 0) {
951     std::string str;
952     packet.GetHexByteString(str);
953     m_process_launch_info.GetEnvironment().insert(str);
954     return SendOKResponse();
955   }
956   return SendErrorResponse(12);
957 }
958 
959 GDBRemoteCommunication::PacketResult
960 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
961     StringExtractorGDBRemote &packet) {
962   packet.SetFilePos(::strlen("QLaunchArch:"));
963   const uint32_t bytes_left = packet.GetBytesLeft();
964   if (bytes_left > 0) {
965     const char *arch_triple = packet.Peek();
966     m_process_launch_info.SetArchitecture(
967         HostInfo::GetAugmentedArchSpec(arch_triple));
968     return SendOKResponse();
969   }
970   return SendErrorResponse(13);
971 }
972 
973 GDBRemoteCommunication::PacketResult
974 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {
975   // The 'A' packet is the most over designed packet ever here with redundant
976   // argument indexes, redundant argument lengths and needed hex encoded
977   // argument string values. Really all that is needed is a comma separated hex
978   // encoded argument value list, but we will stay true to the documented
979   // version of the 'A' packet here...
980 
981   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
982   int actual_arg_index = 0;
983 
984   packet.SetFilePos(1); // Skip the 'A'
985   bool success = true;
986   while (success && packet.GetBytesLeft() > 0) {
987     // Decode the decimal argument string length. This length is the number of
988     // hex nibbles in the argument string value.
989     const uint32_t arg_len = packet.GetU32(UINT32_MAX);
990     if (arg_len == UINT32_MAX)
991       success = false;
992     else {
993       // Make sure the argument hex string length is followed by a comma
994       if (packet.GetChar() != ',')
995         success = false;
996       else {
997         // Decode the argument index. We ignore this really because who would
998         // really send down the arguments in a random order???
999         const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1000         if (arg_idx == UINT32_MAX)
1001           success = false;
1002         else {
1003           // Make sure the argument index is followed by a comma
1004           if (packet.GetChar() != ',')
1005             success = false;
1006           else {
1007             // Decode the argument string value from hex bytes back into a UTF8
1008             // string and make sure the length matches the one supplied in the
1009             // packet
1010             std::string arg;
1011             if (packet.GetHexByteStringFixedLength(arg, arg_len) !=
1012                 (arg_len / 2))
1013               success = false;
1014             else {
1015               // If there are any bytes left
1016               if (packet.GetBytesLeft()) {
1017                 if (packet.GetChar() != ',')
1018                   success = false;
1019               }
1020 
1021               if (success) {
1022                 if (arg_idx == 0)
1023                   m_process_launch_info.GetExecutableFile().SetFile(
1024                       arg, FileSpec::Style::native);
1025                 m_process_launch_info.GetArguments().AppendArgument(arg);
1026                 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg %d: \"%s\"",
1027                           __FUNCTION__, actual_arg_index, arg.c_str());
1028                 ++actual_arg_index;
1029               }
1030             }
1031           }
1032         }
1033       }
1034     }
1035   }
1036 
1037   if (success) {
1038     m_process_launch_error = LaunchProcess();
1039     if (m_process_launch_error.Success())
1040       return SendOKResponse();
1041     LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
1042   }
1043   return SendErrorResponse(8);
1044 }
1045 
1046 GDBRemoteCommunication::PacketResult
1047 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1048     StringExtractorGDBRemote &packet) {
1049   // Just echo back the exact same packet for qEcho...
1050   return SendPacketNoLock(packet.GetStringRef());
1051 }
1052 
1053 GDBRemoteCommunication::PacketResult
1054 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1055     StringExtractorGDBRemote &packet) {
1056   packet.SetFilePos(::strlen("qModuleInfo:"));
1057 
1058   std::string module_path;
1059   packet.GetHexByteStringTerminatedBy(module_path, ';');
1060   if (module_path.empty())
1061     return SendErrorResponse(1);
1062 
1063   if (packet.GetChar() != ';')
1064     return SendErrorResponse(2);
1065 
1066   std::string triple;
1067   packet.GetHexByteString(triple);
1068 
1069   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1070   if (!matched_module_spec.GetFileSpec())
1071     return SendErrorResponse(3);
1072 
1073   const auto file_offset = matched_module_spec.GetObjectOffset();
1074   const auto file_size = matched_module_spec.GetObjectSize();
1075   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1076 
1077   StreamGDBRemote response;
1078 
1079   if (uuid_str.empty()) {
1080     auto Result = llvm::sys::fs::md5_contents(
1081         matched_module_spec.GetFileSpec().GetPath());
1082     if (!Result)
1083       return SendErrorResponse(5);
1084     response.PutCString("md5:");
1085     response.PutStringAsRawHex8(Result->digest());
1086   } else {
1087     response.PutCString("uuid:");
1088     response.PutStringAsRawHex8(uuid_str);
1089   }
1090   response.PutChar(';');
1091 
1092   const auto &module_arch = matched_module_spec.GetArchitecture();
1093   response.PutCString("triple:");
1094   response.PutStringAsRawHex8(module_arch.GetTriple().getTriple());
1095   response.PutChar(';');
1096 
1097   response.PutCString("file_path:");
1098   response.PutStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1099   response.PutChar(';');
1100   response.PutCString("file_offset:");
1101   response.PutHex64(file_offset);
1102   response.PutChar(';');
1103   response.PutCString("file_size:");
1104   response.PutHex64(file_size);
1105   response.PutChar(';');
1106 
1107   return SendPacketNoLock(response.GetString());
1108 }
1109 
1110 GDBRemoteCommunication::PacketResult
1111 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1112     StringExtractorGDBRemote &packet) {
1113   namespace json = llvm::json;
1114 
1115   packet.SetFilePos(::strlen("jModulesInfo:"));
1116 
1117   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1118   if (!object_sp)
1119     return SendErrorResponse(1);
1120 
1121   StructuredData::Array *packet_array = object_sp->GetAsArray();
1122   if (!packet_array)
1123     return SendErrorResponse(2);
1124 
1125   json::Array response_array;
1126   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1127     StructuredData::Dictionary *query =
1128         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1129     if (!query)
1130       continue;
1131     llvm::StringRef file, triple;
1132     if (!query->GetValueForKeyAsString("file", file) ||
1133         !query->GetValueForKeyAsString("triple", triple))
1134       continue;
1135 
1136     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1137     if (!matched_module_spec.GetFileSpec())
1138       continue;
1139 
1140     const auto file_offset = matched_module_spec.GetObjectOffset();
1141     const auto file_size = matched_module_spec.GetObjectSize();
1142     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1143     if (uuid_str.empty())
1144       continue;
1145     const auto triple_str =
1146         matched_module_spec.GetArchitecture().GetTriple().getTriple();
1147     const auto file_path = matched_module_spec.GetFileSpec().GetPath();
1148 
1149     json::Object response{{"uuid", uuid_str},
1150                           {"triple", triple_str},
1151                           {"file_path", file_path},
1152                           {"file_offset", static_cast<int64_t>(file_offset)},
1153                           {"file_size", static_cast<int64_t>(file_size)}};
1154     response_array.push_back(std::move(response));
1155   }
1156 
1157   StreamString response;
1158   response.AsRawOstream() << std::move(response_array);
1159   StreamGDBRemote escaped_response;
1160   escaped_response.PutEscapedBytes(response.GetString().data(),
1161                                    response.GetSize());
1162   return SendPacketNoLock(escaped_response.GetString());
1163 }
1164 
1165 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1166     const ProcessInstanceInfo &proc_info, StreamString &response) {
1167   response.Printf(
1168       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1169       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1170       proc_info.GetUserID(), proc_info.GetGroupID(),
1171       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1172   response.PutCString("name:");
1173   response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1174 
1175   response.PutChar(';');
1176   response.PutCString("args:");
1177   response.PutStringAsRawHex8(proc_info.GetArg0());
1178   for (auto &arg : proc_info.GetArguments()) {
1179     response.PutChar('-');
1180     response.PutStringAsRawHex8(arg.ref());
1181   }
1182 
1183   response.PutChar(';');
1184   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1185   if (proc_arch.IsValid()) {
1186     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1187     response.PutCString("triple:");
1188     response.PutStringAsRawHex8(proc_triple.getTriple());
1189     response.PutChar(';');
1190   }
1191 }
1192 
1193 void GDBRemoteCommunicationServerCommon::
1194     CreateProcessInfoResponse_DebugServerStyle(
1195         const ProcessInstanceInfo &proc_info, StreamString &response) {
1196   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1197                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1198                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1199                   proc_info.GetUserID(), proc_info.GetGroupID(),
1200                   proc_info.GetEffectiveUserID(),
1201                   proc_info.GetEffectiveGroupID());
1202 
1203   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1204   if (proc_arch.IsValid()) {
1205     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1206 #if defined(__APPLE__)
1207     // We'll send cputype/cpusubtype.
1208     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1209     if (cpu_type != 0)
1210       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1211 
1212     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1213     if (cpu_subtype != 0)
1214       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1215 
1216     const std::string vendor = proc_triple.getVendorName().str();
1217     if (!vendor.empty())
1218       response.Printf("vendor:%s;", vendor.c_str());
1219 #else
1220     // We'll send the triple.
1221     response.PutCString("triple:");
1222     response.PutStringAsRawHex8(proc_triple.getTriple());
1223     response.PutChar(';');
1224 #endif
1225     std::string ostype = std::string(proc_triple.getOSName());
1226     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1227     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1228       switch (proc_triple.getArch()) {
1229       case llvm::Triple::arm:
1230       case llvm::Triple::thumb:
1231       case llvm::Triple::aarch64:
1232       case llvm::Triple::aarch64_32:
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 
1300 std::vector<std::string> GDBRemoteCommunicationServerCommon::HandleFeatures(
1301     const llvm::ArrayRef<llvm::StringRef> client_features) {
1302   // 128KBytes is a reasonable max packet size--debugger can always use less.
1303   constexpr uint32_t max_packet_size = 128 * 1024;
1304 
1305   // Features common to platform server and llgs.
1306   return {
1307       llvm::formatv("PacketSize={0}", max_packet_size),
1308       "QStartNoAckMode+",
1309       "QThreadSuffixSupported+",
1310       "QListThreadsInStopReply+",
1311       "qEcho+",
1312   };
1313 }
1314