blob: 9294359dbef1c3173bc2fca3a8e1c80683ca6158 [file] [log] [blame]
Tamas Berghammere13c2732015-02-11 10:29:30 +00001//===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <errno.h>
11
12#include "lldb/Host/Config.h"
13
14#include "GDBRemoteCommunicationServerLLGS.h"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000015#include "lldb/Utility/StreamGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000016
17// C Includes
18// C++ Includes
Tamas Berghammere13c2732015-02-11 10:29:30 +000019#include <chrono>
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include <cstring>
Tamas Berghammere13c2732015-02-11 10:29:30 +000021#include <thread>
22
23// Other libraries and framework includes
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000024#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000025#include "lldb/Core/State.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
27#include "lldb/Host/Debug.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000028#include "lldb/Host/File.h"
29#include "lldb/Host/FileSystem.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Host/HostInfo.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000032#include "lldb/Host/PosixApi.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000033#include "lldb/Host/common/NativeProcessProtocol.h"
34#include "lldb/Host/common/NativeRegisterContext.h"
35#include "lldb/Host/common/NativeThreadProtocol.h"
36#include "lldb/Interpreter/Args.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000037#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000039#include "lldb/Utility/DataBuffer.h"
Zachary Turner01c32432017-02-14 19:06:07 +000040#include "lldb/Utility/Endian.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000041#include "lldb/Utility/JSON.h"
Pavel Labathabadc222015-11-27 13:33:29 +000042#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000043#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000044#include "lldb/Utility/StreamString.h"
Pavel Labath5f7e5832017-02-10 12:21:22 +000045#include "lldb/Utility/UriParser.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000046#include "llvm/ADT/Triple.h"
47#include "llvm/Support/ScopedPrinter.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000048
49// Project includes
Tamas Berghammere13c2732015-02-11 10:29:30 +000050#include "ProcessGDBRemote.h"
51#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000052#include "Utility/StringExtractorGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000053
54using namespace lldb;
55using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000056using namespace lldb_private::process_gdb_remote;
Tamas Berghammer783bfc82015-06-18 20:43:56 +000057using namespace llvm;
Tamas Berghammere13c2732015-02-11 10:29:30 +000058
59//----------------------------------------------------------------------
60// GDBRemote Errors
61//----------------------------------------------------------------------
62
Kate Stoneb9c1b512016-09-06 20:57:50 +000063namespace {
64enum GDBRemoteServerError {
65 // Set to the first unused error number in literal form below
66 eErrorFirst = 29,
67 eErrorNoProcess = eErrorFirst,
68 eErrorResume,
69 eErrorExitStatus
70};
Tamas Berghammere13c2732015-02-11 10:29:30 +000071}
72
73//----------------------------------------------------------------------
74// GDBRemoteCommunicationServerLLGS constructor
75//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000076GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
Pavel Labath96e600f2017-07-07 11:02:19 +000077 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
79 "gdb-remote.server.rx_packet"),
Pavel Labath96e600f2017-07-07 11:02:19 +000080 m_mainloop(mainloop), m_process_factory(process_factory),
81 m_stdio_communication("process.stdio") {
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000083}
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
87 &GDBRemoteCommunicationServerLLGS::Handle_C);
88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
89 &GDBRemoteCommunicationServerLLGS::Handle_c);
90 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
91 &GDBRemoteCommunicationServerLLGS::Handle_D);
92 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
93 &GDBRemoteCommunicationServerLLGS::Handle_H);
94 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
95 &GDBRemoteCommunicationServerLLGS::Handle_I);
96 RegisterMemberFunctionHandler(
97 StringExtractorGDBRemote::eServerPacketType_interrupt,
98 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_m,
101 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
103 &GDBRemoteCommunicationServerLLGS::Handle_M);
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
105 &GDBRemoteCommunicationServerLLGS::Handle_p);
106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
107 &GDBRemoteCommunicationServerLLGS::Handle_P);
108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
109 &GDBRemoteCommunicationServerLLGS::Handle_qC);
110 RegisterMemberFunctionHandler(
111 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
112 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
115 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
118 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
121 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
127 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
133 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
145 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
157 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
158 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
159 &GDBRemoteCommunicationServerLLGS::Handle_s);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_stop_reason,
162 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_vAttach,
165 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vCont,
168 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_x,
174 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
175 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
176 &GDBRemoteCommunicationServerLLGS::Handle_Z);
177 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
178 &GDBRemoteCommunicationServerLLGS::Handle_z);
Pavel Labath4a705e72017-02-24 09:29:14 +0000179 RegisterMemberFunctionHandler(
180 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
181 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000182
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +0000183 RegisterMemberFunctionHandler(
184 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
185 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
191 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
194 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
195 RegisterMemberFunctionHandler(
196 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
197 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
Zachary Turner97206d52017-05-12 04:51:55 +0000200 [this](StringExtractorGDBRemote packet, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 bool &interrupt, bool &quit) {
202 quit = true;
203 return this->Handle_k(packet);
204 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000205}
206
Zachary Turner97206d52017-05-12 04:51:55 +0000207Status
208GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
209 int argc) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 if ((argc < 1) || !args || !args[0] || !args[0][0])
Zachary Turner97206d52017-05-12 04:51:55 +0000211 return Status("%s: no process command line specified to launch",
212 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
Zachary Turner97206d52017-05-12 04:51:55 +0000215 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000216}
217
Zachary Turner97206d52017-05-12 04:51:55 +0000218Status
219GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 m_process_launch_info.GetFlags().Set(launch_flags);
Zachary Turner97206d52017-05-12 04:51:55 +0000221 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000222}
223
Zachary Turner97206d52017-05-12 04:51:55 +0000224Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000228 return Status("%s: no process command line specified to launch",
229 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 const bool should_forward_stdio =
232 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
233 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
234 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
235 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
236 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000237
Kate Stoneb9c1b512016-09-06 20:57:50 +0000238 const bool default_to_use_pty = true;
239 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 {
242 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
Pavel Labath82abefa2017-07-18 09:24:48 +0000243 assert(!m_debugged_process_up && "lldb-server creating debugged "
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 "process but one already exists");
Pavel Labath96e600f2017-07-07 11:02:19 +0000245 auto process_or =
246 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
247 if (!process_or) {
248 Status status(process_or.takeError());
249 llvm::errs() << llvm::formatv(
250 "failed to launch executable `{0}`: {1}",
251 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), status);
252 return status;
253 }
Pavel Labath82abefa2017-07-18 09:24:48 +0000254 m_debugged_process_up = std::move(*process_or);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
258 // as needed.
259 // llgs local-process debugging may specify PTY paths, which will make these
260 // file actions non-null
261 // process launch -i/e/o will also make these file actions non-null
262 // nullptr means that the traffic is expected to flow over gdb-remote protocol
263 if (should_forward_stdio) {
264 // nullptr means it's not redirected to file or pty (in case of LLGS local)
265 // at least one of stdio will be transferred pty<->gdb-remote
266 // we need to give the pty master handle to this object to read and/or write
Pavel Labath82abefa2017-07-18 09:24:48 +0000267 LLDB_LOG(log,
268 "pid = {0}: setting up stdout/stderr redirection via $O "
269 "gdb-remote commands",
270 m_debugged_process_up->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // Setup stdout/stderr mapping from inferior to $O
Pavel Labath82abefa2017-07-18 09:24:48 +0000273 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 if (terminal_fd >= 0) {
275 if (log)
276 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
277 "inferior STDIO fd to %d",
278 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000279 Status status = SetSTDIOFileDescriptor(terminal_fd);
280 if (status.Fail())
281 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 } else {
283 if (log)
284 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
285 "inferior STDIO since terminal fd reported as %d",
286 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000287 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 } else {
Pavel Labath82abefa2017-07-18 09:24:48 +0000289 LLDB_LOG(log,
290 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
291 "will communicate over client-provided file descriptors",
292 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000294
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 printf("Launched '%s' as process %" PRIu64 "...\n",
296 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
Pavel Labath82abefa2017-07-18 09:24:48 +0000297 m_debugged_process_up->GetID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000298
Pavel Labath96e600f2017-07-07 11:02:19 +0000299 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000300}
301
Zachary Turner97206d52017-05-12 04:51:55 +0000302Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
304 if (log)
305 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
306 __FUNCTION__, pid);
307
308 // Before we try to attach, make sure we aren't already monitoring something
309 // else.
Pavel Labath82abefa2017-07-18 09:24:48 +0000310 if (m_debugged_process_up &&
311 m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
Zachary Turner97206d52017-05-12 04:51:55 +0000312 return Status("cannot attach to a process %" PRIu64
313 " when another process with pid %" PRIu64
314 " is being debugged.",
Pavel Labath82abefa2017-07-18 09:24:48 +0000315 pid, m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316
317 // Try to attach.
Pavel Labath96e600f2017-07-07 11:02:19 +0000318 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
319 if (!process_or) {
320 Status status(process_or.takeError());
321 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
322 status);
323 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 }
Pavel Labath82abefa2017-07-18 09:24:48 +0000325 m_debugged_process_up = std::move(*process_or);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326
327 // Setup stdout/stderr mapping from inferior.
Pavel Labath82abefa2017-07-18 09:24:48 +0000328 auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000330 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
332 "inferior STDIO fd to %d",
333 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000334 Status status = SetSTDIOFileDescriptor(terminal_fd);
335 if (status.Fail())
336 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 } else {
338 if (log)
339 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
340 "inferior STDIO since terminal fd reported as %d",
341 __FUNCTION__, terminal_fd);
342 }
343
344 printf("Attached to process %" PRIu64 "...\n", pid);
Pavel Labath96e600f2017-07-07 11:02:19 +0000345 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346}
347
348void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
349 NativeProcessProtocol *process) {
350 assert(process && "process cannot be NULL");
351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
352 if (log) {
353 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
354 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
355 __FUNCTION__, process->GetID(),
356 StateAsCString(process->GetState()));
357 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000358}
359
360GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361GDBRemoteCommunicationServerLLGS::SendWResponse(
362 NativeProcessProtocol *process) {
363 assert(process && "process cannot be NULL");
364 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 // send W notification
Pavel Labath3508fc82017-06-19 12:47:50 +0000367 auto wait_status = process->GetExitStatus();
368 if (!wait_status) {
369 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
370 process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 StreamGDBRemote response;
373 response.PutChar('E');
374 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
375 return SendPacketNoLock(response.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 }
Pavel Labath3508fc82017-06-19 12:47:50 +0000377
378 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
379 *wait_status);
380
381 StreamGDBRemote response;
382 response.Format("{0:g}", *wait_status);
383 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000384}
385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386static void AppendHexValue(StreamString &response, const uint8_t *buf,
387 uint32_t buf_size, bool swap) {
388 int64_t i;
389 if (swap) {
390 for (i = buf_size - 1; i >= 0; i--)
391 response.PutHex8(buf[i]);
392 } else {
393 for (i = 0; i < buf_size; i++)
394 response.PutHex8(buf[i]);
395 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398static void WriteRegisterValueInHexFixedWidth(
399 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000400 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
401 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 RegisterValue reg_value;
403 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000404 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 if (error.Success())
406 reg_value_p = &reg_value;
407 // else log.
408 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 if (reg_value_p) {
411 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000412 reg_value_p->GetByteSize(),
413 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 } else {
415 // Zero-out any unreadable values.
416 if (reg_info.byte_size > 0) {
417 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
418 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000419 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000421}
422
Pavel Labathe0a5b572017-01-20 14:17:16 +0000423static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
427 if (!reg_ctx_sp)
428 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000429
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000431
432#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 // Expedite all registers in the first register set (i.e. should be GPRs) that
434 // are not contained in other registers.
435 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
436 if (!reg_set_p)
437 return nullptr;
438 for (const uint32_t *reg_num_p = reg_set_p->registers;
439 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
440 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000441#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 // Expedite only a couple of registers until we figure out why sending
443 // registers is
444 // expensive.
445 static const uint32_t k_expedited_registers[] = {
446 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
447 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000448
Pavel Labathe0a5b572017-01-20 14:17:16 +0000449 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
451 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
452 eRegisterKindGeneric, *generic_reg_p);
453 if (reg_num == LLDB_INVALID_REGNUM)
454 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000455#endif
456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 const RegisterInfo *const reg_info_p =
458 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
459 if (reg_info_p == nullptr) {
460 if (log)
461 log->Printf(
462 "%s failed to get register info for register index %" PRIu32,
463 __FUNCTION__, reg_num);
464 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000465 }
466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 if (reg_info_p->value_regs != nullptr)
468 continue; // Only expedite registers that are not contained in other
469 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000470
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000472 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473 if (error.Fail()) {
474 if (log)
475 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000476 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
478 reg_num, error.AsCString());
479 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000480 }
481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 StreamString stream;
483 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000484 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485
486 register_object_sp->SetObject(
487 llvm::to_string(reg_num),
488 std::make_shared<JSONString>(stream.GetString()));
489 }
490
491 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000492}
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494static const char *GetStopReasonString(StopReason stop_reason) {
495 switch (stop_reason) {
496 case eStopReasonTrace:
497 return "trace";
498 case eStopReasonBreakpoint:
499 return "breakpoint";
500 case eStopReasonWatchpoint:
501 return "watchpoint";
502 case eStopReasonSignal:
503 return "signal";
504 case eStopReasonException:
505 return "exception";
506 case eStopReasonExec:
507 return "exec";
508 case eStopReasonInstrumentation:
509 case eStopReasonInvalid:
510 case eStopReasonPlanComplete:
511 case eStopReasonThreadExiting:
512 case eStopReasonNone:
513 break; // ignored
514 }
515 return nullptr;
516}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
519 bool abridged) {
520 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 // Ensure we can get info on the given thread.
525 uint32_t thread_idx = 0;
526 for (NativeThreadProtocolSP thread_sp;
527 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
528 ++thread_idx) {
529
530 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000531
532 // Grab the reason this thread stopped.
533 struct ThreadStopInfo tid_stop_info;
534 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 if (!thread_sp->GetStopReason(tid_stop_info, description))
536 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 const int signum = tid_stop_info.details.signal.signo;
539 if (log) {
540 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
541 " tid %" PRIu64
542 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
543 __FUNCTION__, process.GetID(), tid, signum,
544 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000545 }
546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
548 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000549
Pavel Labathe0a5b572017-01-20 14:17:16 +0000550 if (!abridged) {
551 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
552 thread_obj_sp->SetObject("registers", registers_sp);
553 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
556 if (signum != 0)
557 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 const std::string thread_name = thread_sp->GetName();
560 if (!thread_name.empty())
561 thread_obj_sp->SetObject("name",
562 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
565 thread_obj_sp->SetObject("reason",
566 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000567
568 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 thread_obj_sp->SetObject("description",
570 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 if ((tid_stop_info.reason == eStopReasonException) &&
573 tid_stop_info.details.exception.type) {
574 thread_obj_sp->SetObject(
575 "metype",
576 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
577
578 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
579 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
580 ++i) {
581 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
582 tid_stop_info.details.exception.data[i]));
583 }
584 thread_obj_sp->SetObject("medata", medata_array_sp);
585 }
586
587 // TODO: Expedite interesting regions of inferior memory
588 }
589
590 return threads_array_sp;
591}
592
593GDBRemoteCommunication::PacketResult
594GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
595 lldb::tid_t tid) {
596 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
597
598 // Ensure we have a debugged process.
Pavel Labath82abefa2017-07-18 09:24:48 +0000599 if (!m_debugged_process_up ||
600 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 return SendErrorResponse(50);
602
Pavel Labath82abefa2017-07-18 09:24:48 +0000603 LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
604 m_debugged_process_up->GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605
606 // Ensure we can get info on the given thread.
Pavel Labath82abefa2017-07-18 09:24:48 +0000607 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadByID(tid));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 if (!thread_sp)
609 return SendErrorResponse(51);
610
611 // Grab the reason this thread stopped.
612 struct ThreadStopInfo tid_stop_info;
613 std::string description;
614 if (!thread_sp->GetStopReason(tid_stop_info, description))
615 return SendErrorResponse(52);
616
617 // FIXME implement register handling for exec'd inferiors.
618 // if (tid_stop_info.reason == eStopReasonExec)
619 // {
620 // const bool force = true;
621 // InitializeRegisters(force);
622 // }
623
624 StreamString response;
625 // Output the T packet with the thread
626 response.PutChar('T');
627 int signum = tid_stop_info.details.signal.signo;
Pavel Labath82abefa2017-07-18 09:24:48 +0000628 LLDB_LOG(
629 log,
630 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
631 m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
632 tid_stop_info.details.exception.type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633
634 // Print the signal number.
635 response.PutHex8(signum & 0xff);
636
637 // Include the tid.
638 response.Printf("thread:%" PRIx64 ";", tid);
639
640 // Include the thread name if there is one.
641 const std::string thread_name = thread_sp->GetName();
642 if (!thread_name.empty()) {
643 size_t thread_name_len = thread_name.length();
644
645 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
646 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000647 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 } else {
649 // The thread name contains special chars, send as hex bytes.
650 response.PutCString("hexname:");
651 response.PutCStringAsRawHex8(thread_name.c_str());
652 }
653 response.PutChar(';');
654 }
655
656 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
657 // will send all thread IDs back in the "threads" key whose value is
658 // a list of hex thread IDs separated by commas:
659 // "threads:10a,10b,10c;"
660 // This will save the debugger from having to send a pair of qfThreadInfo
661 // and qsThreadInfo packets, but it also might take a lot of room in the
662 // stop reply packet, so it must be enabled only on systems where there
663 // are no limits on packet lengths.
664 if (m_list_threads_in_stop_reply) {
665 response.PutCString("threads:");
666
667 uint32_t thread_index = 0;
668 NativeThreadProtocolSP listed_thread_sp;
669 for (listed_thread_sp =
Pavel Labath82abefa2017-07-18 09:24:48 +0000670 m_debugged_process_up->GetThreadAtIndex(thread_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 listed_thread_sp; ++thread_index,
Pavel Labath82abefa2017-07-18 09:24:48 +0000672 listed_thread_sp = m_debugged_process_up->GetThreadAtIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 thread_index)) {
674 if (thread_index > 0)
675 response.PutChar(',');
676 response.Printf("%" PRIx64, listed_thread_sp->GetID());
677 }
678 response.PutChar(';');
679
680 // Include JSON info that describes the stop reason for any threads
681 // that actually have stop reasons. We use the new "jstopinfo" key
682 // whose values is hex ascii JSON that contains the thread IDs
683 // thread stop info only for threads that have stop reasons. Only send
684 // this if we have more than one thread otherwise this packet has all
685 // the info it needs.
686 if (thread_index > 0) {
687 const bool threads_with_valid_stop_info_only = true;
688 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
Pavel Labath82abefa2017-07-18 09:24:48 +0000689 *m_debugged_process_up, threads_with_valid_stop_info_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 if (threads_info_sp) {
691 response.PutCString("jstopinfo:");
692 StreamString unescaped_response;
693 threads_info_sp->Write(unescaped_response);
694 response.PutCStringAsRawHex8(unescaped_response.GetData());
695 response.PutChar(';');
Pavel Labath82abefa2017-07-18 09:24:48 +0000696 } else
697 LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}",
698 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000700
701 uint32_t i = 0;
702 response.PutCString("thread-pcs");
703 char delimiter = ':';
704 for (NativeThreadProtocolSP thread_sp;
Pavel Labath82abefa2017-07-18 09:24:48 +0000705 (thread_sp = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
Pavel Labathe0a5b572017-01-20 14:17:16 +0000706 ++i) {
707 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
708 if (!reg_ctx_sp)
709 continue;
710
711 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
712 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
713 const RegisterInfo *const reg_info_p =
714 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
715
716 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000717 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000718 if (error.Fail()) {
719 if (log)
720 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
721 __FUNCTION__,
722 reg_info_p->name ? reg_info_p->name
723 : "<unnamed-register>",
724 reg_to_read, error.AsCString());
725 continue;
726 }
727
728 response.PutChar(delimiter);
729 delimiter = ',';
730 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
731 &reg_value, endian::InlHostByteOrder());
732 }
733
734 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 }
736
737 //
738 // Expedite registers.
739 //
740
741 // Grab the register context.
742 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
743 if (reg_ctx_sp) {
744 // Expedite all registers in the first register set (i.e. should be GPRs)
745 // that are not contained in other registers.
746 const RegisterSet *reg_set_p;
747 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
748 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
749 if (log)
750 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
751 "from set '%s' (registers set count: %zu)",
752 __FUNCTION__,
753 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
754 reg_set_p->num_registers);
755
756 for (const uint32_t *reg_num_p = reg_set_p->registers;
757 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
758 const RegisterInfo *const reg_info_p =
759 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
760 if (reg_info_p == nullptr) {
761 if (log)
762 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
763 "register info for register set '%s', register index "
764 "%" PRIu32,
765 __FUNCTION__,
766 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
767 *reg_num_p);
768 } else if (reg_info_p->value_regs == nullptr) {
769 // Only expediate registers that are not contained in other registers.
770 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000771 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 if (error.Success()) {
773 response.Printf("%.02x:", *reg_num_p);
774 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000775 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 response.PutChar(';');
777 } else {
778 if (log)
779 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
780 "register '%s' index %" PRIu32 ": %s",
781 __FUNCTION__, reg_info_p->name ? reg_info_p->name
782 : "<unnamed-register>",
783 *reg_num_p, error.AsCString());
784 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000785 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000787 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
791 if (reason_str != nullptr) {
792 response.Printf("reason:%s;", reason_str);
793 }
794
795 if (!description.empty()) {
796 // Description may contains special chars, send as hex bytes.
797 response.PutCString("description:");
798 response.PutCStringAsRawHex8(description.c_str());
799 response.PutChar(';');
800 } else if ((tid_stop_info.reason == eStopReasonException) &&
801 tid_stop_info.details.exception.type) {
802 response.PutCString("metype:");
803 response.PutHex64(tid_stop_info.details.exception.type);
804 response.PutCString(";mecount:");
805 response.PutHex32(tid_stop_info.details.exception.data_count);
806 response.PutChar(';');
807
808 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
809 response.PutCString("medata:");
810 response.PutHex64(tid_stop_info.details.exception.data[i]);
811 response.PutChar(';');
812 }
813 }
814
815 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000816}
817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
819 NativeProcessProtocol *process) {
820 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000821
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
823 if (log)
824 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
825
826 PacketResult result = SendStopReasonForState(StateType::eStateExited);
827 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000828 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
830 "notification for PID %" PRIu64 ", state: eStateExited",
831 __FUNCTION__, process->GetID());
832 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 // Close the pipe to the inferior terminal i/o if we launched it
835 // and set one up.
836 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000837
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 // We are ready to exit the debug monitor.
839 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000840}
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
843 NativeProcessProtocol *process) {
844 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
847 if (log)
848 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 // Send the stop reason unless this is the stop after the
851 // launch or attach.
852 switch (m_inferior_prev_state) {
853 case eStateLaunching:
854 case eStateAttaching:
855 // Don't send anything per debugserver behavior.
856 break;
857 default:
858 // In all other cases, send the stop reason.
859 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
860 if (result != PacketResult::Success) {
861 if (log)
862 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
863 "notification for PID %" PRIu64 ", state: eStateExited",
864 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000865 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 break;
867 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000868}
869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
871 NativeProcessProtocol *process, lldb::StateType state) {
872 assert(process && "process cannot be NULL");
873 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
874 if (log) {
875 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
876 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
877 __FUNCTION__, process->GetID(), StateAsCString(state));
878 }
879
880 switch (state) {
881 case StateType::eStateRunning:
882 StartSTDIOForwarding();
883 break;
884
885 case StateType::eStateStopped:
886 // Make sure we get all of the pending stdout/stderr from the inferior
887 // and send it to the lldb host before we send the state change
888 // notification
889 SendProcessOutput();
890 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
891 // does not
892 // interfere with our protocol.
893 StopSTDIOForwarding();
894 HandleInferiorState_Stopped(process);
895 break;
896
897 case StateType::eStateExited:
898 // Same as above
899 SendProcessOutput();
900 StopSTDIOForwarding();
901 HandleInferiorState_Exited(process);
902 break;
903
904 default:
905 if (log) {
906 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
907 "change for pid %" PRIu64 ", new state: %s",
908 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 break;
911 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000912
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 // Remember the previous state reported to us.
914 m_inferior_prev_state = state;
915}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000916
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
918 ClearProcessSpecificData();
919}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000920
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
922 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
923
924 if (!m_handshake_completed) {
925 if (!HandshakeWithClient()) {
926 if (log)
927 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
928 "client failed, exiting",
929 __FUNCTION__);
930 m_mainloop.RequestTermination();
931 return;
932 }
933 m_handshake_completed = true;
934 }
935
936 bool interrupt = false;
937 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000938 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000940 const PacketResult result = GetPacketAndSendResponse(
941 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 if (result == PacketResult::ErrorReplyTimeout)
943 break; // No more packets in the queue
944
945 if ((result != PacketResult::Success)) {
946 if (log)
947 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
948 "failed: %s",
949 __FUNCTION__, error.AsCString());
950 m_mainloop.RequestTermination();
951 break;
952 }
953 }
954}
955
Zachary Turner97206d52017-05-12 04:51:55 +0000956Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 std::unique_ptr<Connection> &&connection) {
958 IOObjectSP read_object_sp = connection->GetReadObject();
959 GDBRemoteCommunicationServer::SetConnection(connection.release());
960
Zachary Turner97206d52017-05-12 04:51:55 +0000961 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 m_network_handle_up = m_mainloop.RegisterReadObject(
963 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
964 error);
965 return error;
966}
967
968GDBRemoteCommunication::PacketResult
969GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
970 uint32_t len) {
971 if ((buffer == nullptr) || (len == 0)) {
972 // Nothing to send.
973 return PacketResult::Success;
974 }
975
976 StreamString response;
977 response.PutChar('O');
978 response.PutBytesAsRawHex8(buffer, len);
979
980 return SendPacketNoLock(response.GetString());
981}
982
Zachary Turner97206d52017-05-12 04:51:55 +0000983Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
984 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985
986 // Set up the reading/handling of process I/O
987 std::unique_ptr<ConnectionFileDescriptor> conn_up(
988 new ConnectionFileDescriptor(fd, true));
989 if (!conn_up) {
990 error.SetErrorString("failed to create ConnectionFileDescriptor");
991 return error;
992 }
993
994 m_stdio_communication.SetCloseOnEOF(false);
995 m_stdio_communication.SetConnection(conn_up.release());
996 if (!m_stdio_communication.IsConnected()) {
997 error.SetErrorString(
998 "failed to set connection for inferior I/O communication");
999 return error;
1000 }
1001
Zachary Turner97206d52017-05-12 04:51:55 +00001002 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003}
1004
1005void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1006 // Don't forward if not connected (e.g. when attaching).
1007 if (!m_stdio_communication.IsConnected())
1008 return;
1009
Zachary Turner97206d52017-05-12 04:51:55 +00001010 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 lldbassert(!m_stdio_handle_up);
1012 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1013 m_stdio_communication.GetConnection()->GetReadObject(),
1014 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1015
1016 if (!m_stdio_handle_up) {
1017 // Not much we can do about the failure. Log it and continue without
1018 // forwarding.
1019 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1020 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1021 "forwarding: %s",
1022 __FUNCTION__, error.AsCString());
1023 }
1024}
1025
1026void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1027 m_stdio_handle_up.reset();
1028}
1029
1030void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1031 char buffer[1024];
1032 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001033 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001035 size_t bytes_read = m_stdio_communication.Read(
1036 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 switch (status) {
1038 case eConnectionStatusSuccess:
1039 SendONotification(buffer, bytes_read);
1040 break;
1041 case eConnectionStatusLostConnection:
1042 case eConnectionStatusEndOfFile:
1043 case eConnectionStatusError:
1044 case eConnectionStatusNoConnection:
1045 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1046 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1047 "forwarding as communication returned status %d (error: "
1048 "%s)",
1049 __FUNCTION__, status, error.AsCString());
1050 m_stdio_handle_up.reset();
1051 return;
1052
1053 case eConnectionStatusInterrupted:
1054 case eConnectionStatusTimedOut:
1055 return;
1056 }
1057 }
1058}
1059
1060GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001061GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1062 StringExtractorGDBRemote &packet) {
1063 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1064 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001065 if (!m_debugged_process_up ||
1066 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001067 return SendErrorResponse(68);
1068
1069 if (!packet.ConsumeFront("jTraceStart:"))
1070 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1071
1072 TraceOptions options;
1073 uint64_t type = std::numeric_limits<uint64_t>::max();
1074 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1075 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1076 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1077
1078 auto json_object = StructuredData::ParseJSON(packet.Peek());
1079
1080 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001081 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001082 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1083
1084 auto json_dict = json_object->GetAsDictionary();
1085
Pavel Labath4c950232017-05-26 13:53:39 +00001086 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001087 options.setMetaDataBufferSize(metabuffersize);
1088
Pavel Labath4c950232017-05-26 13:53:39 +00001089 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001090 options.setTraceBufferSize(buffersize);
1091
Pavel Labath4c950232017-05-26 13:53:39 +00001092 json_dict->GetValueForKeyAsInteger("type", type);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001093 options.setType(static_cast<lldb::TraceType>(type));
1094
Pavel Labath4c950232017-05-26 13:53:39 +00001095 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001096 options.setThreadID(tid);
1097
1098 StructuredData::ObjectSP custom_params_sp =
1099 json_dict->GetValueForKey("params");
1100 if (custom_params_sp &&
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001101 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001102 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1103
1104 options.setTraceParams(
1105 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1106
1107 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1108 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1109 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1110 type);
1111 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1112 }
1113
1114 Status error;
1115 lldb::user_id_t uid = LLDB_INVALID_UID;
Pavel Labath82abefa2017-07-18 09:24:48 +00001116 uid = m_debugged_process_up->StartTrace(options, error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001117 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1118 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001119 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001120
1121 StreamGDBRemote response;
1122 response.Printf("%" PRIx64, uid);
1123 return SendPacketNoLock(response.GetString());
1124}
1125
1126GDBRemoteCommunication::PacketResult
1127GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1128 StringExtractorGDBRemote &packet) {
1129 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001130 if (!m_debugged_process_up ||
1131 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001132 return SendErrorResponse(68);
1133
1134 if (!packet.ConsumeFront("jTraceStop:"))
1135 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1136
1137 lldb::user_id_t uid = LLDB_INVALID_UID;
1138 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1139
1140 auto json_object = StructuredData::ParseJSON(packet.Peek());
1141
1142 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001143 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001144 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1145
1146 auto json_dict = json_object->GetAsDictionary();
1147
Pavel Labath4c950232017-05-26 13:53:39 +00001148 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001149 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1150
Pavel Labath4c950232017-05-26 13:53:39 +00001151 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001152
Pavel Labath82abefa2017-07-18 09:24:48 +00001153 Status error = m_debugged_process_up->StopTrace(uid, tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001154
1155 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001156 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001157
1158 return SendOKResponse();
1159}
1160
1161GDBRemoteCommunication::PacketResult
1162GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1163 StringExtractorGDBRemote &packet) {
1164
1165 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001166 if (!m_debugged_process_up ||
1167 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001168 return SendErrorResponse(68);
1169
1170 if (!packet.ConsumeFront("jTraceConfigRead:"))
1171 return SendIllFormedResponse(packet,
1172 "jTraceConfigRead: Ill formed packet ");
1173
1174 lldb::user_id_t uid = LLDB_INVALID_UID;
1175 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1176
1177 auto json_object = StructuredData::ParseJSON(packet.Peek());
1178
1179 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001180 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001181 return SendIllFormedResponse(packet,
1182 "jTraceConfigRead: Ill formed packet ");
1183
1184 auto json_dict = json_object->GetAsDictionary();
1185
Pavel Labath4c950232017-05-26 13:53:39 +00001186 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001187 return SendIllFormedResponse(packet,
1188 "jTraceConfigRead: Ill formed packet ");
1189
Pavel Labath4c950232017-05-26 13:53:39 +00001190 json_dict->GetValueForKeyAsInteger("threadid", threadid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001191
1192 TraceOptions options;
1193 StreamGDBRemote response;
1194
1195 options.setThreadID(threadid);
Pavel Labath82abefa2017-07-18 09:24:48 +00001196 Status error = m_debugged_process_up->GetTraceConfig(uid, options);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001197
1198 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001199 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001200
1201 StreamGDBRemote escaped_response;
1202 StructuredData::Dictionary json_packet;
1203
1204 json_packet.AddIntegerItem("type", options.getType());
1205 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1206 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1207
1208 StructuredData::DictionarySP custom_params = options.getTraceParams();
1209 if (custom_params)
1210 json_packet.AddItem("params", custom_params);
1211
1212 StreamString json_string;
1213 json_packet.Dump(json_string, false);
1214 escaped_response.PutEscapedBytes(json_string.GetData(),
1215 json_string.GetSize());
1216 return SendPacketNoLock(escaped_response.GetString());
1217}
1218
1219GDBRemoteCommunication::PacketResult
1220GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1221 StringExtractorGDBRemote &packet) {
1222
1223 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001224 if (!m_debugged_process_up ||
1225 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001226 return SendErrorResponse(68);
1227
1228 enum PacketType { MetaData, BufferData };
1229 PacketType tracetype = MetaData;
1230
1231 if (packet.ConsumeFront("jTraceBufferRead:"))
1232 tracetype = BufferData;
1233 else if (packet.ConsumeFront("jTraceMetaRead:"))
1234 tracetype = MetaData;
1235 else {
1236 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1237 }
1238
1239 lldb::user_id_t uid = LLDB_INVALID_UID;
1240
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001241 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001242 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001243 uint64_t offset = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001244
1245 auto json_object = StructuredData::ParseJSON(packet.Peek());
1246
1247 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001248 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001249 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1250
1251 auto json_dict = json_object->GetAsDictionary();
1252
Pavel Labath4c950232017-05-26 13:53:39 +00001253 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1254 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1255 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001256 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1257
Pavel Labath4c950232017-05-26 13:53:39 +00001258 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001259
1260 // Allocate the response buffer.
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001261 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1262 if (!buffer)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001263 return SendErrorResponse(0x78);
1264
1265 StreamGDBRemote response;
1266 Status error;
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001267 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001268
1269 if (tracetype == BufferData)
Pavel Labath82abefa2017-07-18 09:24:48 +00001270 error = m_debugged_process_up->GetData(uid, tid, buf, offset);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001271 else if (tracetype == MetaData)
Pavel Labath82abefa2017-07-18 09:24:48 +00001272 error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001273
1274 if (error.Fail())
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001275 return SendErrorResponse(error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001276
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001277 for (auto i : buf)
1278 response.PutHex8(i);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001279
1280 StreamGDBRemote escaped_response;
1281 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1282 return SendPacketNoLock(escaped_response.GetString());
1283}
1284
1285GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1287 StringExtractorGDBRemote &packet) {
1288 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001289 if (!m_debugged_process_up ||
1290 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 return SendErrorResponse(68);
1292
Pavel Labath82abefa2017-07-18 09:24:48 +00001293 lldb::pid_t pid = m_debugged_process_up->GetID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294
1295 if (pid == LLDB_INVALID_PROCESS_ID)
1296 return SendErrorResponse(1);
1297
1298 ProcessInstanceInfo proc_info;
1299 if (!Host::GetProcessInfo(pid, proc_info))
1300 return SendErrorResponse(1);
1301
1302 StreamString response;
1303 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1304 return SendPacketNoLock(response.GetString());
1305}
1306
1307GDBRemoteCommunication::PacketResult
1308GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1309 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001310 if (!m_debugged_process_up ||
1311 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 return SendErrorResponse(68);
1313
1314 // Make sure we set the current thread so g and p packets return
1315 // the data the gdb will expect.
Pavel Labath82abefa2017-07-18 09:24:48 +00001316 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 SetCurrentThreadID(tid);
1318
Pavel Labath82abefa2017-07-18 09:24:48 +00001319 NativeThreadProtocolSP thread_sp = m_debugged_process_up->GetCurrentThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 if (!thread_sp)
1321 return SendErrorResponse(69);
1322
1323 StreamString response;
1324 response.Printf("QC%" PRIx64, thread_sp->GetID());
1325
1326 return SendPacketNoLock(response.GetString());
1327}
1328
1329GDBRemoteCommunication::PacketResult
1330GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1331 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1332
1333 StopSTDIOForwarding();
1334
Pavel Labath82abefa2017-07-18 09:24:48 +00001335 if (!m_debugged_process_up) {
1336 LLDB_LOG(log, "No debugged process found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 return PacketResult::Success;
1338 }
1339
Pavel Labath82abefa2017-07-18 09:24:48 +00001340 Status error = m_debugged_process_up->Kill();
1341 if (error.Fail())
1342 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1343 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344
1345 // No OK response for kill packet.
1346 // return SendOKResponse ();
1347 return PacketResult::Success;
1348}
1349
1350GDBRemoteCommunication::PacketResult
1351GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1352 StringExtractorGDBRemote &packet) {
1353 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1354 if (packet.GetU32(0))
1355 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1356 else
1357 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1358 return SendOKResponse();
1359}
1360
1361GDBRemoteCommunication::PacketResult
1362GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1363 StringExtractorGDBRemote &packet) {
1364 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1365 std::string path;
1366 packet.GetHexByteString(path);
1367 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1368 return SendOKResponse();
1369}
1370
1371GDBRemoteCommunication::PacketResult
1372GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1373 StringExtractorGDBRemote &packet) {
1374 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1375 if (working_dir) {
1376 StreamString response;
1377 response.PutCStringAsRawHex8(working_dir.GetCString());
1378 return SendPacketNoLock(response.GetString());
1379 }
1380
1381 return SendErrorResponse(14);
1382}
1383
1384GDBRemoteCommunication::PacketResult
1385GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1386 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1387 if (log)
1388 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1389
1390 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001391 if (!m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392 if (log)
1393 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1394 "shared pointer",
1395 __FUNCTION__);
1396 return SendErrorResponse(0x36);
1397 }
1398
1399 // Pull out the signal number.
1400 packet.SetFilePos(::strlen("C"));
1401 if (packet.GetBytesLeft() < 1) {
1402 // Shouldn't be using a C without a signal.
1403 return SendIllFormedResponse(packet, "C packet specified without signal.");
1404 }
1405 const uint32_t signo =
1406 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1407 if (signo == std::numeric_limits<uint32_t>::max())
1408 return SendIllFormedResponse(packet, "failed to parse signal number");
1409
1410 // Handle optional continue address.
1411 if (packet.GetBytesLeft() > 0) {
1412 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1413 if (*packet.Peek() == ';')
1414 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1415 else
1416 return SendIllFormedResponse(
1417 packet, "unexpected content after $C{signal-number}");
1418 }
1419
1420 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001421 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422
1423 // We have two branches: what to do if a continue thread is specified (in
1424 // which case we target
1425 // sending the signal to that thread), or when we don't have a continue thread
1426 // set (in which
1427 // case we send a signal to the process).
1428
1429 // TODO discuss with Greg Clayton, make sure this makes sense.
1430
1431 lldb::tid_t signal_tid = GetContinueThreadID();
1432 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1433 // The resume action for the continue thread (or all threads if a continue
1434 // thread is not set).
1435 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1436 static_cast<int>(signo)};
1437
1438 // Add the action for the continue thread (or all threads when the continue
1439 // thread isn't present).
1440 resume_actions.Append(action);
1441 } else {
1442 // Send the signal to the process since we weren't targeting a specific
1443 // continue thread with the signal.
Pavel Labath82abefa2017-07-18 09:24:48 +00001444 error = m_debugged_process_up->Signal(signo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001446 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1447 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448
1449 return SendErrorResponse(0x52);
1450 }
1451 }
1452
1453 // Resume the threads.
Pavel Labath82abefa2017-07-18 09:24:48 +00001454 error = m_debugged_process_up->Resume(resume_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001456 LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1457 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458
1459 return SendErrorResponse(0x38);
1460 }
1461
1462 // Don't send an "OK" packet; response is the stopped/exited message.
1463 return PacketResult::Success;
1464}
1465
1466GDBRemoteCommunication::PacketResult
1467GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1468 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1469 if (log)
1470 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1471
1472 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1473
1474 // For now just support all continue.
1475 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1476 if (has_continue_address) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001477 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1478 packet.Peek());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1480 }
1481
1482 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001483 if (!m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 if (log)
1485 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1486 "shared pointer",
1487 __FUNCTION__);
1488 return SendErrorResponse(0x36);
1489 }
1490
1491 // Build the ResumeActionList
1492 ResumeActionList actions(StateType::eStateRunning, 0);
1493
Pavel Labath82abefa2017-07-18 09:24:48 +00001494 Status error = m_debugged_process_up->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001496 LLDB_LOG(log, "c failed for process {0}: {1}",
1497 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001498 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1499 }
1500
Pavel Labath82abefa2017-07-18 09:24:48 +00001501 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001502 // No response required from continue.
1503 return PacketResult::Success;
1504}
1505
1506GDBRemoteCommunication::PacketResult
1507GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1508 StringExtractorGDBRemote &packet) {
1509 StreamString response;
1510 response.Printf("vCont;c;C;s;S");
1511
1512 return SendPacketNoLock(response.GetString());
1513}
1514
1515GDBRemoteCommunication::PacketResult
1516GDBRemoteCommunicationServerLLGS::Handle_vCont(
1517 StringExtractorGDBRemote &packet) {
1518 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1519 if (log)
1520 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1521 __FUNCTION__);
1522
1523 packet.SetFilePos(::strlen("vCont"));
1524
1525 if (packet.GetBytesLeft() == 0) {
1526 if (log)
1527 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1528 "vCont package",
1529 __FUNCTION__);
1530 return SendIllFormedResponse(packet, "Missing action from vCont package");
1531 }
1532
1533 // Check if this is all continue (no options or ";c").
1534 if (::strcmp(packet.Peek(), ";c") == 0) {
1535 // Move past the ';', then do a simple 'c'.
1536 packet.SetFilePos(packet.GetFilePos() + 1);
1537 return Handle_c(packet);
1538 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1539 // Move past the ';', then do a simple 's'.
1540 packet.SetFilePos(packet.GetFilePos() + 1);
1541 return Handle_s(packet);
1542 }
1543
1544 // Ensure we have a native process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001545 if (!m_debugged_process_up) {
1546 LLDB_LOG(log, "no debugged process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 return SendErrorResponse(0x36);
1548 }
1549
1550 ResumeActionList thread_actions;
1551
1552 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1553 // Skip the semi-colon.
1554 packet.GetChar();
1555
1556 // Build up the thread action.
1557 ResumeAction thread_action;
1558 thread_action.tid = LLDB_INVALID_THREAD_ID;
1559 thread_action.state = eStateInvalid;
1560 thread_action.signal = 0;
1561
1562 const char action = packet.GetChar();
1563 switch (action) {
1564 case 'C':
1565 thread_action.signal = packet.GetHexMaxU32(false, 0);
1566 if (thread_action.signal == 0)
1567 return SendIllFormedResponse(
1568 packet, "Could not parse signal in vCont packet C action");
1569 LLVM_FALLTHROUGH;
1570
1571 case 'c':
1572 // Continue
1573 thread_action.state = eStateRunning;
1574 break;
1575
1576 case 'S':
1577 thread_action.signal = packet.GetHexMaxU32(false, 0);
1578 if (thread_action.signal == 0)
1579 return SendIllFormedResponse(
1580 packet, "Could not parse signal in vCont packet S action");
1581 LLVM_FALLTHROUGH;
1582
1583 case 's':
1584 // Step
1585 thread_action.state = eStateStepping;
1586 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001587
Tamas Berghammere13c2732015-02-11 10:29:30 +00001588 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 return SendIllFormedResponse(packet, "Unsupported vCont action");
1590 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001591 }
1592
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 // Parse out optional :{thread-id} value.
1594 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1595 // Consume the separator.
1596 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1599 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1600 return SendIllFormedResponse(
1601 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001602 }
1603
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 thread_actions.Append(thread_action);
1605 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001606
Pavel Labath82abefa2017-07-18 09:24:48 +00001607 Status error = m_debugged_process_up->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001609 LLDB_LOG(log, "vCont failed for process {0}: {1}",
1610 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1612 }
1613
Pavel Labath82abefa2017-07-18 09:24:48 +00001614 LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001615 // No response required from vCont.
1616 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001617}
1618
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1620 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath82abefa2017-07-18 09:24:48 +00001621 LLDB_LOG(log, "setting current thread id to {0}", tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001622
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 m_current_tid = tid;
Pavel Labath82abefa2017-07-18 09:24:48 +00001624 if (m_debugged_process_up)
1625 m_debugged_process_up->SetCurrentThreadID(m_current_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001626}
1627
1628void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1629 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath82abefa2017-07-18 09:24:48 +00001630 LLDB_LOG(log, "setting continue thread id to {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631
1632 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001633}
1634
Tamas Berghammere13c2732015-02-11 10:29:30 +00001635GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1637 StringExtractorGDBRemote &packet) {
1638 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001639
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 // If no process, indicate error
Pavel Labath82abefa2017-07-18 09:24:48 +00001641 if (!m_debugged_process_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001643
Pavel Labath82abefa2017-07-18 09:24:48 +00001644 return SendStopReasonForState(m_debugged_process_up->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001645}
1646
1647GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1649 lldb::StateType process_state) {
1650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001651
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 switch (process_state) {
1653 case eStateAttaching:
1654 case eStateLaunching:
1655 case eStateRunning:
1656 case eStateStepping:
1657 case eStateDetached:
1658 // NOTE: gdb protocol doc looks like it should return $OK
1659 // when everything is running (i.e. no stopped result).
1660 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 case eStateSuspended:
1663 case eStateStopped:
1664 case eStateCrashed: {
Pavel Labath82abefa2017-07-18 09:24:48 +00001665 lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001666 // Make sure we set the current thread so g and p packets return
1667 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668 SetCurrentThreadID(tid);
1669 return SendStopReplyPacketForThread(tid);
1670 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001671
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 case eStateInvalid:
1673 case eStateUnloaded:
1674 case eStateExited:
Pavel Labath82abefa2017-07-18 09:24:48 +00001675 return SendWResponse(m_debugged_process_up.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001676
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 default:
Pavel Labath82abefa2017-07-18 09:24:48 +00001678 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1679 m_debugged_process_up->GetID(), process_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 break;
1681 }
Pavel Labath424b2012015-07-28 09:06:56 +00001682
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001684}
1685
1686GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1688 StringExtractorGDBRemote &packet) {
1689 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001690 if (!m_debugged_process_up ||
1691 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 // Ensure we have a thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00001695 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadAtIndex(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 if (!thread_sp)
1697 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001698
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 // Get the register context for the first thread.
1700 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1701 if (!reg_context_sp)
1702 return SendErrorResponse(69);
1703
1704 // Parse out the register number from the request.
1705 packet.SetFilePos(strlen("qRegisterInfo"));
1706 const uint32_t reg_index =
1707 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1708 if (reg_index == std::numeric_limits<uint32_t>::max())
1709 return SendErrorResponse(69);
1710
1711 // Return the end of registers response if we've iterated one past the end of
1712 // the register set.
1713 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1714 return SendErrorResponse(69);
1715
1716 const RegisterInfo *reg_info =
1717 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1718 if (!reg_info)
1719 return SendErrorResponse(69);
1720
1721 // Build the reginfos response.
1722 StreamGDBRemote response;
1723
1724 response.PutCString("name:");
1725 response.PutCString(reg_info->name);
1726 response.PutChar(';');
1727
1728 if (reg_info->alt_name && reg_info->alt_name[0]) {
1729 response.PutCString("alt-name:");
1730 response.PutCString(reg_info->alt_name);
1731 response.PutChar(';');
1732 }
1733
1734 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1735 reg_info->byte_size * 8, reg_info->byte_offset);
1736
1737 switch (reg_info->encoding) {
1738 case eEncodingUint:
1739 response.PutCString("encoding:uint;");
1740 break;
1741 case eEncodingSint:
1742 response.PutCString("encoding:sint;");
1743 break;
1744 case eEncodingIEEE754:
1745 response.PutCString("encoding:ieee754;");
1746 break;
1747 case eEncodingVector:
1748 response.PutCString("encoding:vector;");
1749 break;
1750 default:
1751 break;
1752 }
1753
1754 switch (reg_info->format) {
1755 case eFormatBinary:
1756 response.PutCString("format:binary;");
1757 break;
1758 case eFormatDecimal:
1759 response.PutCString("format:decimal;");
1760 break;
1761 case eFormatHex:
1762 response.PutCString("format:hex;");
1763 break;
1764 case eFormatFloat:
1765 response.PutCString("format:float;");
1766 break;
1767 case eFormatVectorOfSInt8:
1768 response.PutCString("format:vector-sint8;");
1769 break;
1770 case eFormatVectorOfUInt8:
1771 response.PutCString("format:vector-uint8;");
1772 break;
1773 case eFormatVectorOfSInt16:
1774 response.PutCString("format:vector-sint16;");
1775 break;
1776 case eFormatVectorOfUInt16:
1777 response.PutCString("format:vector-uint16;");
1778 break;
1779 case eFormatVectorOfSInt32:
1780 response.PutCString("format:vector-sint32;");
1781 break;
1782 case eFormatVectorOfUInt32:
1783 response.PutCString("format:vector-uint32;");
1784 break;
1785 case eFormatVectorOfFloat32:
1786 response.PutCString("format:vector-float32;");
1787 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001788 case eFormatVectorOfUInt64:
1789 response.PutCString("format:vector-uint64;");
1790 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001791 case eFormatVectorOfUInt128:
1792 response.PutCString("format:vector-uint128;");
1793 break;
1794 default:
1795 break;
1796 };
1797
1798 const char *const register_set_name =
1799 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1800 if (register_set_name) {
1801 response.PutCString("set:");
1802 response.PutCString(register_set_name);
1803 response.PutChar(';');
1804 }
1805
1806 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1807 LLDB_INVALID_REGNUM)
1808 response.Printf("ehframe:%" PRIu32 ";",
1809 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1810
1811 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1812 response.Printf("dwarf:%" PRIu32 ";",
1813 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1814
1815 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1816 case LLDB_REGNUM_GENERIC_PC:
1817 response.PutCString("generic:pc;");
1818 break;
1819 case LLDB_REGNUM_GENERIC_SP:
1820 response.PutCString("generic:sp;");
1821 break;
1822 case LLDB_REGNUM_GENERIC_FP:
1823 response.PutCString("generic:fp;");
1824 break;
1825 case LLDB_REGNUM_GENERIC_RA:
1826 response.PutCString("generic:ra;");
1827 break;
1828 case LLDB_REGNUM_GENERIC_FLAGS:
1829 response.PutCString("generic:flags;");
1830 break;
1831 case LLDB_REGNUM_GENERIC_ARG1:
1832 response.PutCString("generic:arg1;");
1833 break;
1834 case LLDB_REGNUM_GENERIC_ARG2:
1835 response.PutCString("generic:arg2;");
1836 break;
1837 case LLDB_REGNUM_GENERIC_ARG3:
1838 response.PutCString("generic:arg3;");
1839 break;
1840 case LLDB_REGNUM_GENERIC_ARG4:
1841 response.PutCString("generic:arg4;");
1842 break;
1843 case LLDB_REGNUM_GENERIC_ARG5:
1844 response.PutCString("generic:arg5;");
1845 break;
1846 case LLDB_REGNUM_GENERIC_ARG6:
1847 response.PutCString("generic:arg6;");
1848 break;
1849 case LLDB_REGNUM_GENERIC_ARG7:
1850 response.PutCString("generic:arg7;");
1851 break;
1852 case LLDB_REGNUM_GENERIC_ARG8:
1853 response.PutCString("generic:arg8;");
1854 break;
1855 default:
1856 break;
1857 }
1858
1859 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1860 response.PutCString("container-regs:");
1861 int i = 0;
1862 for (const uint32_t *reg_num = reg_info->value_regs;
1863 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1864 if (i > 0)
1865 response.PutChar(',');
1866 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 response.PutChar(';');
1869 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001870
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1872 response.PutCString("invalidate-regs:");
1873 int i = 0;
1874 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1875 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1876 if (i > 0)
1877 response.PutChar(',');
1878 response.Printf("%" PRIx32, *reg_num);
1879 }
1880 response.PutChar(';');
1881 }
1882
1883 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1884 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1885 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1886 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1887 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1888 response.PutChar(';');
1889 }
1890 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001891}
1892
1893GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1895 StringExtractorGDBRemote &packet) {
1896 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1897
1898 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00001899 if (!m_debugged_process_up ||
1900 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1901 LLDB_LOG(log, "no process ({0}), returning OK",
1902 m_debugged_process_up ? "invalid process id"
1903 : "null m_debugged_process_up");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 return SendOKResponse();
1905 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001906
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 StreamGDBRemote response;
1908 response.PutChar('m');
1909
Pavel Labath82abefa2017-07-18 09:24:48 +00001910 LLDB_LOG(log, "starting thread iteration");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 NativeThreadProtocolSP thread_sp;
1912 uint32_t thread_index;
1913 for (thread_index = 0,
Pavel Labath82abefa2017-07-18 09:24:48 +00001914 thread_sp = m_debugged_process_up->GetThreadAtIndex(thread_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915 thread_sp; ++thread_index,
Pavel Labath82abefa2017-07-18 09:24:48 +00001916 thread_sp = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1917 LLDB_LOG(log, "iterated thread {0}({1}, tid={2})", thread_index,
1918 thread_sp ? "is not null" : "null",
1919 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920 if (thread_index > 0)
1921 response.PutChar(',');
1922 response.Printf("%" PRIx64, thread_sp->GetID());
1923 }
1924
Pavel Labath82abefa2017-07-18 09:24:48 +00001925 LLDB_LOG(log, "finished thread iteration");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 return SendPacketNoLock(response.GetString());
1927}
1928
1929GDBRemoteCommunication::PacketResult
1930GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1931 StringExtractorGDBRemote &packet) {
1932 // FIXME for now we return the full thread list in the initial packet and
1933 // always do nothing here.
1934 return SendPacketNoLock("l");
1935}
1936
1937GDBRemoteCommunication::PacketResult
1938GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1939 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1940
1941 // Parse out the register number from the request.
1942 packet.SetFilePos(strlen("p"));
1943 const uint32_t reg_index =
1944 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1945 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1946 if (log)
1947 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1948 "parse register number from request \"%s\"",
1949 __FUNCTION__, packet.GetStringRef().c_str());
1950 return SendErrorResponse(0x15);
1951 }
1952
1953 // Get the thread to use.
1954 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1955 if (!thread_sp) {
1956 if (log)
1957 log->Printf(
1958 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
1959 __FUNCTION__);
1960 return SendErrorResponse(0x15);
1961 }
1962
1963 // Get the thread's register context.
1964 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1965 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00001966 LLDB_LOG(
1967 log,
1968 "pid {0} tid {1} failed, no register context available for the thread",
1969 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 return SendErrorResponse(0x15);
1971 }
1972
1973 // Return the end of registers response if we've iterated one past the end of
1974 // the register set.
1975 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1976 if (log)
1977 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1978 "register %" PRIu32 " beyond register count %" PRIu32,
1979 __FUNCTION__, reg_index,
1980 reg_context_sp->GetUserRegisterCount());
1981 return SendErrorResponse(0x15);
1982 }
1983
1984 const RegisterInfo *reg_info =
1985 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1986 if (!reg_info) {
1987 if (log)
1988 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1989 "register %" PRIu32 " returned NULL",
1990 __FUNCTION__, reg_index);
1991 return SendErrorResponse(0x15);
1992 }
1993
1994 // Build the reginfos response.
1995 StreamGDBRemote response;
1996
1997 // Retrieve the value
1998 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00001999 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 if (error.Fail()) {
2001 if (log)
2002 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2003 "requested register %" PRIu32 " (%s) failed: %s",
2004 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2005 return SendErrorResponse(0x15);
2006 }
2007
2008 const uint8_t *const data =
2009 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2010 if (!data) {
2011 if (log)
2012 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2013 "bytes from requested register %" PRIu32,
2014 __FUNCTION__, reg_index);
2015 return SendErrorResponse(0x15);
2016 }
2017
2018 // FIXME flip as needed to get data in big/little endian format for this host.
2019 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2020 response.PutHex8(data[i]);
2021
2022 return SendPacketNoLock(response.GetString());
2023}
2024
2025GDBRemoteCommunication::PacketResult
2026GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2027 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2028
2029 // Ensure there is more content.
2030 if (packet.GetBytesLeft() < 1)
2031 return SendIllFormedResponse(packet, "Empty P packet");
2032
2033 // Parse out the register number from the request.
2034 packet.SetFilePos(strlen("P"));
2035 const uint32_t reg_index =
2036 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2037 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2038 if (log)
2039 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2040 "parse register number from request \"%s\"",
2041 __FUNCTION__, packet.GetStringRef().c_str());
2042 return SendErrorResponse(0x29);
2043 }
2044
2045 // Note debugserver would send an E30 here.
2046 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2047 return SendIllFormedResponse(
2048 packet, "P packet missing '=' char after register number");
2049
2050 // Get process architecture.
2051 ArchSpec process_arch;
Pavel Labath82abefa2017-07-18 09:24:48 +00002052 if (!m_debugged_process_up ||
2053 !m_debugged_process_up->GetArchitecture(process_arch)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 if (log)
2055 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2056 "inferior architecture",
2057 __FUNCTION__);
2058 return SendErrorResponse(0x49);
2059 }
2060
2061 // Parse out the value.
2062 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2063 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2064
2065 // Get the thread to use.
2066 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2067 if (!thread_sp) {
2068 if (log)
2069 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2070 "available (thread index 0)",
2071 __FUNCTION__);
2072 return SendErrorResponse(0x28);
2073 }
2074
2075 // Get the thread's register context.
2076 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2077 if (!reg_context_sp) {
2078 if (log)
2079 log->Printf(
2080 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2081 " failed, no register context available for the thread",
Pavel Labath82abefa2017-07-18 09:24:48 +00002082 __FUNCTION__, m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002083 return SendErrorResponse(0x15);
2084 }
2085
2086 const RegisterInfo *reg_info =
2087 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2088 if (!reg_info) {
2089 if (log)
2090 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2091 "register %" PRIu32 " returned NULL",
2092 __FUNCTION__, reg_index);
2093 return SendErrorResponse(0x48);
2094 }
2095
2096 // Return the end of registers response if we've iterated one past the end of
2097 // the register set.
2098 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2099 if (log)
2100 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2101 "register %" PRIu32 " beyond register count %" PRIu32,
2102 __FUNCTION__, reg_index,
2103 reg_context_sp->GetUserRegisterCount());
2104 return SendErrorResponse(0x47);
2105 }
2106
2107 // The dwarf expression are evaluate on host site
2108 // which may cause register size to change
2109 // Hence the reg_size may not be same as reg_info->bytes_size
2110 if ((reg_size != reg_info->byte_size) &&
2111 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2112 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2113 }
2114
2115 // Build the reginfos response.
2116 StreamGDBRemote response;
2117
2118 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002119 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 if (error.Fail()) {
2121 if (log)
2122 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2123 "requested register %" PRIu32 " (%s) failed: %s",
2124 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2125 return SendErrorResponse(0x32);
2126 }
2127
2128 return SendOKResponse();
2129}
2130
2131GDBRemoteCommunication::PacketResult
2132GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2133 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2134
2135 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002136 if (!m_debugged_process_up ||
2137 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138 if (log)
2139 log->Printf(
2140 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2141 __FUNCTION__);
2142 return SendErrorResponse(0x15);
2143 }
2144
2145 // Parse out which variant of $H is requested.
2146 packet.SetFilePos(strlen("H"));
2147 if (packet.GetBytesLeft() < 1) {
2148 if (log)
2149 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2150 "missing {g,c} variant",
2151 __FUNCTION__);
2152 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2153 }
2154
2155 const char h_variant = packet.GetChar();
2156 switch (h_variant) {
2157 case 'g':
2158 break;
2159
2160 case 'c':
2161 break;
2162
2163 default:
2164 if (log)
2165 log->Printf(
2166 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2167 __FUNCTION__, h_variant);
2168 return SendIllFormedResponse(packet,
2169 "H variant unsupported, should be c or g");
2170 }
2171
2172 // Parse out the thread number.
2173 // FIXME return a parse success/fail value. All values are valid here.
2174 const lldb::tid_t tid =
2175 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2176
2177 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2178 // (any thread).
2179 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002180 NativeThreadProtocolSP thread_sp(m_debugged_process_up->GetThreadByID(tid));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 if (!thread_sp) {
2182 if (log)
2183 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2184 " not found",
2185 __FUNCTION__, tid);
2186 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002187 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002189
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190 // Now switch the given thread type.
2191 switch (h_variant) {
2192 case 'g':
2193 SetCurrentThreadID(tid);
2194 break;
2195
2196 case 'c':
2197 SetContinueThreadID(tid);
2198 break;
2199
2200 default:
2201 assert(false && "unsupported $H variant - shouldn't get here");
2202 return SendIllFormedResponse(packet,
2203 "H variant unsupported, should be c or g");
2204 }
2205
2206 return SendOKResponse();
2207}
2208
2209GDBRemoteCommunication::PacketResult
2210GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2211 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2212
2213 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002214 if (!m_debugged_process_up ||
2215 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 if (log)
2217 log->Printf(
2218 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2219 __FUNCTION__);
2220 return SendErrorResponse(0x15);
2221 }
2222
2223 packet.SetFilePos(::strlen("I"));
2224 uint8_t tmp[4096];
2225 for (;;) {
2226 size_t read = packet.GetHexBytesAvail(tmp);
2227 if (read == 0) {
2228 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230 // write directly to stdin *this might block if stdin buffer is full*
2231 // TODO: enqueue this block in circular buffer and send window size to
2232 // remote host
2233 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002234 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 m_stdio_communication.Write(tmp, read, status, &error);
2236 if (error.Fail()) {
2237 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002238 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002240
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002242}
2243
2244GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002245GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2246 StringExtractorGDBRemote &packet) {
2247 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2248
2249 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002250 if (!m_debugged_process_up ||
2251 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2252 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253 return SendErrorResponse(0x15);
2254 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002255
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 // Interrupt the process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002257 Status error = m_debugged_process_up->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002259 LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2260 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2262 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002263
Pavel Labath82abefa2017-07-18 09:24:48 +00002264 LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002265
Kate Stoneb9c1b512016-09-06 20:57:50 +00002266 // No response required from stop all.
2267 return PacketResult::Success;
2268}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002269
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270GDBRemoteCommunication::PacketResult
2271GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2272 StringExtractorGDBRemote &packet) {
2273 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002274
Pavel Labath82abefa2017-07-18 09:24:48 +00002275 if (!m_debugged_process_up ||
2276 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002277 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 log->Printf(
2279 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2280 __FUNCTION__);
2281 return SendErrorResponse(0x15);
2282 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002283
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284 // Parse out the memory address.
2285 packet.SetFilePos(strlen("m"));
2286 if (packet.GetBytesLeft() < 1)
2287 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002288
Kate Stoneb9c1b512016-09-06 20:57:50 +00002289 // Read the address. Punting on validation.
2290 // FIXME replace with Hex U64 read with no default value that fails on failed
2291 // read.
2292 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 // Validate comma.
2295 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2296 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 // Get # bytes to read.
2299 if (packet.GetBytesLeft() < 1)
2300 return SendIllFormedResponse(packet, "Length missing in m packet");
2301
2302 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2303 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002304 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2306 "zero-length packet",
2307 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002308 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002310
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311 // Allocate the response buffer.
2312 std::string buf(byte_count, '\0');
2313 if (buf.empty())
2314 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002315
Kate Stoneb9c1b512016-09-06 20:57:50 +00002316 // Retrieve the process memory.
2317 size_t bytes_read = 0;
Pavel Labath82abefa2017-07-18 09:24:48 +00002318 Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319 read_addr, &buf[0], byte_count, bytes_read);
2320 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002321 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2323 " mem 0x%" PRIx64 ": failed to read. Error: %s",
Pavel Labath82abefa2017-07-18 09:24:48 +00002324 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002325 error.AsCString());
2326 return SendErrorResponse(0x08);
2327 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002328
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 if (bytes_read == 0) {
2330 if (log)
2331 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2332 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
Pavel Labath82abefa2017-07-18 09:24:48 +00002333 __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 byte_count);
2335 return SendErrorResponse(0x08);
2336 }
2337
2338 StreamGDBRemote response;
2339 packet.SetFilePos(0);
2340 char kind = packet.GetChar('?');
2341 if (kind == 'x')
2342 response.PutEscapedBytes(buf.data(), byte_count);
2343 else {
2344 assert(kind == 'm');
2345 for (size_t i = 0; i < bytes_read; ++i)
2346 response.PutHex8(buf[i]);
2347 }
2348
2349 return SendPacketNoLock(response.GetString());
2350}
2351
2352GDBRemoteCommunication::PacketResult
2353GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2354 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2355
Pavel Labath82abefa2017-07-18 09:24:48 +00002356 if (!m_debugged_process_up ||
2357 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 if (log)
2359 log->Printf(
2360 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2361 __FUNCTION__);
2362 return SendErrorResponse(0x15);
2363 }
2364
2365 // Parse out the memory address.
2366 packet.SetFilePos(strlen("M"));
2367 if (packet.GetBytesLeft() < 1)
2368 return SendIllFormedResponse(packet, "Too short M packet");
2369
2370 // Read the address. Punting on validation.
2371 // FIXME replace with Hex U64 read with no default value that fails on failed
2372 // read.
2373 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2374
2375 // Validate comma.
2376 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2377 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2378
2379 // Get # bytes to read.
2380 if (packet.GetBytesLeft() < 1)
2381 return SendIllFormedResponse(packet, "Length missing in M packet");
2382
2383 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2384 if (byte_count == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002385 LLDB_LOG(log, "nothing to write: zero-length packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002386 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 }
2388
2389 // Validate colon.
2390 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2391 return SendIllFormedResponse(
2392 packet, "Comma sep missing in M packet after byte length");
2393
2394 // Allocate the conversion buffer.
2395 std::vector<uint8_t> buf(byte_count, 0);
2396 if (buf.empty())
2397 return SendErrorResponse(0x78);
2398
2399 // Convert the hex memory write contents to bytes.
2400 StreamGDBRemote response;
2401 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2402 if (convert_count != byte_count) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002403 LLDB_LOG(log,
2404 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2405 "to convert.",
2406 m_debugged_process_up->GetID(), write_addr, byte_count,
2407 convert_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 return SendIllFormedResponse(packet, "M content byte length specified did "
2409 "not match hex-encoded content "
2410 "length");
2411 }
2412
2413 // Write the process memory.
2414 size_t bytes_written = 0;
Pavel Labath82abefa2017-07-18 09:24:48 +00002415 Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
Zachary Turner97206d52017-05-12 04:51:55 +00002416 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002418 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2419 m_debugged_process_up->GetID(), write_addr, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002420 return SendErrorResponse(0x09);
2421 }
2422
2423 if (bytes_written == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002424 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2425 m_debugged_process_up->GetID(), write_addr, byte_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426 return SendErrorResponse(0x09);
2427 }
2428
2429 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002430}
2431
2432GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002433GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2434 StringExtractorGDBRemote &packet) {
2435 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002436
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 // Currently only the NativeProcessProtocol knows if it can handle a
2438 // qMemoryRegionInfoSupported
2439 // request, but we're not guaranteed to be attached to a process. For now
2440 // we'll assume the
2441 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002442
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 // Ensure we have a process running; otherwise, we can't figure this out
2444 // since we won't have a NativeProcessProtocol.
Pavel Labath82abefa2017-07-18 09:24:48 +00002445 if (!m_debugged_process_up ||
2446 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 if (log)
2448 log->Printf(
2449 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2450 __FUNCTION__);
2451 return SendErrorResponse(0x15);
2452 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002453
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454 // Test if we can get any region back when asking for the region around NULL.
2455 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002456 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002457 m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 if (error.Fail()) {
2459 // We don't support memory region info collection for this
2460 // NativeProcessProtocol.
2461 return SendUnimplementedResponse("");
2462 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002463
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002465}
2466
2467GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2469 StringExtractorGDBRemote &packet) {
2470 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002471
Kate Stoneb9c1b512016-09-06 20:57:50 +00002472 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002473 if (!m_debugged_process_up ||
2474 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002475 if (log)
2476 log->Printf(
2477 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2478 __FUNCTION__);
2479 return SendErrorResponse(0x15);
2480 }
2481
2482 // Parse out the memory address.
2483 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2484 if (packet.GetBytesLeft() < 1)
2485 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2486
2487 // Read the address. Punting on validation.
2488 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2489
2490 StreamGDBRemote response;
2491
2492 // Get the memory region info for the target address.
2493 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002494 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002495 m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496 if (error.Fail()) {
2497 // Return the error message.
2498
2499 response.PutCString("error:");
2500 response.PutCStringAsRawHex8(error.AsCString());
2501 response.PutChar(';');
2502 } else {
2503 // Range start and size.
2504 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2505 region_info.GetRange().GetRangeBase(),
2506 region_info.GetRange().GetByteSize());
2507
2508 // Permissions.
2509 if (region_info.GetReadable() || region_info.GetWritable() ||
2510 region_info.GetExecutable()) {
2511 // Write permissions info.
2512 response.PutCString("permissions:");
2513
2514 if (region_info.GetReadable())
2515 response.PutChar('r');
2516 if (region_info.GetWritable())
2517 response.PutChar('w');
2518 if (region_info.GetExecutable())
2519 response.PutChar('x');
2520
2521 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002522 }
2523
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 // Name
2525 ConstString name = region_info.GetName();
2526 if (name) {
2527 response.PutCString("name:");
2528 response.PutCStringAsRawHex8(name.AsCString());
2529 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002530 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002532
Kate Stoneb9c1b512016-09-06 20:57:50 +00002533 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002534}
2535
2536GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2538 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002539 if (!m_debugged_process_up ||
2540 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002541 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002542 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 return SendErrorResponse(0x15);
2544 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002545
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 // Parse out software or hardware breakpoint or watchpoint requested.
2547 packet.SetFilePos(strlen("Z"));
2548 if (packet.GetBytesLeft() < 1)
2549 return SendIllFormedResponse(
2550 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002551
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 bool want_breakpoint = true;
2553 bool want_hardware = false;
2554 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002555
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 const GDBStoppointType stoppoint_type =
2557 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2558 switch (stoppoint_type) {
2559 case eBreakpointSoftware:
2560 want_hardware = false;
2561 want_breakpoint = true;
2562 break;
2563 case eBreakpointHardware:
2564 want_hardware = true;
2565 want_breakpoint = true;
2566 break;
2567 case eWatchpointWrite:
2568 watch_flags = 1;
2569 want_hardware = true;
2570 want_breakpoint = false;
2571 break;
2572 case eWatchpointRead:
2573 watch_flags = 2;
2574 want_hardware = true;
2575 want_breakpoint = false;
2576 break;
2577 case eWatchpointReadWrite:
2578 watch_flags = 3;
2579 want_hardware = true;
2580 want_breakpoint = false;
2581 break;
2582 case eStoppointInvalid:
2583 return SendIllFormedResponse(
2584 packet, "Z packet had invalid software/hardware specifier");
2585 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002586
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2588 return SendIllFormedResponse(
2589 packet, "Malformed Z packet, expecting comma after stoppoint type");
2590
2591 // Parse out the stoppoint address.
2592 if (packet.GetBytesLeft() < 1)
2593 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2594 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2595
2596 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2597 return SendIllFormedResponse(
2598 packet, "Malformed Z packet, expecting comma after address");
2599
2600 // Parse out the stoppoint size (i.e. size hint for opcode size).
2601 const uint32_t size =
2602 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2603 if (size == std::numeric_limits<uint32_t>::max())
2604 return SendIllFormedResponse(
2605 packet, "Malformed Z packet, failed to parse size argument");
2606
2607 if (want_breakpoint) {
2608 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002609 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002610 m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002611 if (error.Success())
2612 return SendOKResponse();
2613 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002614 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2615 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616 return SendErrorResponse(0x09);
2617 } else {
2618 // Try to set the watchpoint.
Pavel Labath82abefa2017-07-18 09:24:48 +00002619 const Status error = m_debugged_process_up->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 addr, size, watch_flags, want_hardware);
2621 if (error.Success())
2622 return SendOKResponse();
2623 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002624 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2625 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 return SendErrorResponse(0x09);
2627 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002628}
2629
2630GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2632 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002633 if (!m_debugged_process_up ||
2634 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002636 LLDB_LOG(log, "failed, no process available");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 return SendErrorResponse(0x15);
2638 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002639
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640 // Parse out software or hardware breakpoint or watchpoint requested.
2641 packet.SetFilePos(strlen("z"));
2642 if (packet.GetBytesLeft() < 1)
2643 return SendIllFormedResponse(
2644 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002645
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002647 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002648
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649 const GDBStoppointType stoppoint_type =
2650 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2651 switch (stoppoint_type) {
2652 case eBreakpointHardware:
2653 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002654 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 break;
2656 case eBreakpointSoftware:
2657 want_breakpoint = true;
2658 break;
2659 case eWatchpointWrite:
2660 want_breakpoint = false;
2661 break;
2662 case eWatchpointRead:
2663 want_breakpoint = false;
2664 break;
2665 case eWatchpointReadWrite:
2666 want_breakpoint = false;
2667 break;
2668 default:
2669 return SendIllFormedResponse(
2670 packet, "z packet had invalid software/hardware specifier");
2671 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002672
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2674 return SendIllFormedResponse(
2675 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002676
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 // Parse out the stoppoint address.
2678 if (packet.GetBytesLeft() < 1)
2679 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2680 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002681
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2683 return SendIllFormedResponse(
2684 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002685
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 /*
2687 // Parse out the stoppoint size (i.e. size hint for opcode size).
2688 const uint32_t size = packet.GetHexMaxU32 (false,
2689 std::numeric_limits<uint32_t>::max ());
2690 if (size == std::numeric_limits<uint32_t>::max ())
2691 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2692 size argument");
2693 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 if (want_breakpoint) {
2696 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002697 const Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00002698 m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 if (error.Success())
2700 return SendOKResponse();
2701 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002702 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2703 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704 return SendErrorResponse(0x09);
2705 } else {
2706 // Try to clear the watchpoint.
Pavel Labath82abefa2017-07-18 09:24:48 +00002707 const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 if (error.Success())
2709 return SendOKResponse();
2710 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
Pavel Labath82abefa2017-07-18 09:24:48 +00002711 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2712 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 return SendErrorResponse(0x09);
2714 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002715}
2716
2717GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2719 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 // Ensure we have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002722 if (!m_debugged_process_up ||
2723 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002724 if (log)
2725 log->Printf(
2726 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2727 __FUNCTION__);
2728 return SendErrorResponse(0x32);
2729 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 // We first try to use a continue thread id. If any one or any all set, use
2732 // the current thread.
2733 // Bail out if we don't have a thread id.
2734 lldb::tid_t tid = GetContinueThreadID();
2735 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2736 tid = GetCurrentThreadID();
2737 if (tid == LLDB_INVALID_THREAD_ID)
2738 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002739
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 // Double check that we have such a thread.
2741 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
Pavel Labath82abefa2017-07-18 09:24:48 +00002742 NativeThreadProtocolSP thread_sp = m_debugged_process_up->GetThreadByID(tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 if (!thread_sp || thread_sp->GetID() != tid)
2744 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002745
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 // Create the step action for the given thread.
2747 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002748
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 // Setup the actions list.
2750 ResumeActionList actions;
2751 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002752
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 // All other threads stop while we're single stepping a thread.
2754 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Pavel Labath82abefa2017-07-18 09:24:48 +00002755 Status error = m_debugged_process_up->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 if (error.Fail()) {
2757 if (log)
2758 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2759 " tid %" PRIu64 " Resume() failed with error: %s",
Pavel Labath82abefa2017-07-18 09:24:48 +00002760 __FUNCTION__, m_debugged_process_up->GetID(), tid,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002761 error.AsCString());
2762 return SendErrorResponse(0x49);
2763 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002764
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 // No response here - the stop or exit will come from the resulting action.
2766 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002767}
2768
2769GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2771 StringExtractorGDBRemote &packet) {
2772// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002773#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 // Parse out the offset.
2777 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2778 if (packet.GetBytesLeft() < 1)
2779 return SendIllFormedResponse(packet,
2780 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 const uint64_t auxv_offset =
2783 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2784 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2785 return SendIllFormedResponse(packet,
2786 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002787
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 // Parse out comma.
2789 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2790 return SendIllFormedResponse(
2791 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002792
Kate Stoneb9c1b512016-09-06 20:57:50 +00002793 // Parse out the length.
2794 const uint64_t auxv_length =
2795 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2796 if (auxv_length == std::numeric_limits<uint64_t>::max())
2797 return SendIllFormedResponse(packet,
2798 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002799
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002801 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002802 // Make sure we have a valid process.
Pavel Labath82abefa2017-07-18 09:24:48 +00002803 if (!m_debugged_process_up ||
2804 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 if (log)
2806 log->Printf(
2807 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2808 __FUNCTION__);
2809 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002810 }
2811
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 // Grab the auxv data.
Pavel Labath82abefa2017-07-18 09:24:48 +00002813 auto buffer_or_error = m_debugged_process_up->GetAuxvData();
Pavel Labathb7f0f452017-03-17 11:08:40 +00002814 if (!buffer_or_error) {
2815 std::error_code ec = buffer_or_error.getError();
2816 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2817 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002818 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002819 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002820 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002821
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 StreamGDBRemote response;
2823 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002824
Pavel Labathb7f0f452017-03-17 11:08:40 +00002825 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2826 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 // We have nothing left to send. Mark the buffer as complete.
2828 response.PutChar('l');
2829 done_with_buffer = true;
2830 } else {
2831 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002832 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833
2834 // Mark the response type according to whether we're reading the remainder
2835 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002836 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 // There will be nothing left to read after this
2838 response.PutChar('l');
2839 done_with_buffer = true;
2840 } else {
2841 // There will still be bytes to read after this request.
2842 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002843 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002844 }
2845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002847 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002851 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852
2853 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002854#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002856#endif
2857}
2858
2859GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2861 StringExtractorGDBRemote &packet) {
2862 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002863
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 // Move past packet name.
2865 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002866
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 // Get the thread to use.
2868 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2869 if (!thread_sp) {
2870 if (m_thread_suffix_supported)
2871 return SendIllFormedResponse(
2872 packet, "No thread specified in QSaveRegisterState packet");
2873 else
2874 return SendIllFormedResponse(packet,
2875 "No thread was is set with the Hg packet");
2876 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002877
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 // Grab the register context for the thread.
2879 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2880 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002881 LLDB_LOG(
2882 log,
2883 "pid {0} tid {1} failed, no register context available for the thread",
2884 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885 return SendErrorResponse(0x15);
2886 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002887
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 // Save registers to a buffer.
2889 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00002890 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002892 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2893 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 return SendErrorResponse(0x75);
2895 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002896
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 // Allocate a new save id.
2898 const uint32_t save_id = GetNextSavedRegistersID();
2899 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2900 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002901
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 // Save the register data buffer under the save id.
2903 {
2904 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2905 m_saved_registers_map[save_id] = register_data_sp;
2906 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002907
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 // Write the response.
2909 StreamGDBRemote response;
2910 response.Printf("%" PRIu32, save_id);
2911 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002912}
2913
2914GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2916 StringExtractorGDBRemote &packet) {
2917 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002918
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 // Parse out save id.
2920 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2921 if (packet.GetBytesLeft() < 1)
2922 return SendIllFormedResponse(
2923 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 const uint32_t save_id = packet.GetU32(0);
2926 if (save_id == 0) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002927 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2928 "expecting decimal uint32_t");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 return SendErrorResponse(0x76);
2930 }
2931
2932 // Get the thread to use.
2933 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2934 if (!thread_sp) {
2935 if (m_thread_suffix_supported)
2936 return SendIllFormedResponse(
2937 packet, "No thread specified in QRestoreRegisterState packet");
2938 else
2939 return SendIllFormedResponse(packet,
2940 "No thread was is set with the Hg packet");
2941 }
2942
2943 // Grab the register context for the thread.
2944 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2945 if (!reg_context_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002946 LLDB_LOG(
2947 log,
2948 "pid {0} tid {1} failed, no register context available for the thread",
2949 m_debugged_process_up->GetID(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 return SendErrorResponse(0x15);
2951 }
2952
2953 // Retrieve register state buffer, then remove from the list.
2954 DataBufferSP register_data_sp;
2955 {
2956 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2957
2958 // Find the register set buffer for the given save id.
2959 auto it = m_saved_registers_map.find(save_id);
2960 if (it == m_saved_registers_map.end()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002961 LLDB_LOG(log,
2962 "pid {0} does not have a register set save buffer for id {1}",
2963 m_debugged_process_up->GetID(), save_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002965 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002967
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 // Remove it from the map.
2969 m_saved_registers_map.erase(it);
2970 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002971
Zachary Turner97206d52017-05-12 04:51:55 +00002972 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 if (error.Fail()) {
Pavel Labath82abefa2017-07-18 09:24:48 +00002974 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2975 m_debugged_process_up->GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 return SendErrorResponse(0x77);
2977 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002978
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002980}
2981
2982GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2984 StringExtractorGDBRemote &packet) {
2985 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 // Consume the ';' after vAttach.
2988 packet.SetFilePos(strlen("vAttach"));
2989 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2990 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002991
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 // Grab the PID to which we will attach (assume hex encoding).
2993 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2994 if (pid == LLDB_INVALID_PROCESS_ID)
2995 return SendIllFormedResponse(packet,
2996 "vAttach failed to parse the process id");
2997
2998 // Attempt to attach.
2999 if (log)
3000 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3001 "pid %" PRIu64,
3002 __FUNCTION__, pid);
3003
Zachary Turner97206d52017-05-12 04:51:55 +00003004 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005
3006 if (error.Fail()) {
3007 if (log)
3008 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3009 "pid %" PRIu64 ": %s\n",
3010 __FUNCTION__, pid, error.AsCString());
3011 return SendErrorResponse(0x01);
3012 }
3013
3014 // Notify we attached by sending a stop packet.
Pavel Labath82abefa2017-07-18 09:24:48 +00003015 return SendStopReasonForState(m_debugged_process_up->GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016}
3017
3018GDBRemoteCommunication::PacketResult
3019GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3020 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3021
3022 StopSTDIOForwarding();
3023
3024 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003025 if (!m_debugged_process_up ||
3026 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 if (log)
3028 log->Printf(
3029 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3030 __FUNCTION__);
3031 return SendErrorResponse(0x15);
3032 }
3033
3034 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3035
3036 // Consume the ';' after D.
3037 packet.SetFilePos(1);
3038 if (packet.GetBytesLeft()) {
3039 if (packet.GetChar() != ';')
3040 return SendIllFormedResponse(packet, "D missing expected ';'");
3041
3042 // Grab the PID from which we will detach (assume hex encoding).
3043 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003044 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003045 return SendIllFormedResponse(packet, "D failed to parse the process id");
3046 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003047
Pavel Labath82abefa2017-07-18 09:24:48 +00003048 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 return SendIllFormedResponse(packet, "Invalid pid");
3050 }
3051
Pavel Labath82abefa2017-07-18 09:24:48 +00003052 const Status error = m_debugged_process_up->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003054 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3056 "pid %" PRIu64 ": %s\n",
Pavel Labath82abefa2017-07-18 09:24:48 +00003057 __FUNCTION__, m_debugged_process_up->GetID(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003058 error.AsCString());
3059 return SendErrorResponse(0x01);
3060 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003061
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003063}
3064
3065GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3067 StringExtractorGDBRemote &packet) {
3068 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003069
Kate Stoneb9c1b512016-09-06 20:57:50 +00003070 packet.SetFilePos(strlen("qThreadStopInfo"));
3071 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3072 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003073 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3075 "parse thread id from request \"%s\"",
3076 __FUNCTION__, packet.GetStringRef().c_str());
3077 return SendErrorResponse(0x15);
3078 }
3079 return SendStopReplyPacketForThread(tid);
3080}
3081
3082GDBRemoteCommunication::PacketResult
3083GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3084 StringExtractorGDBRemote &) {
3085 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3086
3087 // Ensure we have a debugged process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003088 if (!m_debugged_process_up ||
3089 (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 return SendErrorResponse(50);
Pavel Labath82abefa2017-07-18 09:24:48 +00003091 LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003092
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 StreamString response;
3094 const bool threads_with_valid_stop_info_only = false;
3095 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
Pavel Labath82abefa2017-07-18 09:24:48 +00003096 *m_debugged_process_up, threads_with_valid_stop_info_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 if (!threads_array_sp) {
Pavel Labath82abefa2017-07-18 09:24:48 +00003098 LLDB_LOG(log, "failed to prepare a packet for pid {0}",
3099 m_debugged_process_up->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 return SendErrorResponse(52);
3101 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 threads_array_sp->Write(response);
3104 StreamGDBRemote escaped_response;
3105 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3106 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003107}
3108
3109GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3111 StringExtractorGDBRemote &packet) {
3112 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003113 if (!m_debugged_process_up ||
3114 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3118 if (packet.GetBytesLeft() == 0)
3119 return SendOKResponse();
3120 if (packet.GetChar() != ':')
3121 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003122
Pavel Labath82abefa2017-07-18 09:24:48 +00003123 auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003124
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003126 if (hw_debug_cap == llvm::None)
3127 response.Printf("num:0;");
3128 else
3129 response.Printf("num:%d;", hw_debug_cap->second);
3130
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003132}
3133
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003134GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3136 StringExtractorGDBRemote &packet) {
3137 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003138 if (!m_debugged_process_up ||
3139 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003141
Kate Stoneb9c1b512016-09-06 20:57:50 +00003142 packet.SetFilePos(strlen("qFileLoadAddress:"));
3143 if (packet.GetBytesLeft() == 0)
3144 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003145
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 std::string file_name;
3147 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003148
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003150 Status error =
Pavel Labath82abefa2017-07-18 09:24:48 +00003151 m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 if (error.Fail())
3153 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003154
Kate Stoneb9c1b512016-09-06 20:57:50 +00003155 if (file_load_address == LLDB_INVALID_ADDRESS)
3156 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003157
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158 StreamGDBRemote response;
3159 response.PutHex64(file_load_address);
3160 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003161}
3162
Pavel Labath4a705e72017-02-24 09:29:14 +00003163GDBRemoteCommunication::PacketResult
3164GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3165 StringExtractorGDBRemote &packet) {
3166 std::vector<int> signals;
3167 packet.SetFilePos(strlen("QPassSignals:"));
3168
3169 // Read sequence of hex signal numbers divided by a semicolon and
3170 // optionally spaces.
3171 while (packet.GetBytesLeft() > 0) {
3172 int signal = packet.GetS32(-1, 16);
3173 if (signal < 0)
3174 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3175 signals.push_back(signal);
3176
3177 packet.SkipSpaces();
3178 char separator = packet.GetChar();
3179 if (separator == '\0')
3180 break; // End of string
3181 if (separator != ';')
3182 return SendIllFormedResponse(packet, "Invalid separator,"
3183 " expected semicolon.");
3184 }
3185
3186 // Fail if we don't have a current process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003187 if (!m_debugged_process_up)
Pavel Labath4a705e72017-02-24 09:29:14 +00003188 return SendErrorResponse(68);
3189
Pavel Labath82abefa2017-07-18 09:24:48 +00003190 Status error = m_debugged_process_up->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003191 if (error.Fail())
3192 return SendErrorResponse(69);
3193
3194 return SendOKResponse();
3195}
3196
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3198 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003199
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 // Tell the stdio connection to shut down.
3201 if (m_stdio_communication.IsConnected()) {
3202 auto connection = m_stdio_communication.GetConnection();
3203 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003204 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003206
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 if (error.Success()) {
3208 if (log)
3209 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3210 "terminal stdio - SUCCESS",
3211 __FUNCTION__);
3212 } else {
3213 if (log)
3214 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3215 "terminal stdio - FAIL: %s",
3216 __FUNCTION__, error.AsCString());
3217 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003218 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003219 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003220}
3221
Kate Stoneb9c1b512016-09-06 20:57:50 +00003222NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3223 StringExtractorGDBRemote &packet) {
3224 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003225
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226 // We have no thread if we don't have a process.
Pavel Labath82abefa2017-07-18 09:24:48 +00003227 if (!m_debugged_process_up ||
3228 m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003229 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003230
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231 // If the client hasn't asked for thread suffix support, there will not be a
3232 // thread suffix.
3233 // Use the current thread in that case.
3234 if (!m_thread_suffix_supported) {
3235 const lldb::tid_t current_tid = GetCurrentThreadID();
3236 if (current_tid == LLDB_INVALID_THREAD_ID)
3237 return thread_sp;
3238 else if (current_tid == 0) {
3239 // Pick a thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00003240 return m_debugged_process_up->GetThreadAtIndex(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003241 } else
Pavel Labath82abefa2017-07-18 09:24:48 +00003242 return m_debugged_process_up->GetThreadByID(current_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003244
Kate Stoneb9c1b512016-09-06 20:57:50 +00003245 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003246
Kate Stoneb9c1b512016-09-06 20:57:50 +00003247 // Parse out the ';'.
3248 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003249 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3251 "error: expected ';' prior to start of thread suffix: packet "
3252 "contents = '%s'",
3253 __FUNCTION__, packet.GetStringRef().c_str());
3254 return thread_sp;
3255 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003256
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257 if (!packet.GetBytesLeft())
3258 return thread_sp;
3259
3260 // Parse out thread: portion.
3261 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3262 if (log)
3263 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3264 "error: expected 'thread:' but not found, packet contents = "
3265 "'%s'",
3266 __FUNCTION__, packet.GetStringRef().c_str());
3267 return thread_sp;
3268 }
3269 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3270 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3271 if (tid != 0)
Pavel Labath82abefa2017-07-18 09:24:48 +00003272 return m_debugged_process_up->GetThreadByID(tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273
3274 return thread_sp;
3275}
3276
3277lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3278 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3279 // Use whatever the debug process says is the current thread id
3280 // since the protocol either didn't specify or specified we want
3281 // any/all threads marked as the current thread.
Pavel Labath82abefa2017-07-18 09:24:48 +00003282 if (!m_debugged_process_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283 return LLDB_INVALID_THREAD_ID;
Pavel Labath82abefa2017-07-18 09:24:48 +00003284 return m_debugged_process_up->GetCurrentThreadID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285 }
3286 // Use the specific current thread id set by the gdb remote protocol.
3287 return m_current_tid;
3288}
3289
3290uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3291 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3292 return m_next_saved_registers_id++;
3293}
3294
3295void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003296 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297
Pavel Labathb7f0f452017-03-17 11:08:40 +00003298 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3299 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003300}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003301
3302FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3304 const ArchSpec &arch) {
Pavel Labath82abefa2017-07-18 09:24:48 +00003305 if (m_debugged_process_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003306 FileSpec file_spec;
Pavel Labath82abefa2017-07-18 09:24:48 +00003307 if (m_debugged_process_up
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3309 .Success()) {
3310 if (file_spec.Exists())
3311 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003313 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003314
Kate Stoneb9c1b512016-09-06 20:57:50 +00003315 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003316}