]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
Update to bmake-20201101
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lldb / source / Plugins / Process / gdb-remote / GDBRemoteCommunicationServerLLGS.cpp
1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include <errno.h>
10
11 #include "lldb/Host/Config.h"
12
13 #include "GDBRemoteCommunicationServerLLGS.h"
14 #include "lldb/Utility/GDBRemote.h"
15
16 #include <chrono>
17 #include <cstring>
18 #include <thread>
19
20 #include "lldb/Host/ConnectionFileDescriptor.h"
21 #include "lldb/Host/Debug.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/PosixApi.h"
28 #include "lldb/Host/common/NativeProcessProtocol.h"
29 #include "lldb/Host/common/NativeRegisterContext.h"
30 #include "lldb/Host/common/NativeThreadProtocol.h"
31 #include "lldb/Target/MemoryRegionInfo.h"
32 #include "lldb/Utility/Args.h"
33 #include "lldb/Utility/DataBuffer.h"
34 #include "lldb/Utility/Endian.h"
35 #include "lldb/Utility/LLDBAssert.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/RegisterValue.h"
38 #include "lldb/Utility/State.h"
39 #include "lldb/Utility/StreamString.h"
40 #include "lldb/Utility/UriParser.h"
41 #include "llvm/ADT/Triple.h"
42 #include "llvm/Support/JSON.h"
43 #include "llvm/Support/ScopedPrinter.h"
44
45 #include "ProcessGDBRemote.h"
46 #include "ProcessGDBRemoteLog.h"
47 #include "lldb/Utility/StringExtractorGDBRemote.h"
48
49 using namespace lldb;
50 using namespace lldb_private;
51 using namespace lldb_private::process_gdb_remote;
52 using namespace llvm;
53
54 // GDBRemote Errors
55
56 namespace {
57 enum GDBRemoteServerError {
58   // Set to the first unused error number in literal form below
59   eErrorFirst = 29,
60   eErrorNoProcess = eErrorFirst,
61   eErrorResume,
62   eErrorExitStatus
63 };
64 }
65
66 // GDBRemoteCommunicationServerLLGS constructor
67 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
68     MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
69     : GDBRemoteCommunicationServerCommon("gdb-remote.server",
70                                          "gdb-remote.server.rx_packet"),
71       m_mainloop(mainloop), m_process_factory(process_factory),
72       m_stdio_communication("process.stdio") {
73   RegisterPacketHandlers();
74 }
75
76 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
77   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
78                                 &GDBRemoteCommunicationServerLLGS::Handle_C);
79   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
80                                 &GDBRemoteCommunicationServerLLGS::Handle_c);
81   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
82                                 &GDBRemoteCommunicationServerLLGS::Handle_D);
83   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
84                                 &GDBRemoteCommunicationServerLLGS::Handle_H);
85   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
86                                 &GDBRemoteCommunicationServerLLGS::Handle_I);
87   RegisterMemberFunctionHandler(
88       StringExtractorGDBRemote::eServerPacketType_interrupt,
89       &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
90   RegisterMemberFunctionHandler(
91       StringExtractorGDBRemote::eServerPacketType_m,
92       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
93   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
94                                 &GDBRemoteCommunicationServerLLGS::Handle_M);
95   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
96                                 &GDBRemoteCommunicationServerLLGS::Handle_p);
97   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
98                                 &GDBRemoteCommunicationServerLLGS::Handle_P);
99   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
100                                 &GDBRemoteCommunicationServerLLGS::Handle_qC);
101   RegisterMemberFunctionHandler(
102       StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
103       &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
104   RegisterMemberFunctionHandler(
105       StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
106       &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
107   RegisterMemberFunctionHandler(
108       StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
109       &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
110   RegisterMemberFunctionHandler(
111       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
112       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
113   RegisterMemberFunctionHandler(
114       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
115       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
116   RegisterMemberFunctionHandler(
117       StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
118       &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
119   RegisterMemberFunctionHandler(
120       StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
121       &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
122   RegisterMemberFunctionHandler(
123       StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
124       &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
125   RegisterMemberFunctionHandler(
126       StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
127       &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
128   RegisterMemberFunctionHandler(
129       StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
130       &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
131   RegisterMemberFunctionHandler(
132       StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
133       &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
134   RegisterMemberFunctionHandler(
135       StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
136       &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
137   RegisterMemberFunctionHandler(
138       StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
139       &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
140   RegisterMemberFunctionHandler(
141       StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
142       &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
143   RegisterMemberFunctionHandler(
144       StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
145       &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
146   RegisterMemberFunctionHandler(
147       StringExtractorGDBRemote::eServerPacketType_qXfer,
148       &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
149   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
150                                 &GDBRemoteCommunicationServerLLGS::Handle_s);
151   RegisterMemberFunctionHandler(
152       StringExtractorGDBRemote::eServerPacketType_stop_reason,
153       &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
154   RegisterMemberFunctionHandler(
155       StringExtractorGDBRemote::eServerPacketType_vAttach,
156       &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
157   RegisterMemberFunctionHandler(
158       StringExtractorGDBRemote::eServerPacketType_vCont,
159       &GDBRemoteCommunicationServerLLGS::Handle_vCont);
160   RegisterMemberFunctionHandler(
161       StringExtractorGDBRemote::eServerPacketType_vCont_actions,
162       &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
163   RegisterMemberFunctionHandler(
164       StringExtractorGDBRemote::eServerPacketType_x,
165       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
166   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
167                                 &GDBRemoteCommunicationServerLLGS::Handle_Z);
168   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
169                                 &GDBRemoteCommunicationServerLLGS::Handle_z);
170   RegisterMemberFunctionHandler(
171       StringExtractorGDBRemote::eServerPacketType_QPassSignals,
172       &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
173
174   RegisterMemberFunctionHandler(
175       StringExtractorGDBRemote::eServerPacketType_jTraceStart,
176       &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
177   RegisterMemberFunctionHandler(
178       StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
179       &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
180   RegisterMemberFunctionHandler(
181       StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
182       &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
183   RegisterMemberFunctionHandler(
184       StringExtractorGDBRemote::eServerPacketType_jTraceStop,
185       &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
186   RegisterMemberFunctionHandler(
187       StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
188       &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
189
190   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
191                                 &GDBRemoteCommunicationServerLLGS::Handle_g);
192
193   RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
194                         [this](StringExtractorGDBRemote packet, Status &error,
195                                bool &interrupt, bool &quit) {
196                           quit = true;
197                           return this->Handle_k(packet);
198                         });
199 }
200
201 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
202   m_process_launch_info = info;
203 }
204
205 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
206   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
207
208   if (!m_process_launch_info.GetArguments().GetArgumentCount())
209     return Status("%s: no process command line specified to launch",
210                   __FUNCTION__);
211
212   const bool should_forward_stdio =
213       m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
214       m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
215       m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
216   m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
217   m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
218
219   if (should_forward_stdio) {
220     // Temporarily relax the following for Windows until we can take advantage
221     // of the recently added pty support. This doesn't really affect the use of
222     // lldb-server on Windows.
223 #if !defined(_WIN32)
224     if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
225       return Status(std::move(Err));
226 #endif
227   }
228
229   {
230     std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
231     assert(!m_debugged_process_up && "lldb-server creating debugged "
232                                      "process but one already exists");
233     auto process_or =
234         m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
235     if (!process_or)
236       return Status(process_or.takeError());
237     m_debugged_process_up = std::move(*process_or);
238   }
239
240   // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
241   // needed. llgs local-process debugging may specify PTY paths, which will
242   // make these file actions non-null process launch -i/e/o will also make
243   // these file actions non-null nullptr means that the traffic is expected to
244   // flow over gdb-remote protocol
245   if (should_forward_stdio) {
246     // nullptr means it's not redirected to file or pty (in case of LLGS local)
247     // at least one of stdio will be transferred pty<->gdb-remote we need to
248     // give the pty master handle to this object to read and/or write
249     LLDB_LOG(log,
250              "pid = {0}: setting up stdout/stderr redirection via $O "
251              "gdb-remote commands",
252              m_debugged_process_up->GetID());
253
254     // Setup stdout/stderr mapping from inferior to $O
255     auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
256     if (terminal_fd >= 0) {
257       LLDB_LOGF(log,
258                 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
259                 "inferior STDIO fd to %d",
260                 __FUNCTION__, terminal_fd);
261       Status status = SetSTDIOFileDescriptor(terminal_fd);
262       if (status.Fail())
263         return status;
264     } else {
265       LLDB_LOGF(log,
266                 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
267                 "inferior STDIO since terminal fd reported as %d",
268                 __FUNCTION__, terminal_fd);
269     }
270   } else {
271     LLDB_LOG(log,
272              "pid = {0} skipping stdout/stderr redirection via $O: inferior "
273              "will communicate over client-provided file descriptors",
274              m_debugged_process_up->GetID());
275   }
276
277   printf("Launched '%s' as process %" PRIu64 "...\n",
278          m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
279          m_debugged_process_up->GetID());
280
281   return Status();
282 }
283
284 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
285   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
286   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
287             __FUNCTION__, pid);
288
289   // Before we try to attach, make sure we aren't already monitoring something
290   // else.
291   if (m_debugged_process_up &&
292       m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
293     return Status("cannot attach to process %" PRIu64
294                   " when another process with pid %" PRIu64
295                   " is being debugged.",
296                   pid, m_debugged_process_up->GetID());
297
298   // Try to attach.
299   auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
300   if (!process_or) {
301     Status status(process_or.takeError());
302     llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
303                                   status);
304     return status;
305   }
306   m_debugged_process_up = std::move(*process_or);
307
308   // Setup stdout/stderr mapping from inferior.
309   auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
310   if (terminal_fd >= 0) {
311     LLDB_LOGF(log,
312               "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
313               "inferior STDIO fd to %d",
314               __FUNCTION__, terminal_fd);
315     Status status = SetSTDIOFileDescriptor(terminal_fd);
316     if (status.Fail())
317       return status;
318   } else {
319     LLDB_LOGF(log,
320               "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
321               "inferior STDIO since terminal fd reported as %d",
322               __FUNCTION__, terminal_fd);
323   }
324
325   printf("Attached to process %" PRIu64 "...\n", pid);
326   return Status();
327 }
328
329 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
330     NativeProcessProtocol *process) {
331   assert(process && "process cannot be NULL");
332   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
333   if (log) {
334     LLDB_LOGF(log,
335               "GDBRemoteCommunicationServerLLGS::%s called with "
336               "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
337               __FUNCTION__, process->GetID(),
338               StateAsCString(process->GetState()));
339   }
340 }
341
342 GDBRemoteCommunication::PacketResult
343 GDBRemoteCommunicationServerLLGS::SendWResponse(
344     NativeProcessProtocol *process) {
345   assert(process && "process cannot be NULL");
346   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
347
348   // send W notification
349   auto wait_status = process->GetExitStatus();
350   if (!wait_status) {
351     LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
352              process->GetID());
353
354     StreamGDBRemote response;
355     response.PutChar('E');
356     response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
357     return SendPacketNoLock(response.GetString());
358   }
359
360   LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
361            *wait_status);
362
363   StreamGDBRemote response;
364   response.Format("{0:g}", *wait_status);
365   return SendPacketNoLock(response.GetString());
366 }
367
368 static void AppendHexValue(StreamString &response, const uint8_t *buf,
369                            uint32_t buf_size, bool swap) {
370   int64_t i;
371   if (swap) {
372     for (i = buf_size - 1; i >= 0; i--)
373       response.PutHex8(buf[i]);
374   } else {
375     for (i = 0; i < buf_size; i++)
376       response.PutHex8(buf[i]);
377   }
378 }
379
380 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo &reg_info) {
381   switch (reg_info.encoding) {
382   case eEncodingUint:
383     return "uint";
384   case eEncodingSint:
385     return "sint";
386   case eEncodingIEEE754:
387     return "ieee754";
388   case eEncodingVector:
389     return "vector";
390   default:
391     return "";
392   }
393 }
394
395 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo &reg_info) {
396   switch (reg_info.format) {
397   case eFormatBinary:
398     return "binary";
399   case eFormatDecimal:
400     return "decimal";
401   case eFormatHex:
402     return "hex";
403   case eFormatFloat:
404     return "float";
405   case eFormatVectorOfSInt8:
406     return "vector-sint8";
407   case eFormatVectorOfUInt8:
408     return "vector-uint8";
409   case eFormatVectorOfSInt16:
410     return "vector-sint16";
411   case eFormatVectorOfUInt16:
412     return "vector-uint16";
413   case eFormatVectorOfSInt32:
414     return "vector-sint32";
415   case eFormatVectorOfUInt32:
416     return "vector-uint32";
417   case eFormatVectorOfFloat32:
418     return "vector-float32";
419   case eFormatVectorOfUInt64:
420     return "vector-uint64";
421   case eFormatVectorOfUInt128:
422     return "vector-uint128";
423   default:
424     return "";
425   };
426 }
427
428 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo &reg_info) {
429   switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
430   case LLDB_REGNUM_GENERIC_PC:
431     return "pc";
432   case LLDB_REGNUM_GENERIC_SP:
433     return "sp";
434   case LLDB_REGNUM_GENERIC_FP:
435     return "fp";
436   case LLDB_REGNUM_GENERIC_RA:
437     return "ra";
438   case LLDB_REGNUM_GENERIC_FLAGS:
439     return "flags";
440   case LLDB_REGNUM_GENERIC_ARG1:
441     return "arg1";
442   case LLDB_REGNUM_GENERIC_ARG2:
443     return "arg2";
444   case LLDB_REGNUM_GENERIC_ARG3:
445     return "arg3";
446   case LLDB_REGNUM_GENERIC_ARG4:
447     return "arg4";
448   case LLDB_REGNUM_GENERIC_ARG5:
449     return "arg5";
450   case LLDB_REGNUM_GENERIC_ARG6:
451     return "arg6";
452   case LLDB_REGNUM_GENERIC_ARG7:
453     return "arg7";
454   case LLDB_REGNUM_GENERIC_ARG8:
455     return "arg8";
456   default:
457     return "";
458   }
459 }
460
461 static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
462                            bool usehex) {
463   for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
464     if (i > 0)
465       response.PutChar(',');
466     if (usehex)
467       response.Printf("%" PRIx32, *reg_num);
468     else
469       response.Printf("%" PRIu32, *reg_num);
470   }
471 }
472
473 static void WriteRegisterValueInHexFixedWidth(
474     StreamString &response, NativeRegisterContext &reg_ctx,
475     const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
476     lldb::ByteOrder byte_order) {
477   RegisterValue reg_value;
478   if (!reg_value_p) {
479     Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
480     if (error.Success())
481       reg_value_p = &reg_value;
482     // else log.
483   }
484
485   if (reg_value_p) {
486     AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
487                    reg_value_p->GetByteSize(),
488                    byte_order == lldb::eByteOrderLittle);
489   } else {
490     // Zero-out any unreadable values.
491     if (reg_info.byte_size > 0) {
492       std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
493       AppendHexValue(response, zeros.data(), zeros.size(), false);
494     }
495   }
496 }
497
498 static llvm::Expected<json::Object>
499 GetRegistersAsJSON(NativeThreadProtocol &thread) {
500   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
501
502   NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
503
504   json::Object register_object;
505
506 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
507   // Expedite all registers in the first register set (i.e. should be GPRs)
508   // that are not contained in other registers.
509   const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
510   if (!reg_set_p)
511     return llvm::make_error<llvm::StringError>("failed to get registers",
512                                                llvm::inconvertibleErrorCode());
513   for (const uint32_t *reg_num_p = reg_set_p->registers;
514        *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
515     uint32_t reg_num = *reg_num_p;
516 #else
517   // Expedite only a couple of registers until we figure out why sending
518   // registers is expensive.
519   static const uint32_t k_expedited_registers[] = {
520       LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
521       LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
522
523   for (const uint32_t *generic_reg_p = k_expedited_registers;
524        *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
525     uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
526         eRegisterKindGeneric, *generic_reg_p);
527     if (reg_num == LLDB_INVALID_REGNUM)
528       continue; // Target does not support the given register.
529 #endif
530
531     const RegisterInfo *const reg_info_p =
532         reg_ctx.GetRegisterInfoAtIndex(reg_num);
533     if (reg_info_p == nullptr) {
534       LLDB_LOGF(log,
535                 "%s failed to get register info for register index %" PRIu32,
536                 __FUNCTION__, reg_num);
537       continue;
538     }
539
540     if (reg_info_p->value_regs != nullptr)
541       continue; // Only expedite registers that are not contained in other
542                 // registers.
543
544     RegisterValue reg_value;
545     Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
546     if (error.Fail()) {
547       LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
548                 __FUNCTION__,
549                 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
550                 reg_num, error.AsCString());
551       continue;
552     }
553
554     StreamString stream;
555     WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
556                                       &reg_value, lldb::eByteOrderBig);
557
558     register_object.try_emplace(llvm::to_string(reg_num),
559                                 stream.GetString().str());
560   }
561
562   return register_object;
563 }
564
565 static const char *GetStopReasonString(StopReason stop_reason) {
566   switch (stop_reason) {
567   case eStopReasonTrace:
568     return "trace";
569   case eStopReasonBreakpoint:
570     return "breakpoint";
571   case eStopReasonWatchpoint:
572     return "watchpoint";
573   case eStopReasonSignal:
574     return "signal";
575   case eStopReasonException:
576     return "exception";
577   case eStopReasonExec:
578     return "exec";
579   case eStopReasonInstrumentation:
580   case eStopReasonInvalid:
581   case eStopReasonPlanComplete:
582   case eStopReasonThreadExiting:
583   case eStopReasonNone:
584     break; // ignored
585   }
586   return nullptr;
587 }
588
589 static llvm::Expected<json::Array>
590 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
591   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
592
593   json::Array threads_array;
594
595   // Ensure we can get info on the given thread.
596   uint32_t thread_idx = 0;
597   for (NativeThreadProtocol *thread;
598        (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
599        ++thread_idx) {
600
601     lldb::tid_t tid = thread->GetID();
602
603     // Grab the reason this thread stopped.
604     struct ThreadStopInfo tid_stop_info;
605     std::string description;
606     if (!thread->GetStopReason(tid_stop_info, description))
607       return llvm::make_error<llvm::StringError>(
608           "failed to get stop reason", llvm::inconvertibleErrorCode());
609
610     const int signum = tid_stop_info.details.signal.signo;
611     if (log) {
612       LLDB_LOGF(log,
613                 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
614                 " tid %" PRIu64
615                 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
616                 __FUNCTION__, process.GetID(), tid, signum,
617                 tid_stop_info.reason, tid_stop_info.details.exception.type);
618     }
619
620     json::Object thread_obj;
621
622     if (!abridged) {
623       if (llvm::Expected<json::Object> registers =
624               GetRegistersAsJSON(*thread)) {
625         thread_obj.try_emplace("registers", std::move(*registers));
626       } else {
627         return registers.takeError();
628       }
629     }
630
631     thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
632
633     if (signum != 0)
634       thread_obj.try_emplace("signal", signum);
635
636     const std::string thread_name = thread->GetName();
637     if (!thread_name.empty())
638       thread_obj.try_emplace("name", thread_name);
639
640     const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
641     if (stop_reason)
642       thread_obj.try_emplace("reason", stop_reason);
643
644     if (!description.empty())
645       thread_obj.try_emplace("description", description);
646
647     if ((tid_stop_info.reason == eStopReasonException) &&
648         tid_stop_info.details.exception.type) {
649       thread_obj.try_emplace(
650           "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
651
652       json::Array medata_array;
653       for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
654            ++i) {
655         medata_array.push_back(
656             static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
657       }
658       thread_obj.try_emplace("medata", std::move(medata_array));
659     }
660     threads_array.push_back(std::move(thread_obj));
661   }
662   return threads_array;
663 }
664
665 GDBRemoteCommunication::PacketResult
666 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
667     lldb::tid_t tid) {
668   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
669
670   // Ensure we have a debugged process.
671   if (!m_debugged_process_up ||
672       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
673     return SendErrorResponse(50);
674
675   LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
676            m_debugged_process_up->GetID(), tid);
677
678   // Ensure we can get info on the given thread.
679   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
680   if (!thread)
681     return SendErrorResponse(51);
682
683   // Grab the reason this thread stopped.
684   struct ThreadStopInfo tid_stop_info;
685   std::string description;
686   if (!thread->GetStopReason(tid_stop_info, description))
687     return SendErrorResponse(52);
688
689   // FIXME implement register handling for exec'd inferiors.
690   // if (tid_stop_info.reason == eStopReasonExec) {
691   //     const bool force = true;
692   //     InitializeRegisters(force);
693   // }
694
695   StreamString response;
696   // Output the T packet with the thread
697   response.PutChar('T');
698   int signum = tid_stop_info.details.signal.signo;
699   LLDB_LOG(
700       log,
701       "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
702       m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
703       tid_stop_info.details.exception.type);
704
705   // Print the signal number.
706   response.PutHex8(signum & 0xff);
707
708   // Include the tid.
709   response.Printf("thread:%" PRIx64 ";", tid);
710
711   // Include the thread name if there is one.
712   const std::string thread_name = thread->GetName();
713   if (!thread_name.empty()) {
714     size_t thread_name_len = thread_name.length();
715
716     if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
717       response.PutCString("name:");
718       response.PutCString(thread_name);
719     } else {
720       // The thread name contains special chars, send as hex bytes.
721       response.PutCString("hexname:");
722       response.PutStringAsRawHex8(thread_name);
723     }
724     response.PutChar(';');
725   }
726
727   // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
728   // send all thread IDs back in the "threads" key whose value is a list of hex
729   // thread IDs separated by commas:
730   //  "threads:10a,10b,10c;"
731   // This will save the debugger from having to send a pair of qfThreadInfo and
732   // qsThreadInfo packets, but it also might take a lot of room in the stop
733   // reply packet, so it must be enabled only on systems where there are no
734   // limits on packet lengths.
735   if (m_list_threads_in_stop_reply) {
736     response.PutCString("threads:");
737
738     uint32_t thread_index = 0;
739     NativeThreadProtocol *listed_thread;
740     for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
741          listed_thread; ++thread_index,
742         listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
743       if (thread_index > 0)
744         response.PutChar(',');
745       response.Printf("%" PRIx64, listed_thread->GetID());
746     }
747     response.PutChar(';');
748
749     // Include JSON info that describes the stop reason for any threads that
750     // actually have stop reasons. We use the new "jstopinfo" key whose values
751     // is hex ascii JSON that contains the thread IDs thread stop info only for
752     // threads that have stop reasons. Only send this if we have more than one
753     // thread otherwise this packet has all the info it needs.
754     if (thread_index > 1) {
755       const bool threads_with_valid_stop_info_only = true;
756       llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
757           *m_debugged_process_up, threads_with_valid_stop_info_only);
758       if (threads_info) {
759         response.PutCString("jstopinfo:");
760         StreamString unescaped_response;
761         unescaped_response.AsRawOstream() << std::move(*threads_info);
762         response.PutStringAsRawHex8(unescaped_response.GetData());
763         response.PutChar(';');
764       } else {
765         LLDB_LOG_ERROR(log, threads_info.takeError(),
766                        "failed to prepare a jstopinfo field for pid {1}: {0}",
767                        m_debugged_process_up->GetID());
768       }
769     }
770
771     uint32_t i = 0;
772     response.PutCString("thread-pcs");
773     char delimiter = ':';
774     for (NativeThreadProtocol *thread;
775          (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
776          ++i) {
777       NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
778
779       uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
780           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
781       const RegisterInfo *const reg_info_p =
782           reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
783
784       RegisterValue reg_value;
785       Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
786       if (error.Fail()) {
787         LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
788                   __FUNCTION__,
789                   reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
790                   reg_to_read, error.AsCString());
791         continue;
792       }
793
794       response.PutChar(delimiter);
795       delimiter = ',';
796       WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
797                                         &reg_value, endian::InlHostByteOrder());
798     }
799
800     response.PutChar(';');
801   }
802
803   //
804   // Expedite registers.
805   //
806
807   // Grab the register context.
808   NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
809   // Expedite all registers in the first register set (i.e. should be GPRs)
810   // that are not contained in other registers.
811   const RegisterSet *reg_set_p;
812   if (reg_ctx.GetRegisterSetCount() > 0 &&
813       ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
814     LLDB_LOGF(log,
815               "GDBRemoteCommunicationServerLLGS::%s expediting registers "
816               "from set '%s' (registers set count: %zu)",
817               __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
818               reg_set_p->num_registers);
819
820     for (const uint32_t *reg_num_p = reg_set_p->registers;
821          *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
822       const RegisterInfo *const reg_info_p =
823           reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
824       if (reg_info_p == nullptr) {
825         LLDB_LOGF(log,
826                   "GDBRemoteCommunicationServerLLGS::%s failed to get "
827                   "register info for register set '%s', register index "
828                   "%" PRIu32,
829                   __FUNCTION__,
830                   reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
831                   *reg_num_p);
832       } else if (reg_info_p->value_regs == nullptr) {
833         // Only expediate registers that are not contained in other registers.
834         RegisterValue reg_value;
835         Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
836         if (error.Success()) {
837           response.Printf("%.02x:", *reg_num_p);
838           WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
839                                             &reg_value, lldb::eByteOrderBig);
840           response.PutChar(';');
841         } else {
842           LLDB_LOGF(log,
843                     "GDBRemoteCommunicationServerLLGS::%s failed to read "
844                     "register '%s' index %" PRIu32 ": %s",
845                     __FUNCTION__,
846                     reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
847                     *reg_num_p, error.AsCString());
848         }
849       }
850     }
851   }
852
853   const char *reason_str = GetStopReasonString(tid_stop_info.reason);
854   if (reason_str != nullptr) {
855     response.Printf("reason:%s;", reason_str);
856   }
857
858   if (!description.empty()) {
859     // Description may contains special chars, send as hex bytes.
860     response.PutCString("description:");
861     response.PutStringAsRawHex8(description);
862     response.PutChar(';');
863   } else if ((tid_stop_info.reason == eStopReasonException) &&
864              tid_stop_info.details.exception.type) {
865     response.PutCString("metype:");
866     response.PutHex64(tid_stop_info.details.exception.type);
867     response.PutCString(";mecount:");
868     response.PutHex32(tid_stop_info.details.exception.data_count);
869     response.PutChar(';');
870
871     for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
872       response.PutCString("medata:");
873       response.PutHex64(tid_stop_info.details.exception.data[i]);
874       response.PutChar(';');
875     }
876   }
877
878   return SendPacketNoLock(response.GetString());
879 }
880
881 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
882     NativeProcessProtocol *process) {
883   assert(process && "process cannot be NULL");
884
885   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
886   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
887
888   PacketResult result = SendStopReasonForState(StateType::eStateExited);
889   if (result != PacketResult::Success) {
890     LLDB_LOGF(log,
891               "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
892               "notification for PID %" PRIu64 ", state: eStateExited",
893               __FUNCTION__, process->GetID());
894   }
895
896   // Close the pipe to the inferior terminal i/o if we launched it and set one
897   // up.
898   MaybeCloseInferiorTerminalConnection();
899
900   // We are ready to exit the debug monitor.
901   m_exit_now = true;
902   m_mainloop.RequestTermination();
903 }
904
905 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
906     NativeProcessProtocol *process) {
907   assert(process && "process cannot be NULL");
908
909   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
910   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
911
912   // Send the stop reason unless this is the stop after the launch or attach.
913   switch (m_inferior_prev_state) {
914   case eStateLaunching:
915   case eStateAttaching:
916     // Don't send anything per debugserver behavior.
917     break;
918   default:
919     // In all other cases, send the stop reason.
920     PacketResult result = SendStopReasonForState(StateType::eStateStopped);
921     if (result != PacketResult::Success) {
922       LLDB_LOGF(log,
923                 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
924                 "notification for PID %" PRIu64 ", state: eStateExited",
925                 __FUNCTION__, process->GetID());
926     }
927     break;
928   }
929 }
930
931 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
932     NativeProcessProtocol *process, lldb::StateType state) {
933   assert(process && "process cannot be NULL");
934   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
935   if (log) {
936     LLDB_LOGF(log,
937               "GDBRemoteCommunicationServerLLGS::%s called with "
938               "NativeProcessProtocol pid %" PRIu64 ", state: %s",
939               __FUNCTION__, process->GetID(), StateAsCString(state));
940   }
941
942   switch (state) {
943   case StateType::eStateRunning:
944     StartSTDIOForwarding();
945     break;
946
947   case StateType::eStateStopped:
948     // Make sure we get all of the pending stdout/stderr from the inferior and
949     // send it to the lldb host before we send the state change notification
950     SendProcessOutput();
951     // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
952     // does not interfere with our protocol.
953     StopSTDIOForwarding();
954     HandleInferiorState_Stopped(process);
955     break;
956
957   case StateType::eStateExited:
958     // Same as above
959     SendProcessOutput();
960     StopSTDIOForwarding();
961     HandleInferiorState_Exited(process);
962     break;
963
964   default:
965     if (log) {
966       LLDB_LOGF(log,
967                 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
968                 "change for pid %" PRIu64 ", new state: %s",
969                 __FUNCTION__, process->GetID(), StateAsCString(state));
970     }
971     break;
972   }
973
974   // Remember the previous state reported to us.
975   m_inferior_prev_state = state;
976 }
977
978 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
979   ClearProcessSpecificData();
980 }
981
982 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
983   Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
984
985   if (!m_handshake_completed) {
986     if (!HandshakeWithClient()) {
987       LLDB_LOGF(log,
988                 "GDBRemoteCommunicationServerLLGS::%s handshake with "
989                 "client failed, exiting",
990                 __FUNCTION__);
991       m_mainloop.RequestTermination();
992       return;
993     }
994     m_handshake_completed = true;
995   }
996
997   bool interrupt = false;
998   bool done = false;
999   Status error;
1000   while (true) {
1001     const PacketResult result = GetPacketAndSendResponse(
1002         std::chrono::microseconds(0), error, interrupt, done);
1003     if (result == PacketResult::ErrorReplyTimeout)
1004       break; // No more packets in the queue
1005
1006     if ((result != PacketResult::Success)) {
1007       LLDB_LOGF(log,
1008                 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1009                 "failed: %s",
1010                 __FUNCTION__, error.AsCString());
1011       m_mainloop.RequestTermination();
1012       break;
1013     }
1014   }
1015 }
1016
1017 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1018     std::unique_ptr<Connection> connection) {
1019   IOObjectSP read_object_sp = connection->GetReadObject();
1020   GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1021
1022   Status error;
1023   m_network_handle_up = m_mainloop.RegisterReadObject(
1024       read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1025       error);
1026   return error;
1027 }
1028
1029 GDBRemoteCommunication::PacketResult
1030 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1031                                                     uint32_t len) {
1032   if ((buffer == nullptr) || (len == 0)) {
1033     // Nothing to send.
1034     return PacketResult::Success;
1035   }
1036
1037   StreamString response;
1038   response.PutChar('O');
1039   response.PutBytesAsRawHex8(buffer, len);
1040
1041   return SendPacketNoLock(response.GetString());
1042 }
1043
1044 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1045   Status error;
1046
1047   // Set up the reading/handling of process I/O
1048   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1049       new ConnectionFileDescriptor(fd, true));
1050   if (!conn_up) {
1051     error.SetErrorString("failed to create ConnectionFileDescriptor");
1052     return error;
1053   }
1054
1055   m_stdio_communication.SetCloseOnEOF(false);
1056   m_stdio_communication.SetConnection(std::move(conn_up));
1057   if (!m_stdio_communication.IsConnected()) {
1058     error.SetErrorString(
1059         "failed to set connection for inferior I/O communication");
1060     return error;
1061   }
1062
1063   return Status();
1064 }
1065
1066 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1067   // Don't forward if not connected (e.g. when attaching).
1068   if (!m_stdio_communication.IsConnected())
1069     return;
1070
1071   Status error;
1072   lldbassert(!m_stdio_handle_up);
1073   m_stdio_handle_up = m_mainloop.RegisterReadObject(
1074       m_stdio_communication.GetConnection()->GetReadObject(),
1075       [this](MainLoopBase &) { SendProcessOutput(); }, error);
1076
1077   if (!m_stdio_handle_up) {
1078     // Not much we can do about the failure. Log it and continue without
1079     // forwarding.
1080     if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1081       LLDB_LOGF(log,
1082                 "GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1083                 "forwarding: %s",
1084                 __FUNCTION__, error.AsCString());
1085   }
1086 }
1087
1088 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1089   m_stdio_handle_up.reset();
1090 }
1091
1092 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1093   char buffer[1024];
1094   ConnectionStatus status;
1095   Status error;
1096   while (true) {
1097     size_t bytes_read = m_stdio_communication.Read(
1098         buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1099     switch (status) {
1100     case eConnectionStatusSuccess:
1101       SendONotification(buffer, bytes_read);
1102       break;
1103     case eConnectionStatusLostConnection:
1104     case eConnectionStatusEndOfFile:
1105     case eConnectionStatusError:
1106     case eConnectionStatusNoConnection:
1107       if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1108         LLDB_LOGF(log,
1109                   "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1110                   "forwarding as communication returned status %d (error: "
1111                   "%s)",
1112                   __FUNCTION__, status, error.AsCString());
1113       m_stdio_handle_up.reset();
1114       return;
1115
1116     case eConnectionStatusInterrupted:
1117     case eConnectionStatusTimedOut:
1118       return;
1119     }
1120   }
1121 }
1122
1123 GDBRemoteCommunication::PacketResult
1124 GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1125     StringExtractorGDBRemote &packet) {
1126   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1127   // Fail if we don't have a current process.
1128   if (!m_debugged_process_up ||
1129       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1130     return SendErrorResponse(68);
1131
1132   if (!packet.ConsumeFront("jTraceStart:"))
1133     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1134
1135   TraceOptions options;
1136   uint64_t type = std::numeric_limits<uint64_t>::max();
1137   uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1138   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1139   uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1140
1141   auto json_object = StructuredData::ParseJSON(packet.Peek());
1142
1143   if (!json_object ||
1144       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1145     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1146
1147   auto json_dict = json_object->GetAsDictionary();
1148
1149   json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1150   options.setMetaDataBufferSize(metabuffersize);
1151
1152   json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1153   options.setTraceBufferSize(buffersize);
1154
1155   json_dict->GetValueForKeyAsInteger("type", type);
1156   options.setType(static_cast<lldb::TraceType>(type));
1157
1158   json_dict->GetValueForKeyAsInteger("threadid", tid);
1159   options.setThreadID(tid);
1160
1161   StructuredData::ObjectSP custom_params_sp =
1162       json_dict->GetValueForKey("params");
1163   if (custom_params_sp &&
1164       custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1165     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1166
1167   options.setTraceParams(
1168       std::static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1169
1170   if (buffersize == std::numeric_limits<uint64_t>::max() ||
1171       type != lldb::TraceType::eTraceTypeProcessorTrace) {
1172     LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1173              type);
1174     return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1175   }
1176
1177   Status error;
1178   lldb::user_id_t uid = LLDB_INVALID_UID;
1179   uid = m_debugged_process_up->StartTrace(options, error);
1180   LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1181   if (error.Fail())
1182     return SendErrorResponse(error);
1183
1184   StreamGDBRemote response;
1185   response.Printf("%" PRIx64, uid);
1186   return SendPacketNoLock(response.GetString());
1187 }
1188
1189 GDBRemoteCommunication::PacketResult
1190 GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1191     StringExtractorGDBRemote &packet) {
1192   // Fail if we don't have a current process.
1193   if (!m_debugged_process_up ||
1194       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1195     return SendErrorResponse(68);
1196
1197   if (!packet.ConsumeFront("jTraceStop:"))
1198     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1199
1200   lldb::user_id_t uid = LLDB_INVALID_UID;
1201   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1202
1203   auto json_object = StructuredData::ParseJSON(packet.Peek());
1204
1205   if (!json_object ||
1206       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1207     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1208
1209   auto json_dict = json_object->GetAsDictionary();
1210
1211   if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1212     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1213
1214   json_dict->GetValueForKeyAsInteger("threadid", tid);
1215
1216   Status error = m_debugged_process_up->StopTrace(uid, tid);
1217
1218   if (error.Fail())
1219     return SendErrorResponse(error);
1220
1221   return SendOKResponse();
1222 }
1223
1224 GDBRemoteCommunication::PacketResult
1225 GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1226     StringExtractorGDBRemote &packet) {
1227
1228   // Fail if we don't have a current process.
1229   if (!m_debugged_process_up ||
1230       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1231     return SendErrorResponse(68);
1232
1233   if (!packet.ConsumeFront("jTraceConfigRead:"))
1234     return SendIllFormedResponse(packet,
1235                                  "jTraceConfigRead: Ill formed packet ");
1236
1237   lldb::user_id_t uid = LLDB_INVALID_UID;
1238   lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1239
1240   auto json_object = StructuredData::ParseJSON(packet.Peek());
1241
1242   if (!json_object ||
1243       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1244     return SendIllFormedResponse(packet,
1245                                  "jTraceConfigRead: Ill formed packet ");
1246
1247   auto json_dict = json_object->GetAsDictionary();
1248
1249   if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1250     return SendIllFormedResponse(packet,
1251                                  "jTraceConfigRead: Ill formed packet ");
1252
1253   json_dict->GetValueForKeyAsInteger("threadid", threadid);
1254
1255   TraceOptions options;
1256   StreamGDBRemote response;
1257
1258   options.setThreadID(threadid);
1259   Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1260
1261   if (error.Fail())
1262     return SendErrorResponse(error);
1263
1264   StreamGDBRemote escaped_response;
1265   StructuredData::Dictionary json_packet;
1266
1267   json_packet.AddIntegerItem("type", options.getType());
1268   json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1269   json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1270
1271   StructuredData::DictionarySP custom_params = options.getTraceParams();
1272   if (custom_params)
1273     json_packet.AddItem("params", custom_params);
1274
1275   StreamString json_string;
1276   json_packet.Dump(json_string, false);
1277   escaped_response.PutEscapedBytes(json_string.GetData(),
1278                                    json_string.GetSize());
1279   return SendPacketNoLock(escaped_response.GetString());
1280 }
1281
1282 GDBRemoteCommunication::PacketResult
1283 GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1284     StringExtractorGDBRemote &packet) {
1285
1286   // Fail if we don't have a current process.
1287   if (!m_debugged_process_up ||
1288       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1289     return SendErrorResponse(68);
1290
1291   enum PacketType { MetaData, BufferData };
1292   PacketType tracetype = MetaData;
1293
1294   if (packet.ConsumeFront("jTraceBufferRead:"))
1295     tracetype = BufferData;
1296   else if (packet.ConsumeFront("jTraceMetaRead:"))
1297     tracetype = MetaData;
1298   else {
1299     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1300   }
1301
1302   lldb::user_id_t uid = LLDB_INVALID_UID;
1303
1304   uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1305   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1306   uint64_t offset = std::numeric_limits<uint64_t>::max();
1307
1308   auto json_object = StructuredData::ParseJSON(packet.Peek());
1309
1310   if (!json_object ||
1311       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1312     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1313
1314   auto json_dict = json_object->GetAsDictionary();
1315
1316   if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1317       !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1318       !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1319     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1320
1321   json_dict->GetValueForKeyAsInteger("threadid", tid);
1322
1323   // Allocate the response buffer.
1324   std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1325   if (!buffer)
1326     return SendErrorResponse(0x78);
1327
1328   StreamGDBRemote response;
1329   Status error;
1330   llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1331
1332   if (tracetype == BufferData)
1333     error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1334   else if (tracetype == MetaData)
1335     error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1336
1337   if (error.Fail())
1338     return SendErrorResponse(error);
1339
1340   for (auto i : buf)
1341     response.PutHex8(i);
1342
1343   StreamGDBRemote escaped_response;
1344   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1345   return SendPacketNoLock(escaped_response.GetString());
1346 }
1347
1348 GDBRemoteCommunication::PacketResult
1349 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1350     StringExtractorGDBRemote &packet) {
1351   // Fail if we don't have a current process.
1352   if (!m_debugged_process_up ||
1353       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1354     return SendErrorResponse(68);
1355
1356   lldb::pid_t pid = m_debugged_process_up->GetID();
1357
1358   if (pid == LLDB_INVALID_PROCESS_ID)
1359     return SendErrorResponse(1);
1360
1361   ProcessInstanceInfo proc_info;
1362   if (!Host::GetProcessInfo(pid, proc_info))
1363     return SendErrorResponse(1);
1364
1365   StreamString response;
1366   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1367   return SendPacketNoLock(response.GetString());
1368 }
1369
1370 GDBRemoteCommunication::PacketResult
1371 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1372   // Fail if we don't have a current process.
1373   if (!m_debugged_process_up ||
1374       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1375     return SendErrorResponse(68);
1376
1377   // Make sure we set the current thread so g and p packets return the data the
1378   // gdb will expect.
1379   lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1380   SetCurrentThreadID(tid);
1381
1382   NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1383   if (!thread)
1384     return SendErrorResponse(69);
1385
1386   StreamString response;
1387   response.Printf("QC%" PRIx64, thread->GetID());
1388
1389   return SendPacketNoLock(response.GetString());
1390 }
1391
1392 GDBRemoteCommunication::PacketResult
1393 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1394   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1395
1396   StopSTDIOForwarding();
1397
1398   if (!m_debugged_process_up) {
1399     LLDB_LOG(log, "No debugged process found.");
1400     return PacketResult::Success;
1401   }
1402
1403   Status error = m_debugged_process_up->Kill();
1404   if (error.Fail())
1405     LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1406              m_debugged_process_up->GetID(), error);
1407
1408   // No OK response for kill packet.
1409   // return SendOKResponse ();
1410   return PacketResult::Success;
1411 }
1412
1413 GDBRemoteCommunication::PacketResult
1414 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1415     StringExtractorGDBRemote &packet) {
1416   packet.SetFilePos(::strlen("QSetDisableASLR:"));
1417   if (packet.GetU32(0))
1418     m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1419   else
1420     m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1421   return SendOKResponse();
1422 }
1423
1424 GDBRemoteCommunication::PacketResult
1425 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1426     StringExtractorGDBRemote &packet) {
1427   packet.SetFilePos(::strlen("QSetWorkingDir:"));
1428   std::string path;
1429   packet.GetHexByteString(path);
1430   m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1431   return SendOKResponse();
1432 }
1433
1434 GDBRemoteCommunication::PacketResult
1435 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1436     StringExtractorGDBRemote &packet) {
1437   FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1438   if (working_dir) {
1439     StreamString response;
1440     response.PutStringAsRawHex8(working_dir.GetCString());
1441     return SendPacketNoLock(response.GetString());
1442   }
1443
1444   return SendErrorResponse(14);
1445 }
1446
1447 GDBRemoteCommunication::PacketResult
1448 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1449   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1450   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1451
1452   // Ensure we have a native process.
1453   if (!m_debugged_process_up) {
1454     LLDB_LOGF(log,
1455               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1456               "shared pointer",
1457               __FUNCTION__);
1458     return SendErrorResponse(0x36);
1459   }
1460
1461   // Pull out the signal number.
1462   packet.SetFilePos(::strlen("C"));
1463   if (packet.GetBytesLeft() < 1) {
1464     // Shouldn't be using a C without a signal.
1465     return SendIllFormedResponse(packet, "C packet specified without signal.");
1466   }
1467   const uint32_t signo =
1468       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1469   if (signo == std::numeric_limits<uint32_t>::max())
1470     return SendIllFormedResponse(packet, "failed to parse signal number");
1471
1472   // Handle optional continue address.
1473   if (packet.GetBytesLeft() > 0) {
1474     // FIXME add continue at address support for $C{signo}[;{continue-address}].
1475     if (*packet.Peek() == ';')
1476       return SendUnimplementedResponse(packet.GetStringRef().data());
1477     else
1478       return SendIllFormedResponse(
1479           packet, "unexpected content after $C{signal-number}");
1480   }
1481
1482   ResumeActionList resume_actions(StateType::eStateRunning,
1483                                   LLDB_INVALID_SIGNAL_NUMBER);
1484   Status error;
1485
1486   // We have two branches: what to do if a continue thread is specified (in
1487   // which case we target sending the signal to that thread), or when we don't
1488   // have a continue thread set (in which case we send a signal to the
1489   // process).
1490
1491   // TODO discuss with Greg Clayton, make sure this makes sense.
1492
1493   lldb::tid_t signal_tid = GetContinueThreadID();
1494   if (signal_tid != LLDB_INVALID_THREAD_ID) {
1495     // The resume action for the continue thread (or all threads if a continue
1496     // thread is not set).
1497     ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1498                            static_cast<int>(signo)};
1499
1500     // Add the action for the continue thread (or all threads when the continue
1501     // thread isn't present).
1502     resume_actions.Append(action);
1503   } else {
1504     // Send the signal to the process since we weren't targeting a specific
1505     // continue thread with the signal.
1506     error = m_debugged_process_up->Signal(signo);
1507     if (error.Fail()) {
1508       LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1509                m_debugged_process_up->GetID(), error);
1510
1511       return SendErrorResponse(0x52);
1512     }
1513   }
1514
1515   // Resume the threads.
1516   error = m_debugged_process_up->Resume(resume_actions);
1517   if (error.Fail()) {
1518     LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1519              m_debugged_process_up->GetID(), error);
1520
1521     return SendErrorResponse(0x38);
1522   }
1523
1524   // Don't send an "OK" packet; response is the stopped/exited message.
1525   return PacketResult::Success;
1526 }
1527
1528 GDBRemoteCommunication::PacketResult
1529 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1530   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1531   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1532
1533   packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1534
1535   // For now just support all continue.
1536   const bool has_continue_address = (packet.GetBytesLeft() > 0);
1537   if (has_continue_address) {
1538     LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1539              packet.Peek());
1540     return SendUnimplementedResponse(packet.GetStringRef().data());
1541   }
1542
1543   // Ensure we have a native process.
1544   if (!m_debugged_process_up) {
1545     LLDB_LOGF(log,
1546               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1547               "shared pointer",
1548               __FUNCTION__);
1549     return SendErrorResponse(0x36);
1550   }
1551
1552   // Build the ResumeActionList
1553   ResumeActionList actions(StateType::eStateRunning,
1554                            LLDB_INVALID_SIGNAL_NUMBER);
1555
1556   Status error = m_debugged_process_up->Resume(actions);
1557   if (error.Fail()) {
1558     LLDB_LOG(log, "c failed for process {0}: {1}",
1559              m_debugged_process_up->GetID(), error);
1560     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1561   }
1562
1563   LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1564   // No response required from continue.
1565   return PacketResult::Success;
1566 }
1567
1568 GDBRemoteCommunication::PacketResult
1569 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1570     StringExtractorGDBRemote &packet) {
1571   StreamString response;
1572   response.Printf("vCont;c;C;s;S");
1573
1574   return SendPacketNoLock(response.GetString());
1575 }
1576
1577 GDBRemoteCommunication::PacketResult
1578 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1579     StringExtractorGDBRemote &packet) {
1580   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1581   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1582             __FUNCTION__);
1583
1584   packet.SetFilePos(::strlen("vCont"));
1585
1586   if (packet.GetBytesLeft() == 0) {
1587     LLDB_LOGF(log,
1588               "GDBRemoteCommunicationServerLLGS::%s missing action from "
1589               "vCont package",
1590               __FUNCTION__);
1591     return SendIllFormedResponse(packet, "Missing action from vCont package");
1592   }
1593
1594   // Check if this is all continue (no options or ";c").
1595   if (::strcmp(packet.Peek(), ";c") == 0) {
1596     // Move past the ';', then do a simple 'c'.
1597     packet.SetFilePos(packet.GetFilePos() + 1);
1598     return Handle_c(packet);
1599   } else if (::strcmp(packet.Peek(), ";s") == 0) {
1600     // Move past the ';', then do a simple 's'.
1601     packet.SetFilePos(packet.GetFilePos() + 1);
1602     return Handle_s(packet);
1603   }
1604
1605   // Ensure we have a native process.
1606   if (!m_debugged_process_up) {
1607     LLDB_LOG(log, "no debugged process");
1608     return SendErrorResponse(0x36);
1609   }
1610
1611   ResumeActionList thread_actions;
1612
1613   while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1614     // Skip the semi-colon.
1615     packet.GetChar();
1616
1617     // Build up the thread action.
1618     ResumeAction thread_action;
1619     thread_action.tid = LLDB_INVALID_THREAD_ID;
1620     thread_action.state = eStateInvalid;
1621     thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1622
1623     const char action = packet.GetChar();
1624     switch (action) {
1625     case 'C':
1626       thread_action.signal = packet.GetHexMaxU32(false, 0);
1627       if (thread_action.signal == 0)
1628         return SendIllFormedResponse(
1629             packet, "Could not parse signal in vCont packet C action");
1630       LLVM_FALLTHROUGH;
1631
1632     case 'c':
1633       // Continue
1634       thread_action.state = eStateRunning;
1635       break;
1636
1637     case 'S':
1638       thread_action.signal = packet.GetHexMaxU32(false, 0);
1639       if (thread_action.signal == 0)
1640         return SendIllFormedResponse(
1641             packet, "Could not parse signal in vCont packet S action");
1642       LLVM_FALLTHROUGH;
1643
1644     case 's':
1645       // Step
1646       thread_action.state = eStateStepping;
1647       break;
1648
1649     default:
1650       return SendIllFormedResponse(packet, "Unsupported vCont action");
1651       break;
1652     }
1653
1654     // Parse out optional :{thread-id} value.
1655     if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1656       // Consume the separator.
1657       packet.GetChar();
1658
1659       thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1660       if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1661         return SendIllFormedResponse(
1662             packet, "Could not parse thread number in vCont packet");
1663     }
1664
1665     thread_actions.Append(thread_action);
1666   }
1667
1668   Status error = m_debugged_process_up->Resume(thread_actions);
1669   if (error.Fail()) {
1670     LLDB_LOG(log, "vCont failed for process {0}: {1}",
1671              m_debugged_process_up->GetID(), error);
1672     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1673   }
1674
1675   LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1676   // No response required from vCont.
1677   return PacketResult::Success;
1678 }
1679
1680 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1681   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1682   LLDB_LOG(log, "setting current thread id to {0}", tid);
1683
1684   m_current_tid = tid;
1685   if (m_debugged_process_up)
1686     m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1687 }
1688
1689 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1690   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1691   LLDB_LOG(log, "setting continue thread id to {0}", tid);
1692
1693   m_continue_tid = tid;
1694 }
1695
1696 GDBRemoteCommunication::PacketResult
1697 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1698     StringExtractorGDBRemote &packet) {
1699   // Handle the $? gdbremote command.
1700
1701   // If no process, indicate error
1702   if (!m_debugged_process_up)
1703     return SendErrorResponse(02);
1704
1705   return SendStopReasonForState(m_debugged_process_up->GetState());
1706 }
1707
1708 GDBRemoteCommunication::PacketResult
1709 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1710     lldb::StateType process_state) {
1711   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1712
1713   switch (process_state) {
1714   case eStateAttaching:
1715   case eStateLaunching:
1716   case eStateRunning:
1717   case eStateStepping:
1718   case eStateDetached:
1719     // NOTE: gdb protocol doc looks like it should return $OK
1720     // when everything is running (i.e. no stopped result).
1721     return PacketResult::Success; // Ignore
1722
1723   case eStateSuspended:
1724   case eStateStopped:
1725   case eStateCrashed: {
1726     lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1727     // Make sure we set the current thread so g and p packets return the data
1728     // the gdb will expect.
1729     SetCurrentThreadID(tid);
1730     return SendStopReplyPacketForThread(tid);
1731   }
1732
1733   case eStateInvalid:
1734   case eStateUnloaded:
1735   case eStateExited:
1736     return SendWResponse(m_debugged_process_up.get());
1737
1738   default:
1739     LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1740              m_debugged_process_up->GetID(), process_state);
1741     break;
1742   }
1743
1744   return SendErrorResponse(0);
1745 }
1746
1747 GDBRemoteCommunication::PacketResult
1748 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1749     StringExtractorGDBRemote &packet) {
1750   // Fail if we don't have a current process.
1751   if (!m_debugged_process_up ||
1752       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1753     return SendErrorResponse(68);
1754
1755   // Ensure we have a thread.
1756   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1757   if (!thread)
1758     return SendErrorResponse(69);
1759
1760   // Get the register context for the first thread.
1761   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1762
1763   // Parse out the register number from the request.
1764   packet.SetFilePos(strlen("qRegisterInfo"));
1765   const uint32_t reg_index =
1766       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1767   if (reg_index == std::numeric_limits<uint32_t>::max())
1768     return SendErrorResponse(69);
1769
1770   // Return the end of registers response if we've iterated one past the end of
1771   // the register set.
1772   if (reg_index >= reg_context.GetUserRegisterCount())
1773     return SendErrorResponse(69);
1774
1775   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1776   if (!reg_info)
1777     return SendErrorResponse(69);
1778
1779   // Build the reginfos response.
1780   StreamGDBRemote response;
1781
1782   response.PutCString("name:");
1783   response.PutCString(reg_info->name);
1784   response.PutChar(';');
1785
1786   if (reg_info->alt_name && reg_info->alt_name[0]) {
1787     response.PutCString("alt-name:");
1788     response.PutCString(reg_info->alt_name);
1789     response.PutChar(';');
1790   }
1791
1792   response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1793                   reg_info->byte_size * 8, reg_info->byte_offset);
1794
1795   llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
1796   if (!encoding.empty())
1797     response << "encoding:" << encoding << ';';
1798
1799   llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
1800   if (!format.empty())
1801     response << "format:" << format << ';';
1802
1803   const char *const register_set_name =
1804       reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1805   if (register_set_name)
1806     response << "set:" << register_set_name << ';';
1807
1808   if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1809       LLDB_INVALID_REGNUM)
1810     response.Printf("ehframe:%" PRIu32 ";",
1811                     reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1812
1813   if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1814     response.Printf("dwarf:%" PRIu32 ";",
1815                     reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1816
1817   llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
1818   if (!kind_generic.empty())
1819     response << "generic:" << kind_generic << ';';
1820
1821   if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1822     response.PutCString("container-regs:");
1823     CollectRegNums(reg_info->value_regs, response, true);
1824     response.PutChar(';');
1825   }
1826
1827   if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1828     response.PutCString("invalidate-regs:");
1829     CollectRegNums(reg_info->invalidate_regs, response, true);
1830     response.PutChar(';');
1831   }
1832
1833   if (reg_info->dynamic_size_dwarf_expr_bytes) {
1834     const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1835     response.PutCString("dynamic_size_dwarf_expr_bytes:");
1836     for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1837       response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1838     response.PutChar(';');
1839   }
1840   return SendPacketNoLock(response.GetString());
1841 }
1842
1843 GDBRemoteCommunication::PacketResult
1844 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1845     StringExtractorGDBRemote &packet) {
1846   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1847
1848   // Fail if we don't have a current process.
1849   if (!m_debugged_process_up ||
1850       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1851     LLDB_LOG(log, "no process ({0}), returning OK",
1852              m_debugged_process_up ? "invalid process id"
1853                                    : "null m_debugged_process_up");
1854     return SendOKResponse();
1855   }
1856
1857   StreamGDBRemote response;
1858   response.PutChar('m');
1859
1860   LLDB_LOG(log, "starting thread iteration");
1861   NativeThreadProtocol *thread;
1862   uint32_t thread_index;
1863   for (thread_index = 0,
1864       thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1865        thread; ++thread_index,
1866       thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1867     LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1868              thread->GetID());
1869     if (thread_index > 0)
1870       response.PutChar(',');
1871     response.Printf("%" PRIx64, thread->GetID());
1872   }
1873
1874   LLDB_LOG(log, "finished thread iteration");
1875   return SendPacketNoLock(response.GetString());
1876 }
1877
1878 GDBRemoteCommunication::PacketResult
1879 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1880     StringExtractorGDBRemote &packet) {
1881   // FIXME for now we return the full thread list in the initial packet and
1882   // always do nothing here.
1883   return SendPacketNoLock("l");
1884 }
1885
1886 GDBRemoteCommunication::PacketResult
1887 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
1888   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1889
1890   // Move past packet name.
1891   packet.SetFilePos(strlen("g"));
1892
1893   // Get the thread to use.
1894   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1895   if (!thread) {
1896     LLDB_LOG(log, "failed, no thread available");
1897     return SendErrorResponse(0x15);
1898   }
1899
1900   // Get the thread's register context.
1901   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
1902
1903   std::vector<uint8_t> regs_buffer;
1904   for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
1905        ++reg_num) {
1906     const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
1907
1908     if (reg_info == nullptr) {
1909       LLDB_LOG(log, "failed to get register info for register index {0}",
1910                reg_num);
1911       return SendErrorResponse(0x15);
1912     }
1913
1914     if (reg_info->value_regs != nullptr)
1915       continue; // skip registers that are contained in other registers
1916
1917     RegisterValue reg_value;
1918     Status error = reg_ctx.ReadRegister(reg_info, reg_value);
1919     if (error.Fail()) {
1920       LLDB_LOG(log, "failed to read register at index {0}", reg_num);
1921       return SendErrorResponse(0x15);
1922     }
1923
1924     if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
1925       // Resize the buffer to guarantee it can store the register offsetted
1926       // data.
1927       regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
1928
1929     // Copy the register offsetted data to the buffer.
1930     memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
1931            reg_info->byte_size);
1932   }
1933
1934   // Write the response.
1935   StreamGDBRemote response;
1936   response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
1937
1938   return SendPacketNoLock(response.GetString());
1939 }
1940
1941 GDBRemoteCommunication::PacketResult
1942 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1943   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1944
1945   // Parse out the register number from the request.
1946   packet.SetFilePos(strlen("p"));
1947   const uint32_t reg_index =
1948       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1949   if (reg_index == std::numeric_limits<uint32_t>::max()) {
1950     LLDB_LOGF(log,
1951               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
1952               "parse register number from request \"%s\"",
1953               __FUNCTION__, packet.GetStringRef().data());
1954     return SendErrorResponse(0x15);
1955   }
1956
1957   // Get the thread to use.
1958   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1959   if (!thread) {
1960     LLDB_LOG(log, "failed, no thread available");
1961     return SendErrorResponse(0x15);
1962   }
1963
1964   // Get the thread's register context.
1965   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1966
1967   // Return the end of registers response if we've iterated one past the end of
1968   // the register set.
1969   if (reg_index >= reg_context.GetUserRegisterCount()) {
1970     LLDB_LOGF(log,
1971               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1972               "register %" PRIu32 " beyond register count %" PRIu32,
1973               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
1974     return SendErrorResponse(0x15);
1975   }
1976
1977   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1978   if (!reg_info) {
1979     LLDB_LOGF(log,
1980               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1981               "register %" PRIu32 " returned NULL",
1982               __FUNCTION__, reg_index);
1983     return SendErrorResponse(0x15);
1984   }
1985
1986   // Build the reginfos response.
1987   StreamGDBRemote response;
1988
1989   // Retrieve the value
1990   RegisterValue reg_value;
1991   Status error = reg_context.ReadRegister(reg_info, reg_value);
1992   if (error.Fail()) {
1993     LLDB_LOGF(log,
1994               "GDBRemoteCommunicationServerLLGS::%s failed, read of "
1995               "requested register %" PRIu32 " (%s) failed: %s",
1996               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1997     return SendErrorResponse(0x15);
1998   }
1999
2000   const uint8_t *const data =
2001       static_cast<const uint8_t *>(reg_value.GetBytes());
2002   if (!data) {
2003     LLDB_LOGF(log,
2004               "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2005               "bytes from requested register %" PRIu32,
2006               __FUNCTION__, reg_index);
2007     return SendErrorResponse(0x15);
2008   }
2009
2010   // FIXME flip as needed to get data in big/little endian format for this host.
2011   for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2012     response.PutHex8(data[i]);
2013
2014   return SendPacketNoLock(response.GetString());
2015 }
2016
2017 GDBRemoteCommunication::PacketResult
2018 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2019   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2020
2021   // Ensure there is more content.
2022   if (packet.GetBytesLeft() < 1)
2023     return SendIllFormedResponse(packet, "Empty P packet");
2024
2025   // Parse out the register number from the request.
2026   packet.SetFilePos(strlen("P"));
2027   const uint32_t reg_index =
2028       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2029   if (reg_index == std::numeric_limits<uint32_t>::max()) {
2030     LLDB_LOGF(log,
2031               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2032               "parse register number from request \"%s\"",
2033               __FUNCTION__, packet.GetStringRef().data());
2034     return SendErrorResponse(0x29);
2035   }
2036
2037   // Note debugserver would send an E30 here.
2038   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2039     return SendIllFormedResponse(
2040         packet, "P packet missing '=' char after register number");
2041
2042   // Parse out the value.
2043   uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2044   size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2045
2046   // Get the thread to use.
2047   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2048   if (!thread) {
2049     LLDB_LOGF(log,
2050               "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2051               "available (thread index 0)",
2052               __FUNCTION__);
2053     return SendErrorResponse(0x28);
2054   }
2055
2056   // Get the thread's register context.
2057   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2058   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2059   if (!reg_info) {
2060     LLDB_LOGF(log,
2061               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2062               "register %" PRIu32 " returned NULL",
2063               __FUNCTION__, reg_index);
2064     return SendErrorResponse(0x48);
2065   }
2066
2067   // Return the end of registers response if we've iterated one past the end of
2068   // the register set.
2069   if (reg_index >= reg_context.GetUserRegisterCount()) {
2070     LLDB_LOGF(log,
2071               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2072               "register %" PRIu32 " beyond register count %" PRIu32,
2073               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2074     return SendErrorResponse(0x47);
2075   }
2076
2077   // The dwarf expression are evaluate on host site which may cause register
2078   // size to change Hence the reg_size may not be same as reg_info->bytes_size
2079   if ((reg_size != reg_info->byte_size) &&
2080       !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2081     return SendIllFormedResponse(packet, "P packet register size is incorrect");
2082   }
2083
2084   // Build the reginfos response.
2085   StreamGDBRemote response;
2086
2087   RegisterValue reg_value(
2088       reg_bytes, reg_size,
2089       m_debugged_process_up->GetArchitecture().GetByteOrder());
2090   Status error = reg_context.WriteRegister(reg_info, reg_value);
2091   if (error.Fail()) {
2092     LLDB_LOGF(log,
2093               "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2094               "requested register %" PRIu32 " (%s) failed: %s",
2095               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2096     return SendErrorResponse(0x32);
2097   }
2098
2099   return SendOKResponse();
2100 }
2101
2102 GDBRemoteCommunication::PacketResult
2103 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2104   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2105
2106   // Fail if we don't have a current process.
2107   if (!m_debugged_process_up ||
2108       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2109     LLDB_LOGF(
2110         log,
2111         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2112         __FUNCTION__);
2113     return SendErrorResponse(0x15);
2114   }
2115
2116   // Parse out which variant of $H is requested.
2117   packet.SetFilePos(strlen("H"));
2118   if (packet.GetBytesLeft() < 1) {
2119     LLDB_LOGF(log,
2120               "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2121               "missing {g,c} variant",
2122               __FUNCTION__);
2123     return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2124   }
2125
2126   const char h_variant = packet.GetChar();
2127   switch (h_variant) {
2128   case 'g':
2129     break;
2130
2131   case 'c':
2132     break;
2133
2134   default:
2135     LLDB_LOGF(
2136         log,
2137         "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2138         __FUNCTION__, h_variant);
2139     return SendIllFormedResponse(packet,
2140                                  "H variant unsupported, should be c or g");
2141   }
2142
2143   // Parse out the thread number.
2144   // FIXME return a parse success/fail value.  All values are valid here.
2145   const lldb::tid_t tid =
2146       packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2147
2148   // Ensure we have the given thread when not specifying -1 (all threads) or 0
2149   // (any thread).
2150   if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2151     NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2152     if (!thread) {
2153       LLDB_LOGF(log,
2154                 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2155                 " not found",
2156                 __FUNCTION__, tid);
2157       return SendErrorResponse(0x15);
2158     }
2159   }
2160
2161   // Now switch the given thread type.
2162   switch (h_variant) {
2163   case 'g':
2164     SetCurrentThreadID(tid);
2165     break;
2166
2167   case 'c':
2168     SetContinueThreadID(tid);
2169     break;
2170
2171   default:
2172     assert(false && "unsupported $H variant - shouldn't get here");
2173     return SendIllFormedResponse(packet,
2174                                  "H variant unsupported, should be c or g");
2175   }
2176
2177   return SendOKResponse();
2178 }
2179
2180 GDBRemoteCommunication::PacketResult
2181 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2182   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2183
2184   // Fail if we don't have a current process.
2185   if (!m_debugged_process_up ||
2186       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2187     LLDB_LOGF(
2188         log,
2189         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2190         __FUNCTION__);
2191     return SendErrorResponse(0x15);
2192   }
2193
2194   packet.SetFilePos(::strlen("I"));
2195   uint8_t tmp[4096];
2196   for (;;) {
2197     size_t read = packet.GetHexBytesAvail(tmp);
2198     if (read == 0) {
2199       break;
2200     }
2201     // write directly to stdin *this might block if stdin buffer is full*
2202     // TODO: enqueue this block in circular buffer and send window size to
2203     // remote host
2204     ConnectionStatus status;
2205     Status error;
2206     m_stdio_communication.Write(tmp, read, status, &error);
2207     if (error.Fail()) {
2208       return SendErrorResponse(0x15);
2209     }
2210   }
2211
2212   return SendOKResponse();
2213 }
2214
2215 GDBRemoteCommunication::PacketResult
2216 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2217     StringExtractorGDBRemote &packet) {
2218   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2219
2220   // Fail if we don't have a current process.
2221   if (!m_debugged_process_up ||
2222       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2223     LLDB_LOG(log, "failed, no process available");
2224     return SendErrorResponse(0x15);
2225   }
2226
2227   // Interrupt the process.
2228   Status error = m_debugged_process_up->Interrupt();
2229   if (error.Fail()) {
2230     LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2231              error);
2232     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2233   }
2234
2235   LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2236
2237   // No response required from stop all.
2238   return PacketResult::Success;
2239 }
2240
2241 GDBRemoteCommunication::PacketResult
2242 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2243     StringExtractorGDBRemote &packet) {
2244   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2245
2246   if (!m_debugged_process_up ||
2247       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2248     LLDB_LOGF(
2249         log,
2250         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2251         __FUNCTION__);
2252     return SendErrorResponse(0x15);
2253   }
2254
2255   // Parse out the memory address.
2256   packet.SetFilePos(strlen("m"));
2257   if (packet.GetBytesLeft() < 1)
2258     return SendIllFormedResponse(packet, "Too short m packet");
2259
2260   // Read the address.  Punting on validation.
2261   // FIXME replace with Hex U64 read with no default value that fails on failed
2262   // read.
2263   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2264
2265   // Validate comma.
2266   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2267     return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2268
2269   // Get # bytes to read.
2270   if (packet.GetBytesLeft() < 1)
2271     return SendIllFormedResponse(packet, "Length missing in m packet");
2272
2273   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2274   if (byte_count == 0) {
2275     LLDB_LOGF(log,
2276               "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2277               "zero-length packet",
2278               __FUNCTION__);
2279     return SendOKResponse();
2280   }
2281
2282   // Allocate the response buffer.
2283   std::string buf(byte_count, '\0');
2284   if (buf.empty())
2285     return SendErrorResponse(0x78);
2286
2287   // Retrieve the process memory.
2288   size_t bytes_read = 0;
2289   Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2290       read_addr, &buf[0], byte_count, bytes_read);
2291   if (error.Fail()) {
2292     LLDB_LOGF(log,
2293               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2294               " mem 0x%" PRIx64 ": failed to read. Error: %s",
2295               __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2296               error.AsCString());
2297     return SendErrorResponse(0x08);
2298   }
2299
2300   if (bytes_read == 0) {
2301     LLDB_LOGF(log,
2302               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2303               " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2304               __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2305               byte_count);
2306     return SendErrorResponse(0x08);
2307   }
2308
2309   StreamGDBRemote response;
2310   packet.SetFilePos(0);
2311   char kind = packet.GetChar('?');
2312   if (kind == 'x')
2313     response.PutEscapedBytes(buf.data(), byte_count);
2314   else {
2315     assert(kind == 'm');
2316     for (size_t i = 0; i < bytes_read; ++i)
2317       response.PutHex8(buf[i]);
2318   }
2319
2320   return SendPacketNoLock(response.GetString());
2321 }
2322
2323 GDBRemoteCommunication::PacketResult
2324 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2325   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2326
2327   if (!m_debugged_process_up ||
2328       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2329     LLDB_LOGF(
2330         log,
2331         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2332         __FUNCTION__);
2333     return SendErrorResponse(0x15);
2334   }
2335
2336   // Parse out the memory address.
2337   packet.SetFilePos(strlen("M"));
2338   if (packet.GetBytesLeft() < 1)
2339     return SendIllFormedResponse(packet, "Too short M packet");
2340
2341   // Read the address.  Punting on validation.
2342   // FIXME replace with Hex U64 read with no default value that fails on failed
2343   // read.
2344   const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2345
2346   // Validate comma.
2347   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2348     return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2349
2350   // Get # bytes to read.
2351   if (packet.GetBytesLeft() < 1)
2352     return SendIllFormedResponse(packet, "Length missing in M packet");
2353
2354   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2355   if (byte_count == 0) {
2356     LLDB_LOG(log, "nothing to write: zero-length packet");
2357     return PacketResult::Success;
2358   }
2359
2360   // Validate colon.
2361   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2362     return SendIllFormedResponse(
2363         packet, "Comma sep missing in M packet after byte length");
2364
2365   // Allocate the conversion buffer.
2366   std::vector<uint8_t> buf(byte_count, 0);
2367   if (buf.empty())
2368     return SendErrorResponse(0x78);
2369
2370   // Convert the hex memory write contents to bytes.
2371   StreamGDBRemote response;
2372   const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2373   if (convert_count != byte_count) {
2374     LLDB_LOG(log,
2375              "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2376              "to convert.",
2377              m_debugged_process_up->GetID(), write_addr, byte_count,
2378              convert_count);
2379     return SendIllFormedResponse(packet, "M content byte length specified did "
2380                                          "not match hex-encoded content "
2381                                          "length");
2382   }
2383
2384   // Write the process memory.
2385   size_t bytes_written = 0;
2386   Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2387                                                     byte_count, bytes_written);
2388   if (error.Fail()) {
2389     LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2390              m_debugged_process_up->GetID(), write_addr, error);
2391     return SendErrorResponse(0x09);
2392   }
2393
2394   if (bytes_written == 0) {
2395     LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2396              m_debugged_process_up->GetID(), write_addr, byte_count);
2397     return SendErrorResponse(0x09);
2398   }
2399
2400   return SendOKResponse();
2401 }
2402
2403 GDBRemoteCommunication::PacketResult
2404 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2405     StringExtractorGDBRemote &packet) {
2406   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2407
2408   // Currently only the NativeProcessProtocol knows if it can handle a
2409   // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2410   // attached to a process.  For now we'll assume the client only asks this
2411   // when a process is being debugged.
2412
2413   // Ensure we have a process running; otherwise, we can't figure this out
2414   // since we won't have a NativeProcessProtocol.
2415   if (!m_debugged_process_up ||
2416       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2417     LLDB_LOGF(
2418         log,
2419         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2420         __FUNCTION__);
2421     return SendErrorResponse(0x15);
2422   }
2423
2424   // Test if we can get any region back when asking for the region around NULL.
2425   MemoryRegionInfo region_info;
2426   const Status error =
2427       m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2428   if (error.Fail()) {
2429     // We don't support memory region info collection for this
2430     // NativeProcessProtocol.
2431     return SendUnimplementedResponse("");
2432   }
2433
2434   return SendOKResponse();
2435 }
2436
2437 GDBRemoteCommunication::PacketResult
2438 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2439     StringExtractorGDBRemote &packet) {
2440   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2441
2442   // Ensure we have a process.
2443   if (!m_debugged_process_up ||
2444       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2445     LLDB_LOGF(
2446         log,
2447         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2448         __FUNCTION__);
2449     return SendErrorResponse(0x15);
2450   }
2451
2452   // Parse out the memory address.
2453   packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2454   if (packet.GetBytesLeft() < 1)
2455     return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2456
2457   // Read the address.  Punting on validation.
2458   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2459
2460   StreamGDBRemote response;
2461
2462   // Get the memory region info for the target address.
2463   MemoryRegionInfo region_info;
2464   const Status error =
2465       m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2466   if (error.Fail()) {
2467     // Return the error message.
2468
2469     response.PutCString("error:");
2470     response.PutStringAsRawHex8(error.AsCString());
2471     response.PutChar(';');
2472   } else {
2473     // Range start and size.
2474     response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2475                     region_info.GetRange().GetRangeBase(),
2476                     region_info.GetRange().GetByteSize());
2477
2478     // Permissions.
2479     if (region_info.GetReadable() || region_info.GetWritable() ||
2480         region_info.GetExecutable()) {
2481       // Write permissions info.
2482       response.PutCString("permissions:");
2483
2484       if (region_info.GetReadable())
2485         response.PutChar('r');
2486       if (region_info.GetWritable())
2487         response.PutChar('w');
2488       if (region_info.GetExecutable())
2489         response.PutChar('x');
2490
2491       response.PutChar(';');
2492     }
2493
2494     // Name
2495     ConstString name = region_info.GetName();
2496     if (name) {
2497       response.PutCString("name:");
2498       response.PutStringAsRawHex8(name.GetStringRef());
2499       response.PutChar(';');
2500     }
2501   }
2502
2503   return SendPacketNoLock(response.GetString());
2504 }
2505
2506 GDBRemoteCommunication::PacketResult
2507 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2508   // Ensure we have a process.
2509   if (!m_debugged_process_up ||
2510       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2511     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2512     LLDB_LOG(log, "failed, no process available");
2513     return SendErrorResponse(0x15);
2514   }
2515
2516   // Parse out software or hardware breakpoint or watchpoint requested.
2517   packet.SetFilePos(strlen("Z"));
2518   if (packet.GetBytesLeft() < 1)
2519     return SendIllFormedResponse(
2520         packet, "Too short Z packet, missing software/hardware specifier");
2521
2522   bool want_breakpoint = true;
2523   bool want_hardware = false;
2524   uint32_t watch_flags = 0;
2525
2526   const GDBStoppointType stoppoint_type =
2527       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2528   switch (stoppoint_type) {
2529   case eBreakpointSoftware:
2530     want_hardware = false;
2531     want_breakpoint = true;
2532     break;
2533   case eBreakpointHardware:
2534     want_hardware = true;
2535     want_breakpoint = true;
2536     break;
2537   case eWatchpointWrite:
2538     watch_flags = 1;
2539     want_hardware = true;
2540     want_breakpoint = false;
2541     break;
2542   case eWatchpointRead:
2543     watch_flags = 2;
2544     want_hardware = true;
2545     want_breakpoint = false;
2546     break;
2547   case eWatchpointReadWrite:
2548     watch_flags = 3;
2549     want_hardware = true;
2550     want_breakpoint = false;
2551     break;
2552   case eStoppointInvalid:
2553     return SendIllFormedResponse(
2554         packet, "Z packet had invalid software/hardware specifier");
2555   }
2556
2557   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2558     return SendIllFormedResponse(
2559         packet, "Malformed Z packet, expecting comma after stoppoint type");
2560
2561   // Parse out the stoppoint address.
2562   if (packet.GetBytesLeft() < 1)
2563     return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2564   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2565
2566   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2567     return SendIllFormedResponse(
2568         packet, "Malformed Z packet, expecting comma after address");
2569
2570   // Parse out the stoppoint size (i.e. size hint for opcode size).
2571   const uint32_t size =
2572       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2573   if (size == std::numeric_limits<uint32_t>::max())
2574     return SendIllFormedResponse(
2575         packet, "Malformed Z packet, failed to parse size argument");
2576
2577   if (want_breakpoint) {
2578     // Try to set the breakpoint.
2579     const Status error =
2580         m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2581     if (error.Success())
2582       return SendOKResponse();
2583     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2584     LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2585              m_debugged_process_up->GetID(), error);
2586     return SendErrorResponse(0x09);
2587   } else {
2588     // Try to set the watchpoint.
2589     const Status error = m_debugged_process_up->SetWatchpoint(
2590         addr, size, watch_flags, want_hardware);
2591     if (error.Success())
2592       return SendOKResponse();
2593     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2594     LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2595              m_debugged_process_up->GetID(), error);
2596     return SendErrorResponse(0x09);
2597   }
2598 }
2599
2600 GDBRemoteCommunication::PacketResult
2601 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2602   // Ensure we have a process.
2603   if (!m_debugged_process_up ||
2604       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2605     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2606     LLDB_LOG(log, "failed, no process available");
2607     return SendErrorResponse(0x15);
2608   }
2609
2610   // Parse out software or hardware breakpoint or watchpoint requested.
2611   packet.SetFilePos(strlen("z"));
2612   if (packet.GetBytesLeft() < 1)
2613     return SendIllFormedResponse(
2614         packet, "Too short z packet, missing software/hardware specifier");
2615
2616   bool want_breakpoint = true;
2617   bool want_hardware = false;
2618
2619   const GDBStoppointType stoppoint_type =
2620       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2621   switch (stoppoint_type) {
2622   case eBreakpointHardware:
2623     want_breakpoint = true;
2624     want_hardware = true;
2625     break;
2626   case eBreakpointSoftware:
2627     want_breakpoint = true;
2628     break;
2629   case eWatchpointWrite:
2630     want_breakpoint = false;
2631     break;
2632   case eWatchpointRead:
2633     want_breakpoint = false;
2634     break;
2635   case eWatchpointReadWrite:
2636     want_breakpoint = false;
2637     break;
2638   default:
2639     return SendIllFormedResponse(
2640         packet, "z packet had invalid software/hardware specifier");
2641   }
2642
2643   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2644     return SendIllFormedResponse(
2645         packet, "Malformed z packet, expecting comma after stoppoint type");
2646
2647   // Parse out the stoppoint address.
2648   if (packet.GetBytesLeft() < 1)
2649     return SendIllFormedResponse(packet, "Too short z packet, missing address");
2650   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2651
2652   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2653     return SendIllFormedResponse(
2654         packet, "Malformed z packet, expecting comma after address");
2655
2656   /*
2657   // Parse out the stoppoint size (i.e. size hint for opcode size).
2658   const uint32_t size = packet.GetHexMaxU32 (false,
2659   std::numeric_limits<uint32_t>::max ());
2660   if (size == std::numeric_limits<uint32_t>::max ())
2661       return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2662   size argument");
2663   */
2664
2665   if (want_breakpoint) {
2666     // Try to clear the breakpoint.
2667     const Status error =
2668         m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2669     if (error.Success())
2670       return SendOKResponse();
2671     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2672     LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2673              m_debugged_process_up->GetID(), error);
2674     return SendErrorResponse(0x09);
2675   } else {
2676     // Try to clear the watchpoint.
2677     const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2678     if (error.Success())
2679       return SendOKResponse();
2680     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2681     LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2682              m_debugged_process_up->GetID(), error);
2683     return SendErrorResponse(0x09);
2684   }
2685 }
2686
2687 GDBRemoteCommunication::PacketResult
2688 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2689   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2690
2691   // Ensure we have a process.
2692   if (!m_debugged_process_up ||
2693       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2694     LLDB_LOGF(
2695         log,
2696         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2697         __FUNCTION__);
2698     return SendErrorResponse(0x32);
2699   }
2700
2701   // We first try to use a continue thread id.  If any one or any all set, use
2702   // the current thread. Bail out if we don't have a thread id.
2703   lldb::tid_t tid = GetContinueThreadID();
2704   if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2705     tid = GetCurrentThreadID();
2706   if (tid == LLDB_INVALID_THREAD_ID)
2707     return SendErrorResponse(0x33);
2708
2709   // Double check that we have such a thread.
2710   // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2711   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2712   if (!thread)
2713     return SendErrorResponse(0x33);
2714
2715   // Create the step action for the given thread.
2716   ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
2717
2718   // Setup the actions list.
2719   ResumeActionList actions;
2720   actions.Append(action);
2721
2722   // All other threads stop while we're single stepping a thread.
2723   actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2724   Status error = m_debugged_process_up->Resume(actions);
2725   if (error.Fail()) {
2726     LLDB_LOGF(log,
2727               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2728               " tid %" PRIu64 " Resume() failed with error: %s",
2729               __FUNCTION__, m_debugged_process_up->GetID(), tid,
2730               error.AsCString());
2731     return SendErrorResponse(0x49);
2732   }
2733
2734   // No response here - the stop or exit will come from the resulting action.
2735   return PacketResult::Success;
2736 }
2737
2738 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2739 GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
2740   // Ensure we have a thread.
2741   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
2742   if (!thread)
2743     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2744                                    "No thread available");
2745
2746   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2747   // Get the register context for the first thread.
2748   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2749
2750   StreamString response;
2751
2752   response.Printf("<?xml version=\"1.0\"?>");
2753   response.Printf("<target version=\"1.0\">");
2754
2755   response.Printf("<architecture>%s</architecture>",
2756                   m_debugged_process_up->GetArchitecture()
2757                       .GetTriple()
2758                       .getArchName()
2759                       .str()
2760                       .c_str());
2761
2762   response.Printf("<feature>");
2763
2764   const int registers_count = reg_context.GetUserRegisterCount();
2765   for (int reg_index = 0; reg_index < registers_count; reg_index++) {
2766     const RegisterInfo *reg_info =
2767         reg_context.GetRegisterInfoAtIndex(reg_index);
2768
2769     if (!reg_info) {
2770       LLDB_LOGF(log,
2771                 "%s failed to get register info for register index %" PRIu32,
2772                 "target.xml", reg_index);
2773       continue;
2774     }
2775
2776     response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" offset=\"%" PRIu32
2777                     "\" regnum=\"%d\" ",
2778                     reg_info->name, reg_info->byte_size * 8,
2779                     reg_info->byte_offset, reg_index);
2780
2781     if (reg_info->alt_name && reg_info->alt_name[0])
2782       response.Printf("altname=\"%s\" ", reg_info->alt_name);
2783
2784     llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2785     if (!encoding.empty())
2786       response << "encoding=\"" << encoding << "\" ";
2787
2788     llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2789     if (!format.empty())
2790       response << "format=\"" << format << "\" ";
2791
2792     const char *const register_set_name =
2793         reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2794     if (register_set_name)
2795       response << "group=\"" << register_set_name << "\" ";
2796
2797     if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2798         LLDB_INVALID_REGNUM)
2799       response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
2800                       reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2801
2802     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
2803         LLDB_INVALID_REGNUM)
2804       response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
2805                       reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2806
2807     llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2808     if (!kind_generic.empty())
2809       response << "generic=\"" << kind_generic << "\" ";
2810
2811     if (reg_info->value_regs &&
2812         reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2813       response.PutCString("value_regnums=\"");
2814       CollectRegNums(reg_info->value_regs, response, false);
2815       response.Printf("\" ");
2816     }
2817
2818     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2819       response.PutCString("invalidate_regnums=\"");
2820       CollectRegNums(reg_info->invalidate_regs, response, false);
2821       response.Printf("\" ");
2822     }
2823
2824     if (reg_info->dynamic_size_dwarf_expr_bytes) {
2825       const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
2826       response.PutCString("dynamic_size_dwarf_expr_bytes=\"");
2827       for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
2828         response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
2829       response.Printf("\" ");
2830     }
2831
2832     response.Printf("/>");
2833   }
2834
2835   response.Printf("</feature>");
2836   response.Printf("</target>");
2837   return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
2838 }
2839
2840 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2841 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
2842                                                  llvm::StringRef annex) {
2843   // Make sure we have a valid process.
2844   if (!m_debugged_process_up ||
2845       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2846     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2847                                    "No process available");
2848   }
2849
2850   if (object == "auxv") {
2851     // Grab the auxv data.
2852     auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2853     if (!buffer_or_error)
2854       return llvm::errorCodeToError(buffer_or_error.getError());
2855     return std::move(*buffer_or_error);
2856   }
2857
2858   if (object == "libraries-svr4") {
2859     auto library_list = m_debugged_process_up->GetLoadedSVR4Libraries();
2860     if (!library_list)
2861       return library_list.takeError();
2862
2863     StreamString response;
2864     response.Printf("<library-list-svr4 version=\"1.0\">");
2865     for (auto const &library : *library_list) {
2866       response.Printf("<library name=\"%s\" ",
2867                       XMLEncodeAttributeValue(library.name.c_str()).c_str());
2868       response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
2869       response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
2870       response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
2871     }
2872     response.Printf("</library-list-svr4>");
2873     return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
2874   }
2875
2876   if (object == "features" && annex == "target.xml")
2877     return BuildTargetXml();
2878
2879   return llvm::make_error<PacketUnimplementedError>(
2880       "Xfer object not supported");
2881 }
2882
2883 GDBRemoteCommunication::PacketResult
2884 GDBRemoteCommunicationServerLLGS::Handle_qXfer(
2885     StringExtractorGDBRemote &packet) {
2886   SmallVector<StringRef, 5> fields;
2887   // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
2888   StringRef(packet.GetStringRef()).split(fields, ':', 4);
2889   if (fields.size() != 5)
2890     return SendIllFormedResponse(packet, "malformed qXfer packet");
2891   StringRef &xfer_object = fields[1];
2892   StringRef &xfer_action = fields[2];
2893   StringRef &xfer_annex = fields[3];
2894   StringExtractor offset_data(fields[4]);
2895   if (xfer_action != "read")
2896     return SendUnimplementedResponse("qXfer action not supported");
2897   // Parse offset.
2898   const uint64_t xfer_offset =
2899       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2900   if (xfer_offset == std::numeric_limits<uint64_t>::max())
2901     return SendIllFormedResponse(packet, "qXfer packet missing offset");
2902   // Parse out comma.
2903   if (offset_data.GetChar() != ',')
2904     return SendIllFormedResponse(packet,
2905                                  "qXfer packet missing comma after offset");
2906   // Parse out the length.
2907   const uint64_t xfer_length =
2908       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2909   if (xfer_length == std::numeric_limits<uint64_t>::max())
2910     return SendIllFormedResponse(packet, "qXfer packet missing length");
2911
2912   // Get a previously constructed buffer if it exists or create it now.
2913   std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
2914   auto buffer_it = m_xfer_buffer_map.find(buffer_key);
2915   if (buffer_it == m_xfer_buffer_map.end()) {
2916     auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
2917     if (!buffer_up)
2918       return SendErrorResponse(buffer_up.takeError());
2919     buffer_it = m_xfer_buffer_map
2920                     .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
2921                     .first;
2922   }
2923
2924   // Send back the response
2925   StreamGDBRemote response;
2926   bool done_with_buffer = false;
2927   llvm::StringRef buffer = buffer_it->second->getBuffer();
2928   if (xfer_offset >= buffer.size()) {
2929     // We have nothing left to send.  Mark the buffer as complete.
2930     response.PutChar('l');
2931     done_with_buffer = true;
2932   } else {
2933     // Figure out how many bytes are available starting at the given offset.
2934     buffer = buffer.drop_front(xfer_offset);
2935     // Mark the response type according to whether we're reading the remainder
2936     // of the data.
2937     if (xfer_length >= buffer.size()) {
2938       // There will be nothing left to read after this
2939       response.PutChar('l');
2940       done_with_buffer = true;
2941     } else {
2942       // There will still be bytes to read after this request.
2943       response.PutChar('m');
2944       buffer = buffer.take_front(xfer_length);
2945     }
2946     // Now write the data in encoded binary form.
2947     response.PutEscapedBytes(buffer.data(), buffer.size());
2948   }
2949
2950   if (done_with_buffer)
2951     m_xfer_buffer_map.erase(buffer_it);
2952
2953   return SendPacketNoLock(response.GetString());
2954 }
2955
2956 GDBRemoteCommunication::PacketResult
2957 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2958     StringExtractorGDBRemote &packet) {
2959   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2960
2961   // Move past packet name.
2962   packet.SetFilePos(strlen("QSaveRegisterState"));
2963
2964   // Get the thread to use.
2965   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2966   if (!thread) {
2967     if (m_thread_suffix_supported)
2968       return SendIllFormedResponse(
2969           packet, "No thread specified in QSaveRegisterState packet");
2970     else
2971       return SendIllFormedResponse(packet,
2972                                    "No thread was is set with the Hg packet");
2973   }
2974
2975   // Grab the register context for the thread.
2976   NativeRegisterContext& reg_context = thread->GetRegisterContext();
2977
2978   // Save registers to a buffer.
2979   DataBufferSP register_data_sp;
2980   Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2981   if (error.Fail()) {
2982     LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2983              m_debugged_process_up->GetID(), error);
2984     return SendErrorResponse(0x75);
2985   }
2986
2987   // Allocate a new save id.
2988   const uint32_t save_id = GetNextSavedRegistersID();
2989   assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2990          "GetNextRegisterSaveID() returned an existing register save id");
2991
2992   // Save the register data buffer under the save id.
2993   {
2994     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2995     m_saved_registers_map[save_id] = register_data_sp;
2996   }
2997
2998   // Write the response.
2999   StreamGDBRemote response;
3000   response.Printf("%" PRIu32, save_id);
3001   return SendPacketNoLock(response.GetString());
3002 }
3003
3004 GDBRemoteCommunication::PacketResult
3005 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3006     StringExtractorGDBRemote &packet) {
3007   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3008
3009   // Parse out save id.
3010   packet.SetFilePos(strlen("QRestoreRegisterState:"));
3011   if (packet.GetBytesLeft() < 1)
3012     return SendIllFormedResponse(
3013         packet, "QRestoreRegisterState packet missing register save id");
3014
3015   const uint32_t save_id = packet.GetU32(0);
3016   if (save_id == 0) {
3017     LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3018                   "expecting decimal uint32_t");
3019     return SendErrorResponse(0x76);
3020   }
3021
3022   // Get the thread to use.
3023   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3024   if (!thread) {
3025     if (m_thread_suffix_supported)
3026       return SendIllFormedResponse(
3027           packet, "No thread specified in QRestoreRegisterState packet");
3028     else
3029       return SendIllFormedResponse(packet,
3030                                    "No thread was is set with the Hg packet");
3031   }
3032
3033   // Grab the register context for the thread.
3034   NativeRegisterContext &reg_context = thread->GetRegisterContext();
3035
3036   // Retrieve register state buffer, then remove from the list.
3037   DataBufferSP register_data_sp;
3038   {
3039     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3040
3041     // Find the register set buffer for the given save id.
3042     auto it = m_saved_registers_map.find(save_id);
3043     if (it == m_saved_registers_map.end()) {
3044       LLDB_LOG(log,
3045                "pid {0} does not have a register set save buffer for id {1}",
3046                m_debugged_process_up->GetID(), save_id);
3047       return SendErrorResponse(0x77);
3048     }
3049     register_data_sp = it->second;
3050
3051     // Remove it from the map.
3052     m_saved_registers_map.erase(it);
3053   }
3054
3055   Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3056   if (error.Fail()) {
3057     LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3058              m_debugged_process_up->GetID(), error);
3059     return SendErrorResponse(0x77);
3060   }
3061
3062   return SendOKResponse();
3063 }
3064
3065 GDBRemoteCommunication::PacketResult
3066 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3067     StringExtractorGDBRemote &packet) {
3068   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3069
3070   // Consume the ';' after vAttach.
3071   packet.SetFilePos(strlen("vAttach"));
3072   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3073     return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3074
3075   // Grab the PID to which we will attach (assume hex encoding).
3076   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3077   if (pid == LLDB_INVALID_PROCESS_ID)
3078     return SendIllFormedResponse(packet,
3079                                  "vAttach failed to parse the process id");
3080
3081   // Attempt to attach.
3082   LLDB_LOGF(log,
3083             "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3084             "pid %" PRIu64,
3085             __FUNCTION__, pid);
3086
3087   Status error = AttachToProcess(pid);
3088
3089   if (error.Fail()) {
3090     LLDB_LOGF(log,
3091               "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3092               "pid %" PRIu64 ": %s\n",
3093               __FUNCTION__, pid, error.AsCString());
3094     return SendErrorResponse(error);
3095   }
3096
3097   // Notify we attached by sending a stop packet.
3098   return SendStopReasonForState(m_debugged_process_up->GetState());
3099 }
3100
3101 GDBRemoteCommunication::PacketResult
3102 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3103   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3104
3105   StopSTDIOForwarding();
3106
3107   // Fail if we don't have a current process.
3108   if (!m_debugged_process_up ||
3109       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
3110     LLDB_LOGF(
3111         log,
3112         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3113         __FUNCTION__);
3114     return SendErrorResponse(0x15);
3115   }
3116
3117   lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3118
3119   // Consume the ';' after D.
3120   packet.SetFilePos(1);
3121   if (packet.GetBytesLeft()) {
3122     if (packet.GetChar() != ';')
3123       return SendIllFormedResponse(packet, "D missing expected ';'");
3124
3125     // Grab the PID from which we will detach (assume hex encoding).
3126     pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3127     if (pid == LLDB_INVALID_PROCESS_ID)
3128       return SendIllFormedResponse(packet, "D failed to parse the process id");
3129   }
3130
3131   if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
3132     return SendIllFormedResponse(packet, "Invalid pid");
3133   }
3134
3135   const Status error = m_debugged_process_up->Detach();
3136   if (error.Fail()) {
3137     LLDB_LOGF(log,
3138               "GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3139               "pid %" PRIu64 ": %s\n",
3140               __FUNCTION__, m_debugged_process_up->GetID(), error.AsCString());
3141     return SendErrorResponse(0x01);
3142   }
3143
3144   return SendOKResponse();
3145 }
3146
3147 GDBRemoteCommunication::PacketResult
3148 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3149     StringExtractorGDBRemote &packet) {
3150   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3151
3152   packet.SetFilePos(strlen("qThreadStopInfo"));
3153   const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3154   if (tid == LLDB_INVALID_THREAD_ID) {
3155     LLDB_LOGF(log,
3156               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3157               "parse thread id from request \"%s\"",
3158               __FUNCTION__, packet.GetStringRef().data());
3159     return SendErrorResponse(0x15);
3160   }
3161   return SendStopReplyPacketForThread(tid);
3162 }
3163
3164 GDBRemoteCommunication::PacketResult
3165 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3166     StringExtractorGDBRemote &) {
3167   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3168
3169   // Ensure we have a debugged process.
3170   if (!m_debugged_process_up ||
3171       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3172     return SendErrorResponse(50);
3173   LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3174
3175   StreamString response;
3176   const bool threads_with_valid_stop_info_only = false;
3177   llvm::Expected<json::Value> threads_info = GetJSONThreadsInfo(
3178       *m_debugged_process_up, threads_with_valid_stop_info_only);
3179   if (!threads_info) {
3180     LLDB_LOG_ERROR(log, threads_info.takeError(),
3181                    "failed to prepare a packet for pid {1}: {0}",
3182                    m_debugged_process_up->GetID());
3183     return SendErrorResponse(52);
3184   }
3185
3186   response.AsRawOstream() << *threads_info;
3187   StreamGDBRemote escaped_response;
3188   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3189   return SendPacketNoLock(escaped_response.GetString());
3190 }
3191
3192 GDBRemoteCommunication::PacketResult
3193 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3194     StringExtractorGDBRemote &packet) {
3195   // Fail if we don't have a current process.
3196   if (!m_debugged_process_up ||
3197       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3198     return SendErrorResponse(68);
3199
3200   packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3201   if (packet.GetBytesLeft() == 0)
3202     return SendOKResponse();
3203   if (packet.GetChar() != ':')
3204     return SendErrorResponse(67);
3205
3206   auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3207
3208   StreamGDBRemote response;
3209   if (hw_debug_cap == llvm::None)
3210     response.Printf("num:0;");
3211   else
3212     response.Printf("num:%d;", hw_debug_cap->second);
3213
3214   return SendPacketNoLock(response.GetString());
3215 }
3216
3217 GDBRemoteCommunication::PacketResult
3218 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3219     StringExtractorGDBRemote &packet) {
3220   // Fail if we don't have a current process.
3221   if (!m_debugged_process_up ||
3222       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3223     return SendErrorResponse(67);
3224
3225   packet.SetFilePos(strlen("qFileLoadAddress:"));
3226   if (packet.GetBytesLeft() == 0)
3227     return SendErrorResponse(68);
3228
3229   std::string file_name;
3230   packet.GetHexByteString(file_name);
3231
3232   lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3233   Status error =
3234       m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3235   if (error.Fail())
3236     return SendErrorResponse(69);
3237
3238   if (file_load_address == LLDB_INVALID_ADDRESS)
3239     return SendErrorResponse(1); // File not loaded
3240
3241   StreamGDBRemote response;
3242   response.PutHex64(file_load_address);
3243   return SendPacketNoLock(response.GetString());
3244 }
3245
3246 GDBRemoteCommunication::PacketResult
3247 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3248     StringExtractorGDBRemote &packet) {
3249   std::vector<int> signals;
3250   packet.SetFilePos(strlen("QPassSignals:"));
3251
3252   // Read sequence of hex signal numbers divided by a semicolon and optionally
3253   // spaces.
3254   while (packet.GetBytesLeft() > 0) {
3255     int signal = packet.GetS32(-1, 16);
3256     if (signal < 0)
3257       return SendIllFormedResponse(packet, "Failed to parse signal number.");
3258     signals.push_back(signal);
3259
3260     packet.SkipSpaces();
3261     char separator = packet.GetChar();
3262     if (separator == '\0')
3263       break; // End of string
3264     if (separator != ';')
3265       return SendIllFormedResponse(packet, "Invalid separator,"
3266                                             " expected semicolon.");
3267   }
3268
3269   // Fail if we don't have a current process.
3270   if (!m_debugged_process_up)
3271     return SendErrorResponse(68);
3272
3273   Status error = m_debugged_process_up->IgnoreSignals(signals);
3274   if (error.Fail())
3275     return SendErrorResponse(69);
3276
3277   return SendOKResponse();
3278 }
3279
3280 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3281   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3282
3283   // Tell the stdio connection to shut down.
3284   if (m_stdio_communication.IsConnected()) {
3285     auto connection = m_stdio_communication.GetConnection();
3286     if (connection) {
3287       Status error;
3288       connection->Disconnect(&error);
3289
3290       if (error.Success()) {
3291         LLDB_LOGF(log,
3292                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3293                   "terminal stdio - SUCCESS",
3294                   __FUNCTION__);
3295       } else {
3296         LLDB_LOGF(log,
3297                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3298                   "terminal stdio - FAIL: %s",
3299                   __FUNCTION__, error.AsCString());
3300       }
3301     }
3302   }
3303 }
3304
3305 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3306     StringExtractorGDBRemote &packet) {
3307   // We have no thread if we don't have a process.
3308   if (!m_debugged_process_up ||
3309       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3310     return nullptr;
3311
3312   // If the client hasn't asked for thread suffix support, there will not be a
3313   // thread suffix. Use the current thread in that case.
3314   if (!m_thread_suffix_supported) {
3315     const lldb::tid_t current_tid = GetCurrentThreadID();
3316     if (current_tid == LLDB_INVALID_THREAD_ID)
3317       return nullptr;
3318     else if (current_tid == 0) {
3319       // Pick a thread.
3320       return m_debugged_process_up->GetThreadAtIndex(0);
3321     } else
3322       return m_debugged_process_up->GetThreadByID(current_tid);
3323   }
3324
3325   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3326
3327   // Parse out the ';'.
3328   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3329     LLDB_LOGF(log,
3330               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3331               "error: expected ';' prior to start of thread suffix: packet "
3332               "contents = '%s'",
3333               __FUNCTION__, packet.GetStringRef().data());
3334     return nullptr;
3335   }
3336
3337   if (!packet.GetBytesLeft())
3338     return nullptr;
3339
3340   // Parse out thread: portion.
3341   if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3342     LLDB_LOGF(log,
3343               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3344               "error: expected 'thread:' but not found, packet contents = "
3345               "'%s'",
3346               __FUNCTION__, packet.GetStringRef().data());
3347     return nullptr;
3348   }
3349   packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3350   const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3351   if (tid != 0)
3352     return m_debugged_process_up->GetThreadByID(tid);
3353
3354   return nullptr;
3355 }
3356
3357 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3358   if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3359     // Use whatever the debug process says is the current thread id since the
3360     // protocol either didn't specify or specified we want any/all threads
3361     // marked as the current thread.
3362     if (!m_debugged_process_up)
3363       return LLDB_INVALID_THREAD_ID;
3364     return m_debugged_process_up->GetCurrentThreadID();
3365   }
3366   // Use the specific current thread id set by the gdb remote protocol.
3367   return m_current_tid;
3368 }
3369
3370 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3371   std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3372   return m_next_saved_registers_id++;
3373 }
3374
3375 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3376   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3377
3378   LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
3379   m_xfer_buffer_map.clear();
3380 }
3381
3382 FileSpec
3383 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3384                                                  const ArchSpec &arch) {
3385   if (m_debugged_process_up) {
3386     FileSpec file_spec;
3387     if (m_debugged_process_up
3388             ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3389             .Success()) {
3390       if (FileSystem::Instance().Exists(file_spec))
3391         return file_spec;
3392     }
3393   }
3394
3395   return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
3396 }
3397
3398 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
3399     llvm::StringRef value) {
3400   std::string result;
3401   for (const char &c : value) {
3402     switch (c) {
3403     case '\'':
3404       result += "&apos;";
3405       break;
3406     case '"':
3407       result += "&quot;";
3408       break;
3409     case '<':
3410       result += "&lt;";
3411       break;
3412     case '>':
3413       result += "&gt;";
3414       break;
3415     default:
3416       result += c;
3417       break;
3418     }
3419   }
3420   return result;
3421 }