1 //===-- GDBRemoteCommunicationServerCommon.cpp ------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "GDBRemoteCommunicationServerCommon.h"
10 
11 #include <errno.h>
12 
13 #ifdef __APPLE__
14 #include <TargetConditionals.h>
15 #endif
16 
17 #include <chrono>
18 #include <cstring>
19 
20 #include "lldb/Core/ModuleSpec.h"
21 #include "lldb/Host/Config.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileAction.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/SafeMachO.h"
28 #include "lldb/Interpreter/OptionArgParser.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Target/Platform.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Utility/Endian.h"
33 #include "lldb/Utility/JSON.h"
34 #include "lldb/Utility/Log.h"
35 #include "lldb/Utility/StreamGDBRemote.h"
36 #include "lldb/Utility/StreamString.h"
37 #include "llvm/ADT/Triple.h"
38 
39 #include "ProcessGDBRemoteLog.h"
40 #include "lldb/Utility/StringExtractorGDBRemote.h"
41 
42 #ifdef __ANDROID__
43 #include "lldb/Host/android/HostInfoAndroid.h"
44 #endif
45 
46 #include "llvm/ADT/StringSwitch.h"
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 using namespace lldb_private::process_gdb_remote;
51 
52 #ifdef __ANDROID__
53 const static uint32_t g_default_packet_timeout_sec = 20; // seconds
54 #else
55 const static uint32_t g_default_packet_timeout_sec = 0; // not specified
56 #endif
57 
58 // GDBRemoteCommunicationServerCommon constructor
59 GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon(
60     const char *comm_name, const char *listener_name)
61     : GDBRemoteCommunicationServer(comm_name, listener_name),
62       m_process_launch_info(), m_process_launch_error(), m_proc_infos(),
63       m_proc_infos_index(0), m_thread_suffix_supported(false),
64       m_list_threads_in_stop_reply(false) {
65   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A,
66                                 &GDBRemoteCommunicationServerCommon::Handle_A);
67   RegisterMemberFunctionHandler(
68       StringExtractorGDBRemote::eServerPacketType_QEnvironment,
69       &GDBRemoteCommunicationServerCommon::Handle_QEnvironment);
70   RegisterMemberFunctionHandler(
71       StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded,
72       &GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded);
73   RegisterMemberFunctionHandler(
74       StringExtractorGDBRemote::eServerPacketType_qfProcessInfo,
75       &GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo);
76   RegisterMemberFunctionHandler(
77       StringExtractorGDBRemote::eServerPacketType_qGroupName,
78       &GDBRemoteCommunicationServerCommon::Handle_qGroupName);
79   RegisterMemberFunctionHandler(
80       StringExtractorGDBRemote::eServerPacketType_qHostInfo,
81       &GDBRemoteCommunicationServerCommon::Handle_qHostInfo);
82   RegisterMemberFunctionHandler(
83       StringExtractorGDBRemote::eServerPacketType_QLaunchArch,
84       &GDBRemoteCommunicationServerCommon::Handle_QLaunchArch);
85   RegisterMemberFunctionHandler(
86       StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess,
87       &GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess);
88   RegisterMemberFunctionHandler(
89       StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
90       &GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply);
91   RegisterMemberFunctionHandler(
92       StringExtractorGDBRemote::eServerPacketType_qEcho,
93       &GDBRemoteCommunicationServerCommon::Handle_qEcho);
94   RegisterMemberFunctionHandler(
95       StringExtractorGDBRemote::eServerPacketType_qModuleInfo,
96       &GDBRemoteCommunicationServerCommon::Handle_qModuleInfo);
97   RegisterMemberFunctionHandler(
98       StringExtractorGDBRemote::eServerPacketType_jModulesInfo,
99       &GDBRemoteCommunicationServerCommon::Handle_jModulesInfo);
100   RegisterMemberFunctionHandler(
101       StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod,
102       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod);
103   RegisterMemberFunctionHandler(
104       StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir,
105       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir);
106   RegisterMemberFunctionHandler(
107       StringExtractorGDBRemote::eServerPacketType_qPlatform_shell,
108       &GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell);
109   RegisterMemberFunctionHandler(
110       StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID,
111       &GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID);
112   RegisterMemberFunctionHandler(
113       StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError,
114       &GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError);
115   RegisterMemberFunctionHandler(
116       StringExtractorGDBRemote::eServerPacketType_QSetSTDERR,
117       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR);
118   RegisterMemberFunctionHandler(
119       StringExtractorGDBRemote::eServerPacketType_QSetSTDIN,
120       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN);
121   RegisterMemberFunctionHandler(
122       StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT,
123       &GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT);
124   RegisterMemberFunctionHandler(
125       StringExtractorGDBRemote::eServerPacketType_qSpeedTest,
126       &GDBRemoteCommunicationServerCommon::Handle_qSpeedTest);
127   RegisterMemberFunctionHandler(
128       StringExtractorGDBRemote::eServerPacketType_qsProcessInfo,
129       &GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo);
130   RegisterMemberFunctionHandler(
131       StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode,
132       &GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode);
133   RegisterMemberFunctionHandler(
134       StringExtractorGDBRemote::eServerPacketType_qSupported,
135       &GDBRemoteCommunicationServerCommon::Handle_qSupported);
136   RegisterMemberFunctionHandler(
137       StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
138       &GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported);
139   RegisterMemberFunctionHandler(
140       StringExtractorGDBRemote::eServerPacketType_qUserName,
141       &GDBRemoteCommunicationServerCommon::Handle_qUserName);
142   RegisterMemberFunctionHandler(
143       StringExtractorGDBRemote::eServerPacketType_vFile_close,
144       &GDBRemoteCommunicationServerCommon::Handle_vFile_Close);
145   RegisterMemberFunctionHandler(
146       StringExtractorGDBRemote::eServerPacketType_vFile_exists,
147       &GDBRemoteCommunicationServerCommon::Handle_vFile_Exists);
148   RegisterMemberFunctionHandler(
149       StringExtractorGDBRemote::eServerPacketType_vFile_md5,
150       &GDBRemoteCommunicationServerCommon::Handle_vFile_MD5);
151   RegisterMemberFunctionHandler(
152       StringExtractorGDBRemote::eServerPacketType_vFile_mode,
153       &GDBRemoteCommunicationServerCommon::Handle_vFile_Mode);
154   RegisterMemberFunctionHandler(
155       StringExtractorGDBRemote::eServerPacketType_vFile_open,
156       &GDBRemoteCommunicationServerCommon::Handle_vFile_Open);
157   RegisterMemberFunctionHandler(
158       StringExtractorGDBRemote::eServerPacketType_vFile_pread,
159       &GDBRemoteCommunicationServerCommon::Handle_vFile_pRead);
160   RegisterMemberFunctionHandler(
161       StringExtractorGDBRemote::eServerPacketType_vFile_pwrite,
162       &GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite);
163   RegisterMemberFunctionHandler(
164       StringExtractorGDBRemote::eServerPacketType_vFile_size,
165       &GDBRemoteCommunicationServerCommon::Handle_vFile_Size);
166   RegisterMemberFunctionHandler(
167       StringExtractorGDBRemote::eServerPacketType_vFile_stat,
168       &GDBRemoteCommunicationServerCommon::Handle_vFile_Stat);
169   RegisterMemberFunctionHandler(
170       StringExtractorGDBRemote::eServerPacketType_vFile_symlink,
171       &GDBRemoteCommunicationServerCommon::Handle_vFile_symlink);
172   RegisterMemberFunctionHandler(
173       StringExtractorGDBRemote::eServerPacketType_vFile_unlink,
174       &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink);
175 }
176 
177 // Destructor
178 GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() {}
179 
180 GDBRemoteCommunication::PacketResult
181 GDBRemoteCommunicationServerCommon::Handle_qHostInfo(
182     StringExtractorGDBRemote &packet) {
183   StreamString response;
184 
185   // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
186 
187   ArchSpec host_arch(HostInfo::GetArchitecture());
188   const llvm::Triple &host_triple = host_arch.GetTriple();
189   response.PutCString("triple:");
190   response.PutStringAsRawHex8(host_triple.getTriple());
191   response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize());
192 
193   const char *distribution_id = host_arch.GetDistributionId().AsCString();
194   if (distribution_id) {
195     response.PutCString("distribution_id:");
196     response.PutStringAsRawHex8(distribution_id);
197     response.PutCString(";");
198   }
199 
200 #if defined(__APPLE__)
201   // For parity with debugserver, we'll include the vendor key.
202   response.PutCString("vendor:apple;");
203 
204   // Send out MachO info.
205   uint32_t cpu = host_arch.GetMachOCPUType();
206   uint32_t sub = host_arch.GetMachOCPUSubType();
207   if (cpu != LLDB_INVALID_CPUTYPE)
208     response.Printf("cputype:%u;", cpu);
209   if (sub != LLDB_INVALID_CPUTYPE)
210     response.Printf("cpusubtype:%u;", sub);
211 
212   if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) {
213 // Indicate the OS type.
214 #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
215     response.PutCString("ostype:tvos;");
216 #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
217     response.PutCString("ostype:watchos;");
218 #elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
219     response.PutCString("ostype:bridgeos;");
220 #else
221     response.PutCString("ostype:ios;");
222 #endif
223 
224     // On arm, we use "synchronous" watchpoints which means the exception is
225     // delivered before the instruction executes.
226     response.PutCString("watchpoint_exceptions_received:before;");
227   } else {
228     response.PutCString("ostype:macosx;");
229     response.Printf("watchpoint_exceptions_received:after;");
230   }
231 
232 #else
233   if (host_arch.GetMachine() == llvm::Triple::aarch64 ||
234       host_arch.GetMachine() == llvm::Triple::aarch64_be ||
235       host_arch.GetMachine() == llvm::Triple::arm ||
236       host_arch.GetMachine() == llvm::Triple::armeb ||
237       host_arch.GetMachine() == llvm::Triple::mips64 ||
238       host_arch.GetMachine() == llvm::Triple::mips64el ||
239       host_arch.GetMachine() == llvm::Triple::mips ||
240       host_arch.GetMachine() == llvm::Triple::mipsel)
241     response.Printf("watchpoint_exceptions_received:before;");
242   else
243     response.Printf("watchpoint_exceptions_received:after;");
244 #endif
245 
246   switch (endian::InlHostByteOrder()) {
247   case eByteOrderBig:
248     response.PutCString("endian:big;");
249     break;
250   case eByteOrderLittle:
251     response.PutCString("endian:little;");
252     break;
253   case eByteOrderPDP:
254     response.PutCString("endian:pdp;");
255     break;
256   default:
257     response.PutCString("endian:unknown;");
258     break;
259   }
260 
261   llvm::VersionTuple version = HostInfo::GetOSVersion();
262   if (!version.empty()) {
263     response.Format("os_version:{0}", version.getAsString());
264     response.PutChar(';');
265   }
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.GetSize()) {
414     StreamString response;
415     CreateProcessInfoResponse(
416         m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
417     ++m_proc_infos_index;
418     return SendPacketNoLock(response.GetString());
419   }
420   return SendErrorResponse(4);
421 }
422 
423 GDBRemoteCommunication::PacketResult
424 GDBRemoteCommunicationServerCommon::Handle_qUserName(
425     StringExtractorGDBRemote &packet) {
426 #if !defined(LLDB_DISABLE_POSIX)
427   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
428   if (log)
429     log->Printf("GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);
430 
431   // Packet format: "qUserName:%i" where %i is the uid
432   packet.SetFilePos(::strlen("qUserName:"));
433   uint32_t uid = packet.GetU32(UINT32_MAX);
434   if (uid != UINT32_MAX) {
435     if (llvm::Optional<llvm::StringRef> name =
436             HostInfo::GetUserIDResolver().GetUserName(uid)) {
437       StreamString response;
438       response.PutStringAsRawHex8(*name);
439       return SendPacketNoLock(response.GetString());
440     }
441   }
442   if (log)
443     log->Printf("GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);
444 #endif
445   return SendErrorResponse(5);
446 }
447 
448 GDBRemoteCommunication::PacketResult
449 GDBRemoteCommunicationServerCommon::Handle_qGroupName(
450     StringExtractorGDBRemote &packet) {
451 #if !defined(LLDB_DISABLE_POSIX)
452   // Packet format: "qGroupName:%i" where %i is the gid
453   packet.SetFilePos(::strlen("qGroupName:"));
454   uint32_t gid = packet.GetU32(UINT32_MAX);
455   if (gid != UINT32_MAX) {
456     if (llvm::Optional<llvm::StringRef> name =
457             HostInfo::GetUserIDResolver().GetGroupName(gid)) {
458       StreamString response;
459       response.PutStringAsRawHex8(*name);
460       return SendPacketNoLock(response.GetString());
461     }
462   }
463 #endif
464   return SendErrorResponse(6);
465 }
466 
467 GDBRemoteCommunication::PacketResult
468 GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(
469     StringExtractorGDBRemote &packet) {
470   packet.SetFilePos(::strlen("qSpeedTest:"));
471 
472   llvm::StringRef key;
473   llvm::StringRef value;
474   bool success = packet.GetNameColonValue(key, value);
475   if (success && key.equals("response_size")) {
476     uint32_t response_size = 0;
477     if (!value.getAsInteger(0, response_size)) {
478       if (response_size == 0)
479         return SendOKResponse();
480       StreamString response;
481       uint32_t bytes_left = response_size;
482       response.PutCString("data:");
483       while (bytes_left > 0) {
484         if (bytes_left >= 26) {
485           response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
486           bytes_left -= 26;
487         } else {
488           response.Printf("%*.*s;", bytes_left, bytes_left,
489                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
490           bytes_left = 0;
491         }
492       }
493       return SendPacketNoLock(response.GetString());
494     }
495   }
496   return SendErrorResponse(7);
497 }
498 
499 GDBRemoteCommunication::PacketResult
500 GDBRemoteCommunicationServerCommon::Handle_vFile_Open(
501     StringExtractorGDBRemote &packet) {
502   packet.SetFilePos(::strlen("vFile:open:"));
503   std::string path;
504   packet.GetHexByteStringTerminatedBy(path, ',');
505   if (!path.empty()) {
506     if (packet.GetChar() == ',') {
507       uint32_t flags = 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         File file;
513         // Do not close fd.
514         Status error =
515             FileSystem::Instance().Open(file, path_spec, flags, mode, false);
516         const int save_errno = error.GetError();
517         StreamString response;
518         response.PutChar('F');
519         response.Printf("%i", file.GetDescriptor());
520         if (save_errno)
521           response.Printf(",%i", save_errno);
522         return SendPacketNoLock(response.GetString());
523       }
524     }
525   }
526   return SendErrorResponse(18);
527 }
528 
529 GDBRemoteCommunication::PacketResult
530 GDBRemoteCommunicationServerCommon::Handle_vFile_Close(
531     StringExtractorGDBRemote &packet) {
532   packet.SetFilePos(::strlen("vFile:close:"));
533   int fd = packet.GetS32(-1);
534   int err = -1;
535   int save_errno = 0;
536   if (fd >= 0) {
537     File file(fd, true);
538     Status error = file.Close();
539     err = 0;
540     save_errno = error.GetError();
541   } else {
542     save_errno = EINVAL;
543   }
544   StreamString response;
545   response.PutChar('F');
546   response.Printf("%i", err);
547   if (save_errno)
548     response.Printf(",%i", save_errno);
549   return SendPacketNoLock(response.GetString());
550 }
551 
552 GDBRemoteCommunication::PacketResult
553 GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(
554     StringExtractorGDBRemote &packet) {
555   StreamGDBRemote response;
556   packet.SetFilePos(::strlen("vFile:pread:"));
557   int fd = packet.GetS32(-1);
558   if (packet.GetChar() == ',') {
559     size_t count = packet.GetU64(UINT64_MAX);
560     if (packet.GetChar() == ',') {
561       off_t offset = packet.GetU64(UINT32_MAX);
562       if (count == UINT64_MAX) {
563         response.Printf("F-1:%i", EINVAL);
564         return SendPacketNoLock(response.GetString());
565       }
566 
567       std::string buffer(count, 0);
568       File file(fd, false);
569       Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset);
570       const ssize_t bytes_read = error.Success() ? count : -1;
571       const int save_errno = error.GetError();
572       response.PutChar('F');
573       response.Printf("%zi", bytes_read);
574       if (save_errno)
575         response.Printf(",%i", save_errno);
576       else {
577         response.PutChar(';');
578         response.PutEscapedBytes(&buffer[0], bytes_read);
579       }
580       return SendPacketNoLock(response.GetString());
581     }
582   }
583   return SendErrorResponse(21);
584 }
585 
586 GDBRemoteCommunication::PacketResult
587 GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(
588     StringExtractorGDBRemote &packet) {
589   packet.SetFilePos(::strlen("vFile:pwrite:"));
590 
591   StreamGDBRemote response;
592   response.PutChar('F');
593 
594   int fd = packet.GetU32(UINT32_MAX);
595   if (packet.GetChar() == ',') {
596     off_t offset = packet.GetU64(UINT32_MAX);
597     if (packet.GetChar() == ',') {
598       std::string buffer;
599       if (packet.GetEscapedBinaryData(buffer)) {
600         File file(fd, false);
601         size_t count = buffer.size();
602         Status error =
603             file.Write(static_cast<const void *>(&buffer[0]), count, offset);
604         const ssize_t bytes_written = error.Success() ? count : -1;
605         const int save_errno = error.GetError();
606         response.Printf("%zi", bytes_written);
607         if (save_errno)
608           response.Printf(",%i", save_errno);
609       } else {
610         response.Printf("-1,%i", EINVAL);
611       }
612       return SendPacketNoLock(response.GetString());
613     }
614   }
615   return SendErrorResponse(27);
616 }
617 
618 GDBRemoteCommunication::PacketResult
619 GDBRemoteCommunicationServerCommon::Handle_vFile_Size(
620     StringExtractorGDBRemote &packet) {
621   packet.SetFilePos(::strlen("vFile:size:"));
622   std::string path;
623   packet.GetHexByteString(path);
624   if (!path.empty()) {
625     uint64_t Size;
626     if (llvm::sys::fs::file_size(path, Size))
627       return SendErrorResponse(5);
628     StreamString response;
629     response.PutChar('F');
630     response.PutHex64(Size);
631     if (Size == UINT64_MAX) {
632       response.PutChar(',');
633       response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode()
634     }
635     return SendPacketNoLock(response.GetString());
636   }
637   return SendErrorResponse(22);
638 }
639 
640 GDBRemoteCommunication::PacketResult
641 GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(
642     StringExtractorGDBRemote &packet) {
643   packet.SetFilePos(::strlen("vFile:mode:"));
644   std::string path;
645   packet.GetHexByteString(path);
646   if (!path.empty()) {
647     FileSpec file_spec(path);
648     FileSystem::Instance().Resolve(file_spec);
649     std::error_code ec;
650     const uint32_t mode = FileSystem::Instance().GetPermissions(file_spec, ec);
651     StreamString response;
652     response.Printf("F%u", mode);
653     if (mode == 0 || ec)
654       response.Printf(",%i", (int)Status(ec).GetError());
655     return SendPacketNoLock(response.GetString());
656   }
657   return SendErrorResponse(23);
658 }
659 
660 GDBRemoteCommunication::PacketResult
661 GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(
662     StringExtractorGDBRemote &packet) {
663   packet.SetFilePos(::strlen("vFile:exists:"));
664   std::string path;
665   packet.GetHexByteString(path);
666   if (!path.empty()) {
667     bool retcode = llvm::sys::fs::exists(path);
668     StreamString response;
669     response.PutChar('F');
670     response.PutChar(',');
671     if (retcode)
672       response.PutChar('1');
673     else
674       response.PutChar('0');
675     return SendPacketNoLock(response.GetString());
676   }
677   return SendErrorResponse(24);
678 }
679 
680 GDBRemoteCommunication::PacketResult
681 GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(
682     StringExtractorGDBRemote &packet) {
683   packet.SetFilePos(::strlen("vFile:symlink:"));
684   std::string dst, src;
685   packet.GetHexByteStringTerminatedBy(dst, ',');
686   packet.GetChar(); // Skip ',' char
687   packet.GetHexByteString(src);
688 
689   FileSpec src_spec(src);
690   FileSystem::Instance().Resolve(src_spec);
691   Status error = FileSystem::Instance().Symlink(src_spec, FileSpec(dst));
692 
693   StreamString response;
694   response.Printf("F%u,%u", error.GetError(), error.GetError());
695   return SendPacketNoLock(response.GetString());
696 }
697 
698 GDBRemoteCommunication::PacketResult
699 GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(
700     StringExtractorGDBRemote &packet) {
701   packet.SetFilePos(::strlen("vFile:unlink:"));
702   std::string path;
703   packet.GetHexByteString(path);
704   Status error(llvm::sys::fs::remove(path));
705   StreamString response;
706   response.Printf("F%u,%u", error.GetError(), error.GetError());
707   return SendPacketNoLock(response.GetString());
708 }
709 
710 GDBRemoteCommunication::PacketResult
711 GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(
712     StringExtractorGDBRemote &packet) {
713   packet.SetFilePos(::strlen("qPlatform_shell:"));
714   std::string path;
715   std::string working_dir;
716   packet.GetHexByteStringTerminatedBy(path, ',');
717   if (!path.empty()) {
718     if (packet.GetChar() == ',') {
719       // FIXME: add timeout to qPlatform_shell packet
720       // uint32_t timeout = packet.GetHexMaxU32(false, 32);
721       if (packet.GetChar() == ',')
722         packet.GetHexByteString(working_dir);
723       int status, signo;
724       std::string output;
725       FileSpec working_spec(working_dir);
726       FileSystem::Instance().Resolve(working_spec);
727       Status err =
728           Host::RunShellCommand(path.c_str(), working_spec, &status, &signo,
729                                 &output, std::chrono::seconds(10));
730       StreamGDBRemote response;
731       if (err.Fail()) {
732         response.PutCString("F,");
733         response.PutHex32(UINT32_MAX);
734       } else {
735         response.PutCString("F,");
736         response.PutHex32(status);
737         response.PutChar(',');
738         response.PutHex32(signo);
739         response.PutChar(',');
740         response.PutEscapedBytes(output.c_str(), output.size());
741       }
742       return SendPacketNoLock(response.GetString());
743     }
744   }
745   return SendErrorResponse(24);
746 }
747 
748 GDBRemoteCommunication::PacketResult
749 GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(
750     StringExtractorGDBRemote &packet) {
751   return SendUnimplementedResponse(
752       "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");
753 }
754 
755 GDBRemoteCommunication::PacketResult
756 GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(
757     StringExtractorGDBRemote &packet) {
758   packet.SetFilePos(::strlen("vFile:MD5:"));
759   std::string path;
760   packet.GetHexByteString(path);
761   if (!path.empty()) {
762     StreamGDBRemote response;
763     auto Result = llvm::sys::fs::md5_contents(path);
764     if (!Result) {
765       response.PutCString("F,");
766       response.PutCString("x");
767     } else {
768       response.PutCString("F,");
769       response.PutHex64(Result->low());
770       response.PutHex64(Result->high());
771     }
772     return SendPacketNoLock(response.GetString());
773   }
774   return SendErrorResponse(25);
775 }
776 
777 GDBRemoteCommunication::PacketResult
778 GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(
779     StringExtractorGDBRemote &packet) {
780   packet.SetFilePos(::strlen("qPlatform_mkdir:"));
781   mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
782   if (packet.GetChar() == ',') {
783     std::string path;
784     packet.GetHexByteString(path);
785     Status error(llvm::sys::fs::create_directory(path, mode));
786 
787     StreamGDBRemote response;
788     response.Printf("F%u", error.GetError());
789 
790     return SendPacketNoLock(response.GetString());
791   }
792   return SendErrorResponse(20);
793 }
794 
795 GDBRemoteCommunication::PacketResult
796 GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(
797     StringExtractorGDBRemote &packet) {
798   packet.SetFilePos(::strlen("qPlatform_chmod:"));
799 
800   auto perms =
801       static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX));
802   if (packet.GetChar() == ',') {
803     std::string path;
804     packet.GetHexByteString(path);
805     Status error(llvm::sys::fs::setPermissions(path, perms));
806 
807     StreamGDBRemote response;
808     response.Printf("F%u", error.GetError());
809 
810     return SendPacketNoLock(response.GetString());
811   }
812   return SendErrorResponse(19);
813 }
814 
815 GDBRemoteCommunication::PacketResult
816 GDBRemoteCommunicationServerCommon::Handle_qSupported(
817     StringExtractorGDBRemote &packet) {
818   StreamGDBRemote response;
819 
820   // Features common to lldb-platform and llgs.
821   uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet
822                                          // size--debugger can always use less
823   response.Printf("PacketSize=%x", max_packet_size);
824 
825   response.PutCString(";QStartNoAckMode+");
826   response.PutCString(";QThreadSuffixSupported+");
827   response.PutCString(";QListThreadsInStopReply+");
828   response.PutCString(";qEcho+");
829 #if defined(__linux__) || defined(__NetBSD__)
830   response.PutCString(";QPassSignals+");
831   response.PutCString(";qXfer:auxv:read+");
832 #endif
833 
834   return SendPacketNoLock(response.GetString());
835 }
836 
837 GDBRemoteCommunication::PacketResult
838 GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported(
839     StringExtractorGDBRemote &packet) {
840   m_thread_suffix_supported = true;
841   return SendOKResponse();
842 }
843 
844 GDBRemoteCommunication::PacketResult
845 GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply(
846     StringExtractorGDBRemote &packet) {
847   m_list_threads_in_stop_reply = true;
848   return SendOKResponse();
849 }
850 
851 GDBRemoteCommunication::PacketResult
852 GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(
853     StringExtractorGDBRemote &packet) {
854   packet.SetFilePos(::strlen("QSetDetachOnError:"));
855   if (packet.GetU32(0))
856     m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
857   else
858     m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);
859   return SendOKResponse();
860 }
861 
862 GDBRemoteCommunication::PacketResult
863 GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(
864     StringExtractorGDBRemote &packet) {
865   // Send response first before changing m_send_acks to we ack this packet
866   PacketResult packet_result = SendOKResponse();
867   m_send_acks = false;
868   return packet_result;
869 }
870 
871 GDBRemoteCommunication::PacketResult
872 GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(
873     StringExtractorGDBRemote &packet) {
874   packet.SetFilePos(::strlen("QSetSTDIN:"));
875   FileAction file_action;
876   std::string path;
877   packet.GetHexByteString(path);
878   const bool read = true;
879   const bool write = false;
880   if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) {
881     m_process_launch_info.AppendFileAction(file_action);
882     return SendOKResponse();
883   }
884   return SendErrorResponse(15);
885 }
886 
887 GDBRemoteCommunication::PacketResult
888 GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(
889     StringExtractorGDBRemote &packet) {
890   packet.SetFilePos(::strlen("QSetSTDOUT:"));
891   FileAction file_action;
892   std::string path;
893   packet.GetHexByteString(path);
894   const bool read = false;
895   const bool write = true;
896   if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) {
897     m_process_launch_info.AppendFileAction(file_action);
898     return SendOKResponse();
899   }
900   return SendErrorResponse(16);
901 }
902 
903 GDBRemoteCommunication::PacketResult
904 GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(
905     StringExtractorGDBRemote &packet) {
906   packet.SetFilePos(::strlen("QSetSTDERR:"));
907   FileAction file_action;
908   std::string path;
909   packet.GetHexByteString(path);
910   const bool read = false;
911   const bool write = true;
912   if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) {
913     m_process_launch_info.AppendFileAction(file_action);
914     return SendOKResponse();
915   }
916   return SendErrorResponse(17);
917 }
918 
919 GDBRemoteCommunication::PacketResult
920 GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(
921     StringExtractorGDBRemote &packet) {
922   if (m_process_launch_error.Success())
923     return SendOKResponse();
924   StreamString response;
925   response.PutChar('E');
926   response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
927   return SendPacketNoLock(response.GetString());
928 }
929 
930 GDBRemoteCommunication::PacketResult
931 GDBRemoteCommunicationServerCommon::Handle_QEnvironment(
932     StringExtractorGDBRemote &packet) {
933   packet.SetFilePos(::strlen("QEnvironment:"));
934   const uint32_t bytes_left = packet.GetBytesLeft();
935   if (bytes_left > 0) {
936     m_process_launch_info.GetEnvironment().insert(packet.Peek());
937     return SendOKResponse();
938   }
939   return SendErrorResponse(12);
940 }
941 
942 GDBRemoteCommunication::PacketResult
943 GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(
944     StringExtractorGDBRemote &packet) {
945   packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));
946   const uint32_t bytes_left = packet.GetBytesLeft();
947   if (bytes_left > 0) {
948     std::string str;
949     packet.GetHexByteString(str);
950     m_process_launch_info.GetEnvironment().insert(str);
951     return SendOKResponse();
952   }
953   return SendErrorResponse(12);
954 }
955 
956 GDBRemoteCommunication::PacketResult
957 GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(
958     StringExtractorGDBRemote &packet) {
959   packet.SetFilePos(::strlen("QLaunchArch:"));
960   const uint32_t bytes_left = packet.GetBytesLeft();
961   if (bytes_left > 0) {
962     const char *arch_triple = packet.Peek();
963     m_process_launch_info.SetArchitecture(
964         HostInfo::GetAugmentedArchSpec(arch_triple));
965     return SendOKResponse();
966   }
967   return SendErrorResponse(13);
968 }
969 
970 GDBRemoteCommunication::PacketResult
971 GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {
972   // The 'A' packet is the most over designed packet ever here with redundant
973   // argument indexes, redundant argument lengths and needed hex encoded
974   // argument string values. Really all that is needed is a comma separated hex
975   // encoded argument value list, but we will stay true to the documented
976   // version of the 'A' packet here...
977 
978   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
979   int actual_arg_index = 0;
980 
981   packet.SetFilePos(1); // Skip the 'A'
982   bool success = true;
983   while (success && packet.GetBytesLeft() > 0) {
984     // Decode the decimal argument string length. This length is the number of
985     // hex nibbles in the argument string value.
986     const uint32_t arg_len = packet.GetU32(UINT32_MAX);
987     if (arg_len == UINT32_MAX)
988       success = false;
989     else {
990       // Make sure the argument hex string length is followed by a comma
991       if (packet.GetChar() != ',')
992         success = false;
993       else {
994         // Decode the argument index. We ignore this really because who would
995         // really send down the arguments in a random order???
996         const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
997         if (arg_idx == UINT32_MAX)
998           success = false;
999         else {
1000           // Make sure the argument index is followed by a comma
1001           if (packet.GetChar() != ',')
1002             success = false;
1003           else {
1004             // Decode the argument string value from hex bytes back into a UTF8
1005             // string and make sure the length matches the one supplied in the
1006             // packet
1007             std::string arg;
1008             if (packet.GetHexByteStringFixedLength(arg, arg_len) !=
1009                 (arg_len / 2))
1010               success = false;
1011             else {
1012               // If there are any bytes left
1013               if (packet.GetBytesLeft()) {
1014                 if (packet.GetChar() != ',')
1015                   success = false;
1016               }
1017 
1018               if (success) {
1019                 if (arg_idx == 0)
1020                   m_process_launch_info.GetExecutableFile().SetFile(
1021                       arg, FileSpec::Style::native);
1022                 m_process_launch_info.GetArguments().AppendArgument(arg);
1023                 if (log)
1024                   log->Printf("LLGSPacketHandler::%s added arg %d: \"%s\"",
1025                               __FUNCTION__, actual_arg_index, arg.c_str());
1026                 ++actual_arg_index;
1027               }
1028             }
1029           }
1030         }
1031       }
1032     }
1033   }
1034 
1035   if (success) {
1036     m_process_launch_error = LaunchProcess();
1037     if (m_process_launch_error.Success())
1038       return SendOKResponse();
1039     LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
1040   }
1041   return SendErrorResponse(8);
1042 }
1043 
1044 GDBRemoteCommunication::PacketResult
1045 GDBRemoteCommunicationServerCommon::Handle_qEcho(
1046     StringExtractorGDBRemote &packet) {
1047   // Just echo back the exact same packet for qEcho...
1048   return SendPacketNoLock(packet.GetStringRef());
1049 }
1050 
1051 GDBRemoteCommunication::PacketResult
1052 GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(
1053     StringExtractorGDBRemote &packet) {
1054   packet.SetFilePos(::strlen("qModuleInfo:"));
1055 
1056   std::string module_path;
1057   packet.GetHexByteStringTerminatedBy(module_path, ';');
1058   if (module_path.empty())
1059     return SendErrorResponse(1);
1060 
1061   if (packet.GetChar() != ';')
1062     return SendErrorResponse(2);
1063 
1064   std::string triple;
1065   packet.GetHexByteString(triple);
1066 
1067   ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);
1068   if (!matched_module_spec.GetFileSpec())
1069     return SendErrorResponse(3);
1070 
1071   const auto file_offset = matched_module_spec.GetObjectOffset();
1072   const auto file_size = matched_module_spec.GetObjectSize();
1073   const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1074 
1075   StreamGDBRemote response;
1076 
1077   if (uuid_str.empty()) {
1078     auto Result = llvm::sys::fs::md5_contents(
1079         matched_module_spec.GetFileSpec().GetPath());
1080     if (!Result)
1081       return SendErrorResponse(5);
1082     response.PutCString("md5:");
1083     response.PutStringAsRawHex8(Result->digest());
1084   } else {
1085     response.PutCString("uuid:");
1086     response.PutStringAsRawHex8(uuid_str);
1087   }
1088   response.PutChar(';');
1089 
1090   const auto &module_arch = matched_module_spec.GetArchitecture();
1091   response.PutCString("triple:");
1092   response.PutStringAsRawHex8(module_arch.GetTriple().getTriple());
1093   response.PutChar(';');
1094 
1095   response.PutCString("file_path:");
1096   response.PutStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString());
1097   response.PutChar(';');
1098   response.PutCString("file_offset:");
1099   response.PutHex64(file_offset);
1100   response.PutChar(';');
1101   response.PutCString("file_size:");
1102   response.PutHex64(file_size);
1103   response.PutChar(';');
1104 
1105   return SendPacketNoLock(response.GetString());
1106 }
1107 
1108 GDBRemoteCommunication::PacketResult
1109 GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(
1110     StringExtractorGDBRemote &packet) {
1111   packet.SetFilePos(::strlen("jModulesInfo:"));
1112 
1113   StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());
1114   if (!object_sp)
1115     return SendErrorResponse(1);
1116 
1117   StructuredData::Array *packet_array = object_sp->GetAsArray();
1118   if (!packet_array)
1119     return SendErrorResponse(2);
1120 
1121   JSONArray::SP response_array_sp = std::make_shared<JSONArray>();
1122   for (size_t i = 0; i < packet_array->GetSize(); ++i) {
1123     StructuredData::Dictionary *query =
1124         packet_array->GetItemAtIndex(i)->GetAsDictionary();
1125     if (!query)
1126       continue;
1127     llvm::StringRef file, triple;
1128     if (!query->GetValueForKeyAsString("file", file) ||
1129         !query->GetValueForKeyAsString("triple", triple))
1130       continue;
1131 
1132     ModuleSpec matched_module_spec = GetModuleInfo(file, triple);
1133     if (!matched_module_spec.GetFileSpec())
1134       continue;
1135 
1136     const auto file_offset = matched_module_spec.GetObjectOffset();
1137     const auto file_size = matched_module_spec.GetObjectSize();
1138     const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");
1139 
1140     if (uuid_str.empty())
1141       continue;
1142 
1143     JSONObject::SP response = std::make_shared<JSONObject>();
1144     response_array_sp->AppendObject(response);
1145     response->SetObject("uuid", std::make_shared<JSONString>(uuid_str));
1146     response->SetObject(
1147         "triple",
1148         std::make_shared<JSONString>(
1149             matched_module_spec.GetArchitecture().GetTriple().getTriple()));
1150     response->SetObject("file_path",
1151                         std::make_shared<JSONString>(
1152                             matched_module_spec.GetFileSpec().GetPath()));
1153     response->SetObject("file_offset",
1154                         std::make_shared<JSONNumber>(file_offset));
1155     response->SetObject("file_size", std::make_shared<JSONNumber>(file_size));
1156   }
1157 
1158   StreamString response;
1159   response_array_sp->Write(response);
1160   StreamGDBRemote escaped_response;
1161   escaped_response.PutEscapedBytes(response.GetString().data(),
1162                                    response.GetSize());
1163   return SendPacketNoLock(escaped_response.GetString());
1164 }
1165 
1166 void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(
1167     const ProcessInstanceInfo &proc_info, StreamString &response) {
1168   response.Printf(
1169       "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
1170       proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1171       proc_info.GetUserID(), proc_info.GetGroupID(),
1172       proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());
1173   response.PutCString("name:");
1174   response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetCString());
1175   response.PutChar(';');
1176   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1177   if (proc_arch.IsValid()) {
1178     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1179     response.PutCString("triple:");
1180     response.PutStringAsRawHex8(proc_triple.getTriple());
1181     response.PutChar(';');
1182   }
1183 }
1184 
1185 void GDBRemoteCommunicationServerCommon::
1186     CreateProcessInfoResponse_DebugServerStyle(
1187         const ProcessInstanceInfo &proc_info, StreamString &response) {
1188   response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64
1189                   ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1190                   proc_info.GetProcessID(), proc_info.GetParentProcessID(),
1191                   proc_info.GetUserID(), proc_info.GetGroupID(),
1192                   proc_info.GetEffectiveUserID(),
1193                   proc_info.GetEffectiveGroupID());
1194 
1195   const ArchSpec &proc_arch = proc_info.GetArchitecture();
1196   if (proc_arch.IsValid()) {
1197     const llvm::Triple &proc_triple = proc_arch.GetTriple();
1198 #if defined(__APPLE__)
1199     // We'll send cputype/cpusubtype.
1200     const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1201     if (cpu_type != 0)
1202       response.Printf("cputype:%" PRIx32 ";", cpu_type);
1203 
1204     const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1205     if (cpu_subtype != 0)
1206       response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);
1207 
1208     const std::string vendor = proc_triple.getVendorName();
1209     if (!vendor.empty())
1210       response.Printf("vendor:%s;", vendor.c_str());
1211 #else
1212     // We'll send the triple.
1213     response.PutCString("triple:");
1214     response.PutStringAsRawHex8(proc_triple.getTriple());
1215     response.PutChar(';');
1216 #endif
1217     std::string ostype = proc_triple.getOSName();
1218     // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1219     if (proc_triple.getVendor() == llvm::Triple::Apple) {
1220       switch (proc_triple.getArch()) {
1221       case llvm::Triple::arm:
1222       case llvm::Triple::thumb:
1223       case llvm::Triple::aarch64:
1224         ostype = "ios";
1225         break;
1226       default:
1227         // No change.
1228         break;
1229       }
1230     }
1231     response.Printf("ostype:%s;", ostype.c_str());
1232 
1233     switch (proc_arch.GetByteOrder()) {
1234     case lldb::eByteOrderLittle:
1235       response.PutCString("endian:little;");
1236       break;
1237     case lldb::eByteOrderBig:
1238       response.PutCString("endian:big;");
1239       break;
1240     case lldb::eByteOrderPDP:
1241       response.PutCString("endian:pdp;");
1242       break;
1243     default:
1244       // Nothing.
1245       break;
1246     }
1247     // In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer
1248     // size is 4 and for N64 it is 8
1249     std::string abi = proc_arch.GetTargetABI();
1250     if (!abi.empty())
1251       response.Printf("elf_abi:%s;", abi.c_str());
1252     response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());
1253   }
1254 }
1255 
1256 FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(
1257     const std::string &module_path, const ArchSpec &arch) {
1258 #ifdef __ANDROID__
1259   return HostInfoAndroid::ResolveLibraryPath(module_path, arch);
1260 #else
1261   FileSpec file_spec(module_path);
1262   FileSystem::Instance().Resolve(file_spec);
1263   return file_spec;
1264 #endif
1265 }
1266 
1267 ModuleSpec
1268 GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path,
1269                                                   llvm::StringRef triple) {
1270   ArchSpec arch(triple);
1271 
1272   FileSpec req_module_path_spec(module_path);
1273   FileSystem::Instance().Resolve(req_module_path_spec);
1274 
1275   const FileSpec module_path_spec =
1276       FindModuleFile(req_module_path_spec.GetPath(), arch);
1277   const ModuleSpec module_spec(module_path_spec, arch);
1278 
1279   ModuleSpecList module_specs;
1280   if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0,
1281                                            module_specs))
1282     return ModuleSpec();
1283 
1284   ModuleSpec matched_module_spec;
1285   if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))
1286     return ModuleSpec();
1287 
1288   return matched_module_spec;
1289 }
1290