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