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