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