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